
Your Agent Has No Brakes: Rate-Limiting AI Traffic at the Gateway Layer
How to stop noisy tenants and runaway tool loops from burning your budget, without adding throttling code to every agent.
The 2 a.m. bill
Picture a composite of what I've seen. A SaaS platform launches an AI assistant. All tenants share one AWS account and one set of model quotas. For a few weeks everything is fine. Then one night a large tenant runs a batch job that sends thousands of agent requests. In the same week, a bug in a tool response makes an agent retry the same call in a loop. Nobody notices until two things happen:
- Every other tenant starts getting throttling errors, because the shared quota is used up.
- The monthly inference bill comes in far above forecast.
Neither problem is really about the model. They're both about missing limits. Traditional APIs have had rate limits for decades. Agents usually don't, even though they're more likely to produce unbounded traffic: one user prompt can fan out into dozens of tool calls and model invocations.
This post covers the two failure modes I see most often, and how to handle both at one choke point: the gateway.
Two problems, one root cause
1. The noisy neighbor
In a multi-tenant app, tenants usually share account-level quotas such as tokens per minute (TPM) and requests per minute (RPM). Those quotas know nothing about tenants. If one tenant uses the whole bucket, everyone else waits.
The first fix most teams try is custom throttling in the application: a Redis counter, a middleware layer, a token bucket per tenant. It works at first. But you end up building it again for every agent, every tool, and every new team that ships on your platform.
2. The runaway agent
Agents run in loops: reason, call a tool, read the result, repeat. That loop is the whole point, and it's also the risk. A bad tool response, an ambiguous instruction, or a hallucinated "let me try again" can produce:
- the same tool called hundreds of times,
- context windows that keep growing, with each call costing more tokens than the last,
- long streaming connections that never get released.
Retry logic in agent SDKs is meant for transient failures. It isn't a budget control. You need a hard ceiling outside the agent's own reasoning.
The root cause is the same in both cases: traffic limits live inside each application, if they exist at all, rather than at a shared entry point.
Why the gateway is the right place
If all AI traffic (model inference, MCP tools, other agents, HTTP APIs) goes through one gateway, the gateway sees every request, along with who sent it and where it's going. That makes it the natural place to enforce limits:
- One policy, many agents. Platform teams set limits once, and every agent behind the gateway gets them.
- Identity-aware. The gateway has already authenticated the caller, so it can limit by tenant, user, or role.
- Target-aware. It knows which tool, model, or downstream service is being called, so it can protect fragile backends too.

