---
title: "Tool Metrics and Performance: Tracking Execution Latency and Failure Rates"
date: "2026-11-29T08:55:09+07:00"
description: "Instrument Google ADK tool executions with OpenTelemetry and custom callbacks to monitor execution latency, error taxonomy, and degraded upstream dependencies."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/adk-tool-metrics-latency-failure-rates.jpg"
alt: "Google ADK Tool Metrics Latency and Failure Monitoring"
tags: ['google-adk', 'observability', 'metrics', 'opentelemetry', 'python']
---

In enterprise AI agent systems, tools are the single largest source of unpredictable latency and operational failures. While model inference latency is relatively stable for a given token count, external tools talk to third-party payment gateways, internal microservices, relational databases, and web scrapers—all subject to network timeouts, rate limits, and service degradation.

If an agent turn takes 12 seconds instead of 1.5 seconds, developers must quickly determine whether the delay came from the model's reasoning chain or an unresponsive downstream API.

In this tutorial, we will instrument tool calls in Google Agent Development Kit (ADK) using custom lifecycle callbacks and OpenTelemetry to track execution latency, failure rates, and error taxonomy in real time.

---

## 1. Observability Architecture for ADK Tools

Google ADK provides native lifecycle hooks for agents: `before_tool_callback` and `after_tool_callback`. By tapping into these hooks, we can observe every tool invocation without modifying individual tool functions.

```
+--------------------------------------------------------------+
|                     ADK Execution Loop                       |
|                                                              |
|   1. Model emits ToolCall: search_customer_db(id=941)        |
|                                                              |
|   2. Trigger before_tool_callback                            |
|      - Start timer (time.perf_counter())                     |
|      - Open OpenTelemetry Span ("tool:search_customer_db")   |
|                                                              |
|   3. Tool Function Executes                                  |
|      - Queries Postgres / External REST API                  |
|                                                              |
|   4. Trigger after_tool_callback                             |
|      - Record execution duration                             |
|      - Classify outcome (Success, Timeout, 4xx, 5xx)         |
|      - Emit metrics to Prometheus / Cloud Monitoring         |
|      - Close Span                                            |
+--------------------------------------------------------------+
```

---

## 2. Implementing Callback-Based Tool Metrics Collector

Let's build a dedicated `ToolMetricsCollector` that records latency histograms and failure counters:

```python
import time
from typing import Dict, Any, Optional
from dataclasses import dataclass, field
from collections import defaultdict

@dataclass
class ToolExecutionRecord:
    tool_name: str
    duration_ms: float
    success: bool
    error_type: Optional[str] = None

class ToolMetricsCollector:
    """In-memory telemetry collector for ADK tool performance."""

    def __init__(self):
        self.invocations: Dict[str, int] = defaultdict(int)
        self.failures: Dict[str, int] = defaultdict(int)
        self.latencies: Dict[str, list[float]] = defaultdict(list)

    def record_execution(self, record: ToolExecutionRecord):
        self.invocations[record.tool_name] += 1
        self.latencies[record.tool_name].append(record.duration_ms)
        if not record.success:
            self.failures[record.tool_name] += 1

    def get_summary(self) -> Dict[str, Any]:
        summary = {}
        for tool, count in self.invocations.items():
            lats = sorted(self.latencies[tool])
            p50 = lats[int(len(lats) * 0.50)] if lats else 0.0
            p95 = lats[int(len(lats) * 0.95)] if lats else 0.0
            fail_count = self.failures[tool]

            summary[tool] = {
                "total_calls": count,
                "failure_count": fail_count,
                "failure_rate": f"{(fail_count / count) * 100:.2f}%",
                "p50_latency_ms": round(p50, 2),
                "p95_latency_ms": round(p95, 2),
            }
        return summary

metrics_collector = ToolMetricsCollector()
```

---

## 3. Wiring Callbacks into Google ADK Agents

We now attach our callbacks to the ADK `Agent` definition:

