---
title: "Monitoring Context Window Utilization and Prompt Bloat with ADK Tracing"
date: "2026-12-05T08:08:00+07:00"
description: "How to trace token accumulation, detect prompt bloat, and instrument telemetry across long-running Google ADK agent sessions using OpenTelemetry and Cloud Trace."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/adk-monitoring-context-utilization-prompt-bloat-tracing.jpg"
alt: "Monitoring Context Window Utilization in Google ADK"
tags: ['google-adk', 'observability', 'tracing', 'opentelemetry', 'python']
---

In autonomous agent development, long-running loops often exhibit **context drift and prompt bloat**: multi-turn sessions silently accumulate thousands of tokens of history, unpruned tool payloads, and intermediate scratchpads.

Without granular telemetry, teams only discover prompt bloat when cloud billing spikes or when latency degrades unacceptably.

Google Agent Development Kit (ADK) includes built-in tracing interfaces that integrate seamlessly with OpenTelemetry, Google Cloud Trace, and BigQuery Agent Analytics. In this tutorial, we will instrument an ADK agent to monitor context window consumption turn-by-turn.

---

### Context Telemetry Architecture

```
User Turn ──► ADK Runner Pipeline
                     │
                     ▼
       ┌───────────────────────────────┐
       │   InvocationContext Tracing   │
       │   - System Prompt Tokens      │
       │   - Tool Schema Tokens        │
       │   - Conversation History      │
       │   - Output Generation Tokens  │
       └──────────────┬────────────────┘
                      │
            ┌─────────┴─────────┐
            ▼                   ▼
    Google Cloud Trace     Prometheus / OTel
   (Span-level latency)  (Turn-by-turn metrics)
```

---

### Instrumentation with ADK Middleware Hooks

We can capture token allocation across each turn of the ADK Runner by subscribing to runner event lifecycles:

```python
import time
from typing import Dict, Any
from google_adk.runners import RunnerMiddleware
from google_adk.events import AgentEvent

class ContextTelemetryMiddleware(RunnerMiddleware):
    def __init__(self, warning_threshold_tokens: int = 50000):
        self.warning_threshold = warning_threshold_tokens

    async def before_agent_turn(self, context: Dict[str, Any], prompt_parts: list):
        """Captures context breakdown before sending request to Gemini."""
        context["_turn_start_time"] = time.perf_counter()
        # Estimate or count prompt tokens
        estimated_input_chars = sum(len(str(p)) for p in prompt_parts)
        context["_est_input_tokens"] = estimated_input_chars // 4

    async def after_agent_turn(self, context: Dict[str, Any], event: AgentEvent):
        """Extracts exact token usage metadata from Gemini response."""
        duration = time.perf_counter() - context.get("_turn_start_time", 0)
        
        usage = getattr(event, "usage_metadata", None)
        if not usage:
            return

        prompt_tokens = usage.prompt_token_count
        candidates_tokens = usage.candidates_token_count
        total_tokens = usage.total_token_count
        cached_tokens = getattr(usage, "cached_content_token_count", 0)

        metrics = {
            "session_id": context.get("session_id", "unknown"),
            "agent_name": context.get("agent_name", "unknown"),
            "prompt_tokens": prompt_tokens,
            "completion_tokens": candidates_tokens,
            "total_tokens": total_tokens,
            "cached_tokens": cached_tokens,
            "latency_seconds": round(duration, 3)
        }

        # Emit telemetry log
        self._record_metric(metrics)

        # Alert on prompt bloat
        if prompt_tokens > self.warning_threshold:
            print(f"⚠️ [PROMPT BLOAT ALERT] Session {metrics['session_id']} reached {prompt_tokens} tokens!")

    def _record_metric(self, metrics: dict):
        # In production, dispatch to OpenTelemetry Counter or Cloud Logging
        print(f"📊 [TRACE] Turn finished: {metrics['prompt_tokens']} in / {metrics['completion_tokens']} out | Latency: {metrics['latency_seconds']}s")
```

---

### Exporting Metrics to Cloud Trace and OpenTelemetry

When deploying to Google Cloud Run or GKE, ADK supports native OpenTelemetry exporters:

```python
from opentelemetry import trace
from opentelemetry.exporter.cloud_trace import CloudTraceSpanExporter
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor

# Initialize OpenTelemetry Cloud Trace Provider
provider = TracerProvider()
processor = BatchSpanProcessor(CloudTraceSpanExporter())
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)

tracer = trace.get_tracer("adk-context-monitor")

def trace_context_turn(session_id: str, prompt_tokens: int, duration_ms: float):
    with tracer.start_as_current_span("adk.agent.turn") as span:
        span.set_attribute("session.id", session_id)
        span.set_attribute("tokens.prompt", prompt_tokens)
        span.set_attribute("latency.ms", duration_ms)
        if prompt_tokens > 64000:
            span.set_attribute("risk.bloat", True)
```

---

### Key Metrics to Monitor in Production

| Metric | Threshold Alert | Cause | Remediation |
|---|---|---|---|
| **Prompt Token Growth Rate** | `> 2,000 tokens/turn` | Unpruned tool outputs / verbose logs | Truncate tool returns or compress to TSV |
| **Cache Hit Ratio** | `< 60%` | Invariant prefixes being mutated | Re-order prompts to keep invariant prefix stable |
| **TTFT (Time-to-First-Token)** | `> 2,500 ms` | Oversized context window | Implement sliding-window history pruning |
| **Dead Turn Waste** | `> 5 failed retries` | Agent caught in repetitive loop | Set `max_turns` limit on Runner |

---

### Conclusion

Instrumenting telemetry into the ADK context pipeline provides early visibility into token accumulation patterns. With proactive alerts on prompt bloat, you maintain fast, cost-efficient, and predictable AI agents in production.