Every request must pass every applicable limit. Noisy callers are capped in their own buckets, so other tenants keep working.
Amazon Bedrock AgentCore Gateway added native rate limiting in August 2026, and its design maps closely to these needs. The AWS launch post is the reference walkthrough. Below I go through the concepts and how I'd apply them to the two problems above.
The three things you can limit
AgentCore Gateway supports three metrics, and each one stops a different failure:
Metric | What it measures | Applies to | What it stops |
|---|---|---|---|
Requests (RPS / RPM) | Number of calls in a time window | All targets (MCP, inference, HTTP) | Tool-call loops, request floods |
Tokens (TPM) | Input + output tokens | Inference targets only | Budget blowouts, expanding contexts |
Connections (CPS) | Concurrent open connections, held for the full duration | All targets | Long streaming sessions tying up capacity |
A useful detail on tokens: the gateway estimates input tokens before sending the request, deducts them up front, and then reconciles against the actual input and output usage once the model responds. So a request whose input estimate doesn't fit the remaining budget is rejected before you pay for it. Output tokens, however, are only counted after the response comes back. While long-running calls are in flight, they hold only their estimated cost, so many concurrent calls with long outputs can temporarily push usage past the limit until reconciliation catches up.
The difference between requests and connections is also important. A 50 ms request and a 90-second streaming request each count as one request. But the streaming one holds a connection the whole time. If your agents stream heavily, request limits alone won't protect you.
How the limits are structured: dimensions and entries
Each rate limit has two parts:
- Dimension keys define how traffic is grouped into buckets. Examples include
targetName,toolName,qualifiedModelId, a JWT claim such as$.context.jwt.tenant_id, or an IAM principal.
- Entries define the allowed rate for each bucket. An entry can name a specific value (for example, the
enterprisetier) or use the wildcard*, which gives each distinct value its own separate bucket at that rate.
Two rules make this work well:
- The most specific match wins. A named entry overrides the wildcard.
- Multiple limits are combined with AND. A request must pass every applicable limit. That lets you stack ceilings by tenant, user, and target.
Pattern 1: Fixing the noisy neighbor
The goal is that no single tenant can use up the shared capacity.
Assume your identity provider puts a
tenant_id claim and a tier claim in each JWT. Start with a per-tenant ceiling, using the wildcard so every tenant gets its own bucket:aws bedrock-agentcore-control create-gateway-rate-limit \ --gateway-identifier <your-gateway-id> \ --dimension-keys '["$.context.jwt.tenant_id"]' \ --description "Per-tenant ceiling" \ --entries '[ { "dimensions": {"$.context.jwt.tenant_id": "*"}, "requests": [{"rate": 600, "period": "minute"}], "connections": [{"rate": 50, "period": "second"}] } ]'Now one tenant's batch job can only use up its own 600 RPM. Everyone else keeps working.
Then tier it, so paying customers get more headroom. Token limits only apply to inference traffic, so this one budgets model usage:
# Abbreviated: same create-gateway-rate-limit command as above--dimension-keys '["$.context.jwt.tier"]'--entries '[ {"dimensions": {"$.context.jwt.tier": "enterprise"}, "tokens": [{"rate": 200000, "period": "minute"}]}, {"dimensions": {"$.context.jwt.tier": "standard"}, "tokens": [{"rate": 50000, "period": "minute"}]}, {"dimensions": {"$.context.jwt.tier": "*"}, "tokens": [{"rate": 10000, "period": "minute"}]}]'Finally, guard against one user starving the rest of their own tenant by adding a second limit keyed on
tenant_id + sub . Because limits are combined with AND, you get a two-layer model:- the tenant ceiling protects tenants from each other, and
- the per-user ceiling protects users within the same tenant.
Watch for missing claims: if a request's token doesn't contain the claim a limit is keyed on (say, notenant_id), the gateway can't resolve that dimension and skips the limit for that request. It doesn't block it. Make sure your IdP always issues the claims you key on, and keep a broader catch-all limit (for example, per target) as a backstop.
Tip: Use simple, stable claim names (for example,tenant_id,tier) for the values you key limits on, and check how your identity provider names custom claims. If a claim is an array (such as a list of roles), each entry has to match the JSON-encoded array exactly, so every combination needs its own entry. Only claims from tokens the gateway has validated are used.
Pattern 2: Putting brakes on runaway agents
The goal is a hard ceiling on how much one agent session can consume, whatever the model "decides" to do.
Agentic workloads need limits at two levels.
Level 1: How often the agent can be invoked. Limit invocations of the agent target itself, per user:
# Abbreviated: same create-gateway-rate-limit command as above--dimension-keys '["targetName", "$.context.jwt.sub"]'--entries '[ {"dimensions": {"targetName": "research-agent", "$.context.jwt.sub": "*"}, "requests": [{"rate": 30, "period": "minute"}]}]'Level 2: What the agent consumes downstream. This is where loops get caught. Use
toolName to cap individual tools, and qualifiedModelId to cap token usage per model:# Abbreviated. toolName format is <targetName>___<toolName>--dimension-keys '["toolName", "$.context.jwt.sub"]'--entries '[ {"dimensions": {"toolName": "search-target___web_search", "$.context.jwt.sub": "*"}, "requests": [{"rate": 20, "period": "minute"}]}, {"dimensions": {"toolName": "*", "$.context.jwt.sub": "*"}, "requests": [{"rate": 60, "period": "minute"}]}]'If an agent gets stuck calling the same tool, it's capped at 20 calls in that minute and gets a throttling response rather than an unlimited bill. But a request cap doesn't cap tokens: each looping call can carry a bigger context than the last. For real loop protection, pair tool request limits with a per-model token limit:
# Abbreviated: same create-gateway-rate-limit command as above--dimension-keys '["qualifiedModelId", "$.context.jwt.sub"]'--entries '[ {"dimensions": {"qualifiedModelId": "*", "$.context.jwt.sub": "*"}, "requests": [{"rate": 60, "period": "minute"}], "tokens": [{"rate": 100000, "period": "minute"}]}]'When an entry lists more than one metric, the gateway checks each one separately and throttles as soon as any of them is exceeded.
One caveat: token limits only apply to requests on the gateway's known inference paths (
/v1/chat/completions , /v1/messages , /v1/responses ). If a target proxies to a model some other way, only request and connection limits protect you.Handle the throttling response well in the agent. The gateway returns a
retryAfter value (in seconds) in the error body, for HTTP, MCP, OpenAI-compatible and Anthropic-compatible calls. Have your agent code honor it, cap tool-level retries in your own code, and tell the model it hit a limit so it stops retrying instead of looping. (Check whether your agent SDK's retry settings cover tool calls or only model calls.)Bonus pattern: block access by setting the rate to zero. An entry with
"rate": 0 blocks every matching request. For example, it can stop your free tier from calling an expensive frontier model, or shut off a misbehaving caller during an incident. The block takes effect once the change propagates, which can take up to 30 seconds.
Pattern 3: Limiting by what's in the request
Sometimes the value you want to limit on isn't in the token. Maybe a client sends a workload type (
interactive vs. batch ) in the request body, or a customer ID in a header. AgentCore Gateway can key limits on these too, using $.context.request.header.<name> and $.context.request.body.<path> .There's an important safeguard: because the caller controls headers and body fields, the gateway won't let you use them on their own. Every limit that uses one must also include a trusted identity key, such as a JWT claim or an IAM principal. Without one, creating the limit fails with a validation error. That means a caller can't dodge their limit by changing a header; at most they move between buckets that are still scoped to their own identity.
Here's a limit that gives each user a generous budget for interactive traffic and a much smaller one for batch work. The workload key comes first because a wildcard can only appear in trailing positions: you can write
["batch", "*"] , but not ["*", "batch"] .# Abbreviated: same create-gateway-rate-limit command as above--dimension-keys '["$.context.request.body.metadata.workload_type", "$.context.jwt.sub"]'--entries '[ {"dimensions": {"$.context.request.body.metadata.workload_type": "interactive", "$.context.jwt.sub": "*"}, "requests": [{"rate": 120, "period": "minute"}]}, {"dimensions": {"$.context.request.body.metadata.workload_type": "batch", "$.context.jwt.sub": "*"}, "requests": [{"rate": 10, "period": "minute"}]}, {"dimensions": {"$.context.request.body.metadata.workload_type": "*", "$.context.jwt.sub": "*"}, "requests": [{"rate": 30, "period": "minute"}]}]'Each user gets a separate bucket per workload type: 120 RPM for interactive, 10 RPM for batch, and 30 RPM for any other value.
A few rules to know:
- Values are matched exactly. Leading and trailing whitespace is trimmed, but values are case-sensitive, so
batchandBatchare different buckets. Normalize values in your client.
- Bad or missing values skip the limit. If the header is absent, the body isn't valid JSON, the path doesn't lead to a single value, or the value breaks the format rules (over 256 characters, or containing
/,|,,,*or control characters), that limit doesn't apply to the request. Keep an identity-only limit underneath as a backstop.
- Body paths are simple dotted field names, like
metadata.tier. JSONPath filters, wildcards and array slices aren't supported, and a selector can be at most 128 characters.
- Header names are matched case-insensitively.
- You need inbound authentication. A gateway with no inbound auth can't use these keys at all.
- Never use per-request values like a request ID or trace ID here. Every request would get its own bucket and never be throttled.
Avoid this mistake: shared target limits
You might start by limiting by
targetName alone ("the knowledge-base tool gets 20 RPS"). That protects the backend, but all callers share that single bucket. One heavy tenant can use the whole thing.Rule of thumb: if a small group of callers is likely to dominate a target, include an identity dimension in the key (
["targetName", "$.context.jwt.tenant_id"] ). Use target-only limits purely to protect the backend, and rely on identity-scoped limits for fairness.The opposite mistake is just as bad: never key a limit on a value that's unique per request, such as
jti , a nonce, or a request ID. Every request gets its own fresh bucket and is never throttled, which effectively turns rate limiting off. Stick to stable, bounded identifiers like sub , team , or tier .AWS's own best-practices guidance calls the layered approach defense in depth: a per-target limit to protect backend capacity, a per-caller limit to prevent abuse, and a per-tool token limit to control cost.
Remember the account-level quotas
Your custom limits sit on top of service-managed quotas for the account. The gateway checks your limits first, then the service quotas, and the effective limit is whichever is lower. Use gateway limits to distribute capacity fairly, and request Service Quotas increases (where a quota is adjustable) to raise the overall ceiling. The model provider's own quotas still apply behind the gateway too.
What gateway limits don't do
Rate limits are powerful, but be clear-eyed about their design:
- They're approximate, not exact. Enforcement is eventually consistent. A new or idle ("cold") limit can over-admit for a short period before it converges, short bursts can slip through, very low rates (under about 1 request per second) are less precise, and token limits converge more slowly than request limits.
- They fail open. If the rate-limit service times out, requests are allowed: availability takes precedence over enforcement. If a dimension key can't be resolved from a request, that limit is skipped.
- They're not a security boundary. AWS explicitly says not to rely on rate limits alone for security. Use authentication, authorization and WAF rules for that.
So treat gateway limits as traffic management and fairness: smoothing bursts and keeping noisy neighbors in check over a sustained window. For a hard budget, add provider or account-level spend controls and billing alerts on top.
Rollout checklist
- Route all AI traffic through the gateway. Limits only apply to traffic the gateway actually sees.
- Standardize identity claims and plan your keys. Use simple claim names for tenant, tier, and user. You can't change a limit's dimension keys after you create it (you'd have to delete and recreate it), so settle the structure before production.
- Start with observation. Look at your real per-tenant and per-tool traffic before choosing numbers. The gateway emits OpenTelemetry span attributes showing each throttle decision and which limit fired, which helps a lot when tuning. Remember that limit changes take up to 30 seconds to propagate.
- Add layers in order: tenant ceiling → per-user ceiling → per-tool and per-model limits.
- Treat throttling as a product state. Return clear errors, honor the
retryAftervalue, tell users when they've hit a limit, and make agents stop retrying when they're throttled.
- Test with sustained traffic. A short burst against a cold limit may not trigger throttling, so test over several minutes.
- Review limits like you review cost. Revisit them as tenants grow and new models launch.
The takeaway
Agents fan out. One prompt can turn into hundreds of downstream calls, and agent loops have no built-in sense of cost. Putting rate limits at the gateway, keyed by identity and by target, turns "hope nothing goes wrong" into an enforced ceiling on sustained traffic. Pair it with spend caps and billing alerts for a hard budget, and you protect your tenants from each other, your backends from overload, and your budget from your own agents.
References
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article