```python
from google.adk.agents import Agent
from google.adk.agents.invocation_context import InvocationContext

def tool_telemetry_before_hook(
    tool_name: str,
    tool_args: Dict[str, Any],
    ctx: InvocationContext
) -> None:
    """Executes immediately before a tool is invoked."""
    # Stash start timestamp in session state or invocation metadata
    ctx.session.state[f"_perf_start_{tool_name}"] = time.perf_counter()

def tool_telemetry_after_hook(
    tool_name: str,
    tool_args: Dict[str, Any],
    tool_result: Any,
    ctx: InvocationContext
) -> None:
    """Executes immediately after a tool finishes execution."""
    start_time = ctx.session.state.pop(f"_perf_start_{tool_name}", None)
    if start_time is None:
        return

    duration_ms = (time.perf_counter() - start_time) * 1000.0

    # Determine success status from result payload
    is_success = True
    error_type = None

    if isinstance(tool_result, dict):
        if tool_result.get("status") in ("error", "failed"):
            is_success = False
            error_type = tool_result.get("error_code", "generic_tool_error")
    elif isinstance(tool_result, Exception):
        is_success = False
        error_type = type(tool_result).__name__

    record = ToolExecutionRecord(
        tool_name=tool_name,
        duration_ms=duration_ms,
        success=is_success,
        error_type=error_type,
    )
    metrics_collector.record_execution(record)

    # Optional: Log warning if tool exceeds SLA threshold
    if duration_ms > 2000:
        print(f"[LATENCY WARNING] Tool '{tool_name}' took {duration_ms:.1f}ms to complete!")
```

---

## 4. OpenTelemetry Spans for Distributed Tracing

For enterprise deployments running on Google Cloud Run or Kubernetes, export your spans directly to Cloud Trace using OpenTelemetry:

```python
from opentelemetry import trace
from opentelemetry.trace import Status, StatusCode

tracer = trace.get_tracer("adk.tools.instrumentation")

def otel_tool_wrapper(func):
    """Decorator to wrap tool functions in an OpenTelemetry span."""
    async def wrapper(*args, **kwargs):
        tool_name = func.__name__
        with tracer.start_as_current_span(f"adk.tool.{tool_name}") as span:
            span.set_attribute("tool.name", tool_name)
            try:
                result = await func(*args, **kwargs) if asyncio.iscoroutinefunction(func) else func(*args, **kwargs)
                span.set_status(Status(StatusCode.OK))
                return result
            except Exception as exc:
                span.record_exception(exc)
                span.set_status(Status(StatusCode.ERROR, description=str(exc)))
                raise
    return wrapper
```

---

## 5. Instrumenting the Agent Configuration

```python
# Sample mock tool
def query_inventory_db(item_id: str) -> Dict[str, Any]:
    """Queries warehouse inventory database."""
    time.sleep(0.12)  # Simulate network latency
    return {"status": "success", "item_id": item_id, "in_stock": 42}

monitored_agent = Agent(
    name="inventory_bot",
    model="gemini-3.8-flash",
    instruction="Assist users with inventory lookups using `query_inventory_db`.",
    tools=[query_inventory_db],
    before_tool_callback=tool_telemetry_before_hook,
    after_tool_callback=tool_telemetry_after_hook,
)
```

### Inspecting Performance Summaries

After processing multiple user requests, query the collector's health summary:

```python
print(metrics_collector.get_summary())
# Output:
# {
#   'query_inventory_db': {
#       'total_calls': 150,
#       'failure_count': 3,
#       'failure_rate': '2.00%',
#       'p50_latency_ms': 122.45,
#       'p95_latency_ms': 210.18
#   }
# }
```

---

## 6. Key Takeaways for Production Deployments

1. **Set Hard Timeouts:** Never let an external tool hang indefinitely. Wrap HTTP requests in 5–10 second client timeouts.
2. **Circuit Breakers:** If a tool's failure rate exceeds 25% over a 5-minute rolling window, trip a circuit breaker so the agent immediately uses a cached fallback or notifies the user without stalling.
3. **Decouple Metric Publishing:** Push telemetry asynchronously (via OpenTelemetry BatchSpanProcessor or background daemon) so logging never degrades agent response times.

**Takeaway:** Instrumenting tool lifecycles with ADK callbacks provides immediate visibility into upstream bottlenecks, ensuring responsive and reliable agent workflows.

## Sources
- Google ADK Documentation: https://adk.dev/
- OpenTelemetry Python SDK: https://opentelemetry.io/docs/languages/python/
- Google Cloud Trace Documentation: https://cloud.google.com/trace
