---
title: "Rate-Limiting External Tool Calls to Protect Upstream Services"
date: "2026-11-28T12:15:00+07:00"
description: "How to safeguard third-party APIs and downstream services by enforcing token-bucket rate limits, concurrency semaphores, and exponential backoff inside ADK tools."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/rate-limiting-external-tool-calls.jpg"
alt: "Digital traffic control valve throttling high-frequency data packets"
tags: ['google-adk', 'adk-tools', 'rate-limiting', 'concurrency', 'resilience', 'api-design']
---

When an autonomous agent loops through parallel sub-tasks or complex query plans, it can fire dozens of tool invocations within seconds. While foundation model APIs have their own request-per-minute (RPM) quotas, your third-party backends—CRM endpoints, payment processors, geocoding providers, and private databases—rarely tolerate unfiltered bursts. Without rate-limiting, an enthusiastic agent can exhaust partner API quotas or trigger instant IP blocks.

This tutorial covers the architectural distinction between LLM rate limits and tool rate limits, implementing in-memory token buckets, concurrency caps with `asyncio.Semaphore`, and translating upstream HTTP 429 responses into recoverable guidance for the model.

## Model rate limits vs tool rate limits

Architects frequently confuse model-tier rate limits with tool-tier constraints:

| Dimension | Model rate limits | Tool rate limits |
|---|---|---|
| **Governed resource** | Gemini / LLM inference tokens & RPM | Third-party REST/gRPC endpoints |
| **Enforcement layer** | GenAI SDK client / Vertex AI Gateway | Tool wrapper or middleware interceptor |
| **Response on breach** | Exponential backoff before prompt completion | Informative feedback returned into tool context |
| **Concurrency risk** | Parallel agent turns | Parallel tool fan-out across worker instances |
| **Cost impact** | Wasted token generation | External billing penalties or account bans |

Model rate limits protect the LLM link; tool rate limits protect your external infrastructure from agent-induced denial of service.

## Enforcing concurrency limits with `asyncio.Semaphore`

The simplest rate limiter prevents burst saturation by bounding how many concurrent calls can hit an upstream service simultaneously:

```python
import asyncio
from google.adk.tools import ToolContext

# Allow maximum 3 concurrent calls to the external search API
SEARCH_SEMAPHORE = asyncio.Semaphore(3)

async def query_crm_records(query: str, ctx: ToolContext) -> dict:
    """Search enterprise CRM customer records.

    Args:
        query (str): The search keywords or account names.
    """
    async with SEARCH_SEMAPHORE:
        # Downstream call is throttled against concurrent stampedes
        result = await crm_client.search_accounts(query)
        return {"status": "success", "count": len(result), "records": result[:5]}
```

If multiple parallel sub-agents invoke `query_crm_records`, the fourth and subsequent calls wait gracefully until an earlier call finishes.

## Building a token-bucket rate limiter for tools

To enforce strict request-per-second (RPS) limits, implement an async token bucket that refills tokens continuously:

```python
import time
import asyncio

class AsyncTokenBucket:
    def __init__(self, rate_per_second: float, capacity: float):
        self.rate = rate_per_second
        self.capacity = capacity
        self.tokens = capacity
        self.last_update = time.monotonic()
        self._lock = asyncio.Lock()

    async def acquire(self):
        async with self._lock:
            while True:
                now = time.monotonic()
                elapsed = now - self.last_update
                self.tokens = min(self.capacity, self.tokens + elapsed * self.rate)
                self.last_update = now

                if self.tokens >= 1.0:
                    self.tokens -= 1.0
                    return
                # Wait until enough time passes for 1 token to regenerate
                needed = (1.0 - self.tokens) / self.rate
                await asyncio.sleep(needed)

# Enforce 5 calls per second with a burst burst capacity of 10
WEATHER_LIMITER = AsyncTokenBucket(rate_per_second=5.0, capacity=10.0)

async def get_geocoding_coordinates(location: str) -> dict:
    """Resolve coordinates for a location string."""
    await WEATHER_LIMITER.acquire()
    return await external_maps_api.geocode(location)
```

## Surfacing upstream 429s as recoverable guidance

When an external service returns HTTP 429 despite local controls, never crash the agent turn with an uncaught exception. Instead, surface a structured response that informs the model to pause or adjust strategy:

```python
import httpx
from tenacity import retry, stop_after_attempt, wait_exponential_jitter, retry_if_exception_type

@retry(
    stop=stop_after_attempt(3),
    wait=wait_exponential_jitter(initial=1, max=10),
    retry=retry_if_exception_type(httpx.HTTPStatusError),
    reraise=False
)
async def call_payment_gateway(payload: dict) -> dict:
    response = await httpx.post("https://api.payments.com/v1/charge", json=payload)
    response.raise_for_status()
    return response.json()

async def execute_charge(account_id: str, amount_cents: int) -> dict:
    """Initiate a debit charge for an account."""
    try:
        data = await call_payment_gateway({"account": account_id, "amount": amount_cents})
        return {"status": "success", "charge_id": data["id"]}
    except Exception as exc:
        # Provide clean, actionable context back to LLM
        return {
            "status": "rate_limited",
            "error_message": "Payment gateway is currently experiencing high load. Do not retry this charge immediately. Inform the user and suggest checking back in 1 minute."
        }
```

By returning `status: "rate_limited"` with clear guidance, the agent explains the delay to the user rather than entering an infinite retry hallucination.

## Takeaways

- Protect downstream third-party systems from agent burst loops using tool-level rate limiters.
- Use `asyncio.Semaphore` to cap concurrent outgoing connections per worker.
- Implement token-bucket algorithms to smoothly pace outbound requests under fixed vendor RPS ceilings.
- Catch HTTP 429 exceptions inside tools and return structured messages explaining that the service is congested.
- Keep exponential backoff bounded with jitter to prevent retry storms against recovering external endpoints.

## Further reading

- [Synchronous vs Asynchronous Tool Implementations in ADK](/blog/sync-vs-async-tools-adk)
- [Handling Tool Errors and Recoverable Exceptions](/blog/adk-tool-errors-recoverable-exceptions)
- [Handling Rate Limits (429) and Quota Exhaustion with Exponential Backoff](/blog/adk-rate-limits-429-exponential-backoff)
- [Caching Tool Responses to Eliminate Duplicate Expensive Calls](/blog/caching-tool-responses-adk)
- [Google ADK Documentation on Tools](https://adk.dev/tools-custom/)
