AWS Builder Center

Per-user budget enforcement for AI agents on Amazon Bedrock

Stop runaway AI agent spend before it happens. Use Amazon Bedrock AgentCore Gateway interceptors to cap, downgrade, or block individual users at the platform layer, with no enforcement code in the agents.

Stop runaway AI agent spend before it happens. Use Amazon Bedrock AgentCore Gateway interceptors to cap, downgrade, or block individual users at the platform layer, with no enforcement code in the agents.
The first half covers the concept; the second half is the implementation. At the end of the implementation half, you'll find a ready-made prompt you can drop into Claude Code or Kiro to accelerate applying this guide to your own project.
This article builds on the  attribution article , which covered who is spending: OpenTelemetry baggage puts the end user on every usage record, and per-user IAM sessions put the user on the bill. This article answers the question that arrives about a minute after you present the per-user dashboard: what stops a runaway user?
It presents one approach to that question: enforcement at an Amazon Bedrock AgentCore Gateway, in the request path. It fits workloads whose clients speak the Anthropic or OpenAI API shapes, because those are the formats the gateway's inference connectors serve today (bedrock-mantle for Bedrock-hosted models, plus the anthropic and openai provider connectors) [2]; agents calling Bedrock through the native Converse or InvokeModel SDK paths need a different enforcement point. Other approaches, including an embedded, framework-level budget gate that works with any client, are material for a future article.

The concept: why enforcement belongs on the platform, and the one idea that delivers it

You rolled out the attribution from the first article. The dashboards work. You can see, by name, that one power user consumed half of yesterday's capacity, that a team's overnight batch tripped the account's rate limit, that costs doubled this month and exactly which sessions did it.
Then leadership asks the obvious next question: so what stops them?

Seeing is not stopping

Attribution is a rear-view mirror. It tells you, precisely and by name, who consumed half the capacity last night. It does not decline their next request. A dashboard informs, an alarm pages a human, and by the time the human acts, the budget is spent.
Think of a credit card statement versus a credit limit. The statement tells you, line by line, where the money went, indispensable, and entirely after the fact. The limit is different: it acts at the moment of purchase, with no human in the loop, and the card simply declines when the limit is reached. Attribution gave you the statement. This guide builds the limit.

Why enforcement inside agents fails

The instinctive answer is to ask every team to add budget checks inside their agents. That fails structurally, for three reasons:
  • You have several frameworks. A budget check written for Strands does not run in LangGraph, and neither runs inside Claude Code, which is a closed binary you cannot modify.
  • You have many teams, each with its own retry behavior, error handling, and release schedule. An enforcement rule that must be re-implemented N times will be wrong in at least one of them.
  • The user you most need to stop is the one whose code you do not control. Self-enforcement asks the person over budget to decline their own requests.
Enforcement belongs on the platform, at a point every request already passes through, keyed to an identity the platform itself validates. Agent code should not change at all; agents should only change where they point.

The idea: a checkpoint every request must pass

Picture a toll gate on the only bridge into a city. Every vehicle crosses it, no exceptions, because the bridge is the only way in. The gate reads the transponder, checks the account, and either lifts the barrier, waves the vehicle into a slower lane, or turns it away, all before the vehicle is on the bridge. Nobody asks drivers to voluntarily report their crossings.
Amazon Bedrock AgentCore Gateway is that bridge. It can front Amazon Bedrock as an inference target, presenting an Anthropic Messages API endpoint behind a JWT authorizer [1][2]. Gateway interceptors are the toll gate: your Lambda function runs on every request before it reaches Bedrock, and again on every response before it returns to the caller [3]. The identity comes from the JWT the gateway already validated. The decision, allow, downgrade, or refuse, happens before any tokens are spent.
This is a supported platform feature, not a workaround: interceptors are the documented mechanism for exactly this kind of centralized policy [3], and the inference target's built-in connector to Bedrock is a documented gateway capability [2].

What you get once the checkpoint is in place

Once every model call passes through the gateway:
  • A per-user daily token budget that refuses requests with HTTP 429 before Bedrock is ever called, so a refused request costs nothing.
  • Automatic model downgrade: past a threshold you set, a Sonnet request is rewritten to Haiku at the gateway, and work continues on the cheaper model.
  • A hard per-user block (HTTP 403) for offboarding or incident response, effective on the very next request.
  • An audit ledger the platform writes itself: one record per model call, carrying the user, the models requested and served, and the settled token counts, no longer trusted from the client.
  • Live policy changes: budgets are rows in a table, and a change takes effect on the next request, with no deployment.
Figure: Enforcement at a glance. Every agent's request carries the user's JWT to the gateway; the REQUEST interceptor decides against the user's budget before Bedrock is called (the solid path), and the RESPONSE interceptor settles real usage into the ledger afterward (the dashed path). [Add diagram image here.]

The design in one sentence, and where it comes from

The enforcement design is reserve-and-settle: before the call, reserve the request's worst case against the user's budget; after the call, replace the reservation with what the model actually reported.
This is not invented here. It is how Amazon Bedrock itself meters quota. Bedrock's token burndown documentation describes the same three moments: at the start of a request, the sum of input tokens plus the caller's  max_tokens  is deducted from the quota, and the request throttles if the sum exceeds it; during processing, the deduction is adjusted toward actual output; at the end, unused tokens are replenished [4]. Azure OpenAI similarly counts prompt plus  max_tokens  against its per-minute quota at admission [5]. This guide applies that per-account mechanism per user.
The alternative, counting usage only after responses complete, is what several popular LLM gateways ship by default, and its cost is documented by its own vendors: Cloudflare's spend-limits documentation notes that because the current request's cost is recorded after completion, "a burst of concurrent requests can briefly exceed the limit before enforcement catches up" [6]; LiteLLM's budget documentation describes the same read-spend-then-admit model with an optional fail-closed mode [7]. For dashboards, brief overshoot is fine. For a hard budget, it is the difference between a limit and a suggestion, which is why this guide reserves.

Two questions, two answers

As with attribution, there are two flavors of "stopping":
The first is operational: refuse, downgrade, or block a user's next request, in milliseconds, at the platform. That is the gateway story, and what this guide covers.
The second is contractual: per-account throughput and quota, which Amazon Bedrock service quotas already manage [8], including the token burndown behavior described above [4]. Quotas protect the account; this guide's budgets protect it per user, inside whatever the account-level quota allows.
Most organizations want both. They complement each other.

Who does what

The work splits cleanly:
  • The platform team deploys the gateway, the interceptor, and the ledger once, and owns the policy table.
  • Developers point their agents at the gateway URL and pass the user's JWT, one connection-string change per client, with zero enforcement logic.
That division is the structure of the implementation half, for Strands, LangGraph, and Claude Code, whether the agents run on AgentCore Runtime or anywhere else.

The implementation, for platform teams and developers

The concept half explained the why. This half is the how-to. It splits by role, read the section that applies to you:
  • The platform team deploys the checkpoint (gateway, interceptor, ledger) and owns policies.
  • Developers point their agents at it (one connection change per framework).
Before either role's section, two things that come up in every review: what are we deploying, and what actually got verified.

What you are deploying, and how to vet it

Three pieces, all in your own account, no third-party services in the request path.
Piece
What it does
AgentCore Gateway with an inference target
Presents an Anthropic Messages API endpoint behind a JWT authorizer; forwards to Bedrock through the built-in  bedrock-mantle  connector under the gateway's IAM role [2]
One Lambda interceptor
Registered on the gateway's REQUEST and RESPONSE hooks [3]; roughly 900 lines of Python you can read end to end, using only boto3 and botocore from the managed runtime
One DynamoDB table
The ledger:  POLICY  items (budget, thresholds, blocked flag),  USAGE  items (per-user, per-day counters),  EVENT  items (one audit row per model call), with TTL cleanup
Auth in is your JWT (Amazon Cognito in the sample); auth out is IAM. There are no API keys anywhere in the path.

Trust boundaries, stated explicitly

You are putting an enforcement decision in front of every model call, so be precise about who verifies what:
  • Amazon Cognito signs the user's token at sign-in [9].
  • The gateway verifies the token's signature against the user pool's JSON Web Key Set on every request (the CUSTOM_JWT authorizer) [1]. An invalid or expired token gets 401 before your Lambda ever runs.
  • The interceptor does not re-verify; it base64-decodes the already-verified token and reads only the  sub  claim, the stable subject identifier defined by RFC 7519 [10]. Identity is never read from the request body, so a client cannot claim to be someone else.
  • The interceptor Lambda carries a resource policy allowing invocation only by the exact gateway ARN, so nothing else can call it with forged events.
  • Enforcement holds only if the gateway is the only door. If an agent's execution role still carries  bedrock:InvokeModel , a user can bypass every budget by calling Bedrock directly. Strip direct model-invocation permissions from agent roles and let the gateway role alone hold the model permissions. One IAM lesson worth stating plainly: the gateway role needs  bedrock-mantle:*  in addition to  bedrock:InvokeModel* , which came from a live failure, not from documentation.
The identity in the ledger is the same pseudonymized subject the first article's privacy section established; every handling rule from that section (pseudonymize at the boundary, encrypt, expire, minimize) applies unchanged to the ledger table.

For the platform team: deploy the checkpoint

The architecture

Strands / LangGraph / Claude Code
| Anthropic Messages request + Bearer JWT
v
AgentCore Gateway (JWT authorizer)
|
+-- REQUEST hook --> Lambda interceptor --> allow / downgrade / 429 / 403
| |
| v
| DynamoDB ledger (POLICY, USAGE, EVENT)
| ^
+-- RESPONSE hook --> Lambda interceptor --> settle real usage, idempotent
|
v inference target (bedrock-mantle), same account, same IAM
Amazon Bedrock
A request moves through six steps:
  1. The agent sends an ordinary Anthropic Messages request with  Authorization: Bearer <JWT> . Without a valid JWT the gateway returns 401 and the Lambda never runs [1].
  1. The REQUEST interceptor takes the user id from the validated JWT  sub  claim [10]. That is the identity for everything downstream.
  1. It loads the user's  POLICY  item and estimates the request's worst case: the body length at roughly three bytes per token (English text runs near four bytes per token; three keeps margin for dense scripts) plus the requested  max_tokens  as the output bound. Deliberately blunt, always an overestimate.
  1. It reserves that estimate against the user's daily  USAGE  item in one atomic, conditional DynamoDB transaction [11]. The write succeeds only if the reservation fits the remaining budget, so two racing requests cannot both squeeze into the last slice.
  1. It decides: pass the request through untouched; downgrade it by rewriting the model id in the body (a Sonnet request goes to Bedrock as Haiku); short-circuit with HTTP 429  budget_exceeded  and a  retry_after  before Bedrock is ever called; or return HTTP 403  access_denied  for a blocked user.
  1. The RESPONSE interceptor settles: it replaces the reservation with the real usage reported by the model, including usage from streamed responses, keyed idempotently by request id, and writes the  EVENT  row.
Step 6 is where the conservative estimate stops mattering. In one verified Claude Code run, the interceptor reserved 115805 tokens and settled 30548 real ones. The reservation protects the budget during the request; the settle makes the ledger true afterward. This mirrors Bedrock's own quota burndown, which also deducts the worst case up front and replenishes unused tokens at the end [4].

The reservation math, and its one documented tradeoff

The reserve is  input estimate + max_tokens . Both terms matter:
  • The input estimate uses a bytes-per-token heuristic rather than a tokenizer, because the interceptor must be fast and dependency-free. The default is one token per three body bytes, overridable with the  INPUT_BYTES_PER_TOKEN  environment variable. English text runs near four bytes per token, so three over-reserves modestly by design.
  • The output bound is the caller's own  max_tokens , the only pre-call bound that exists, since output length is unknown until the response returns. This is the same bound Bedrock [4] and Azure OpenAI [5] use for admission.
The tradeoff is documented by AWS for its own quotas: a  max_tokens  far above the real completion size makes every request look expensive to the admission check, which throttles earlier than the visible usage suggests. AWS's guidance for its quotas applies verbatim to these budgets: "try reducing max_tokens to better approximate the size of your completions" [4]. Research on LLM serving reaches the same conclusion from the throughput side: reserving worst-case output length lowers effective capacity, and predicting output length recovers it [12]. Practically: have clients send a  max_tokens  sized to the ask, and treat a percentile-based output estimate as the production refinement.

Policies are rows, not code

A user's policy is one DynamoDB item:
{
"pk": "POLICY#<sub>",
"budget_tokens": 400000,
"downgrade_at_tokens": 360000,
"fallback_model": "anthropic.claude-haiku-4-5",
"blocked": false
}
Change  budget_tokens  and the next request obeys it. Set  blocked  and the next request gets 403. No deployment, no restart, no agent involvement. This is what makes the mechanism operational rather than architectural: incident response is a  PutItem .

Confirm it works

Before wiring every agent, prove the path end to end with one call. Mint a JWT for a test user, send one Anthropic Messages request at the gateway URL, then read the ledger:
aws dynamodb query \
--table-name <LedgerTable> \
--key-condition-expression "pk = :p" \
--expression-attribute-values '{":p": {"S": "USAGE#<sub>#<today>"}}'
If the usage item shows your test call's tokens, enforcement is live. Then set  budget_tokens  to a value below the usage you just recorded, send another request, and confirm the 429 arrives with  retry_after  in the body and the usage counters unchanged, the proof that a refused request costs nothing.

When enforcement breaks

Enforcement fails loudly (requests refuse), but attribution inside it can fail quietly. The causes worth checking, in order:
  • The settle failed. A failed RESPONSE-side settle leaves the oversized reservation, not the real usage, standing against the user's budget until the day rolls over. Alarm on the interceptor's  response_finalize_failed  output; this is the one silent failure mode with a per-user blast radius.
  • The budget is sized for real usage but not for the estimator. Large-context clients (Claude Code sends roughly 116 KB of system prompt and tool schemas) reserve tens of thousands of tokens per request. Size budgets against reservations, not just settled usage, or requests will refuse below the visible budget line.
  • The gateway is not the only door. If usage moves but the ledger does not, some path still calls Bedrock directly; audit agent roles for  bedrock:InvokeModel .
  • Near a threshold, big requests refuse while small ones pass. This is the reservation working: admission checks  used + this request's reserve , not just  used . Expect it within one reservation's width of any threshold, and teach on-call staff that it is by design.

For developers: point your agent at the gateway

Your agents contain zero enforcement logic. The only change is where they connect and what credential they carry: the gateway URL as the base URL, and the user's JWT as a Bearer token. The JWT is the same token your application already holds for the signed-in user; where an orchestrator invokes agents on the user's behalf, forward that token (on AgentCore Runtime, create the runtime with a  requestHeaderAllowlist  for  Authorization  so the platform passes it into your container).
The pattern is identical across frameworks. What differs is each client library's authentication quirk, and every quirk below came from a live failure, not from documentation.
Framework
The one change
The quirk
Strands
 AnthropicModel  with  auth_token  and  base_url 
 api_key  sends the wrong header and gets 401
LangGraph
 ChatAnthropic  plus Bearer-only client injection
no constructor path to Bearer-only auth today
Claude Code
two environment variables
must disable experimental beta flags

Strands

Strands ships an Anthropic model provider [14]. It must authenticate with  auth_token , not  api_key . Passing  api_key  makes the SDK send an  x-api-key  header, and the gateway answers 401 Missing Bearer token.
from strands import Agent
from strands.models.anthropic import AnthropicModel

model = AnthropicModel(
client_args={
"auth_token": jwt, # Bearer auth, which the gateway validates
"base_url": gateway_url, # not api_key: that sends x-api-key and gets 401
"max_retries": 0, # surface 429/403 refusals immediately
},
model_id="governance-inference/anthropic.claude-sonnet-5",
max_tokens=2048, # sized to the ask; the gateway reserves this
)
agent = Agent(model=model, system_prompt="You are a concise, helpful assistant.")
agent(prompt)
Set  max_retries=0  so a 429 from the gateway surfaces as the governance decision it is, rather than being retried into a timeout. A multi-agent Strands application needs nothing extra: build sub-agents from the same model factory, and each sub-agent call passes the gateway under the same user. In verification, one orchestrator prompt produced three  EVENT  rows, all attributed to the same person, the usage that disappears when accounting depends on agents reporting honestly.

LangGraph

LangChain's  ChatAnthropic  [15] always forwards an api key, and adding a Bearer header alongside produces 401 "must not include both authorization and x-api-key". There is currently no constructor path to Bearer-only auth, so the working pattern is a deliberate library-gap workaround: construct the model with a dummy key, then inject Bearer-only SDK clients into the cached client slots.
import anthropic
from langchain_anthropic import ChatAnthropic

llm = ChatAnthropic(
model="governance-inference/anthropic.claude-sonnet-5",
api_key="unused-gateway-uses-bearer",
base_url=gateway_url,
max_tokens=2048,
max_retries=0,
)

# Workaround for a library gap: ChatAnthropic has no Bearer-only mode.
# Replace its cached SDK clients with ones built from auth_token.
llm.__dict__["_client"] = anthropic.Client(
auth_token=jwt, base_url=gateway_url)
llm.__dict__["_async_client"] = anthropic.AsyncClient(
auth_token=jwt, base_url=gateway_url)
This reaches into private attributes and should be retired the day the library grows a supported option. Until then, isolate it in one factory function so the day it breaks, it breaks in one place.

Claude Code

Claude Code talks to any Anthropic-compatible endpoint through its environment [13]. Point it at the gateway and disable the experimental beta flags, which Bedrock's Anthropic path rejects with 400 "invalid beta flag":
export ANTHROPIC_BASE_URL="$GATEWAY_URL"
export ANTHROPIC_AUTH_TOKEN="$JWT"
export CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1 # Bedrock 400s the beta flags otherwise
claude -p "$PROMPT"
Know your budget math before you size Claude Code's policy: it sends a very large request body (roughly 116 KB of system prompt and tool schemas), so the byte-based estimator reserves tens of thousands of tokens per request. At the default three-bytes-per-token setting that is about 39k tokens reserved per request, settling to the real usage afterward. A few hundred thousand tokens per day is a realistic Claude Code budget. Undersize it and Claude Code's requests refuse with 429, which it retries silently until an outer timeout, a failure that looks like a network problem and is actually a budget problem.

What the user experiences

Three behaviors, all decided at the gateway, all verified live:
  • Under budget: the request passes untouched, and the response is byte-identical to calling Bedrock directly.
  • Past the downgrade threshold: the request is served by the fallback model. In verification, a Sonnet request was rewritten to Haiku, the response reported  claude-haiku-4-5-20251001  as the serving model, and the user's ledger settled exactly 38 actual tokens. This also works on streaming: a  stream: true  Sonnet request returned a real SSE stream from Haiku.
  • Over budget: HTTP 429 with  budget_exceeded  and  retry_after  in the JSON body, before Bedrock is called; the ledger's counters do not move. A blocked user gets HTTP 403 on every request until the flag is cleared.
One wire-level detail for client authors: the gateway strips custom response headers on a short-circuit, so the machine-readable  retry_after  travels in the JSON error body, not in a  Retry-After  header. If your backoff logic reads headers only, teach it to read the body.

What we actually verified

Two Cognito users, called A and B here, carried different policies.
Client
Local
On AgentCore Runtime
Strands, single agent
PASS. One  EVENT , 26 in / 11 out, attributed to user A
PASS. One  EVENT , 26 in / 11 out
Strands, multi-agent (orchestrator plus tool sub-agent)
PASS. 3  EVENT s, all attributed to the same user
PASS. 3  EVENT s: 611/72, 35/5, 698/10
LangGraph, two-node graph
PASS. 2  EVENT s for user B: 24/9 and 21/9
PASS. 2  EVENT s: 27/12 and 24/12
Native Claude Code
PASS. Exit 0, marker returned,  EVENT  settled with 3 in / 12 out / 30533 cache creation, streaming
PASS. v2.1.210, exit 0,  EVENT  with 3 in / 10 out / 31321 cache creation
Enforcement surfaced in the client
Strands surfaced HTTP 429  budget_exceeded  with  retry_after  60; LangGraph surfaced HTTP 403  access_denied 
A Runtime invocation surfaced the 429  budget_exceeded 
The core governance proofs behind the matrix: a Sonnet request from user A was downgraded to Haiku ( original_model  Sonnet,  effective_model  Haiku,  response_model   claude-haiku-4-5-20251001 ), used 25 input and 13 output tokens, and the user's daily aggregate landed on exactly 38 actual tokens. An over-budget request returned 429 with  retry_after  60 and never reached Bedrock: the event count and accepted-request counters did not move. User B succeeded with HTTP 200 under a usage key distinct from user A's, and the same user B, once flagged  blocked , got HTTP 403.
Two rows deserve a second look. The multi-agent Strands run produced three separate  EVENT  rows for one user prompt, because the orchestrator and its tool sub-agent each made model calls, and all three attributed to the same person. And Claude Code's cache-creation tokens (30533 locally, 31321 on Runtime) settled into per-user attribution even though the response streamed, which is precisely the usage that disappears when attribution depends on clients reporting honestly.

Honest limits

Four things the live testing made unambiguous, stated plainly so you can plan around them.
The gateway strips custom response headers on a short-circuit. The interceptor sets a  Retry-After  header on the 429, but the client receives only  Date ,  Content-Type ,  Transfer-Encoding ,  Connection , and  x-amzn-RequestId . The machine-readable  retry_after  therefore travels in the JSON error body, where clients verifiably received it, and the header remains best effort.
Response-side streaming transformation is buffered only. The interceptor cannot rewrite SSE events one by one as they pass. This did not block anything in the verification matrix, because enforcement decisions happen on the request side and settlement reads the completed stream's usage, but if your design requires editing streamed content mid-flight, this is not the tool.
Enforcement holds only if the gateway is the only door. The live deployment held that shape: the interceptor Lambda had no function URL and could only be invoked by the exact gateway ARN, Cognito was admin-create-only, and the only reachable endpoint was the JWT-authed gateway URL. Audit your agent roles for direct  bedrock:InvokeModel  before you rely on the budgets.
Finally, this is a sandbox-grade sample. The path to production is short but real: alarm on  response_finalize_failed , because a failed settle leaves the oversized reservation standing against the user's budget until the day rolls over; tune the estimator if your traffic is unusual (the default is one token per three body bytes via  INPUT_BYTES_PER_TOKEN ; a tokenizer-based estimate would reserve less and admit more, and a percentile-based output estimate instead of full  max_tokens  is the researched refinement [12]); and rethink budget windows, because a daily counter is the demo, while production wants rolling windows, per-team rollups, and grace behavior at the boundary.

From tokens to dollars

The ledger governs tokens because tokens are what the model reports. Dollars are one multiplication away. Every  EVENT  row carries input, output, and cache token counts plus the effective model, so tokens times a price table equals per-user dollars, the same estimate the first article built in CloudWatch, now computed from records the platform wrote itself. And a budget in dollars is the same mechanism, not a new system: price the estimate at reserve time, price the real usage at settle time, and the only thing that changes in the ledger is the unit.
The first article told you who is spending. This one stops or slows them. The multiplication in between is what it costs.

Rolling it out

A practical order that keeps each step verifiable:
  1. Platform first. Stand up the gateway, interceptor, and ledger, create a test user, run the confirmation check, and set the  response_finalize_failed  alarm before any real traffic arrives.
  1. Set starter policies. Budgets sized against reservations, not just settled usage (remember the Claude Code math above), the downgrade threshold at 90 percent, and  blocked  false.
  1. Smoke-test one client. Point one framework at the gateway with one user's JWT, confirm the  EVENT  row, then set a tiny budget and confirm the 429 costs nothing.
  1. Roll out per framework. One connection change per client, following the framework sections above. On AgentCore Runtime, create runtimes with the  Authorization  header allowlist so the user's JWT reaches your container.
  1. Close the side door. Remove  bedrock:InvokeModel  from agent execution roles, leaving the gateway role as the only path to the models.
  1. Reconcile weekly. The ledger's settled tokens should track the account's Bedrock usage; a growing gap means some path is bypassing the gateway.
The platform team owns steps 1, 2, 5, and 6; developers own 3 and 4. After step 2, neither blocks on the other.

Accelerate with a coding agent

If you don't have to implement this manually, feed this guide to a coding agent, Claude Code or Kiro, along with your codebase, and let it generate the integration steps and tests tailored to your stack.
Setup:
  1. Point the agent at your codebase (open the repo in Kiro, or pass the path to Claude Code).
  1. Add the AWS Documentation MCP server from  https://awslabs.github.io/mcp/servers/aws-documentation-mcp-server  so the agent can pull current docs for AgentCore Gateway, Bedrock, and DynamoDB as it works.
  1. Give it the prompt below.
The prompt:
I want to implement per-user budget enforcement for our AI agents that call
Amazon Bedrock, following this guide (a companion to the per-user usage
attribution guide):
[link to this article]

Our stack:
- Framework: [Strands / LangGraph / Claude Code]
- Runtime: [AgentCore container / Lambda / ECS / EKS / local]
- Auth: [Cognito / Okta / custom IdP, and how agents receive the user's JWT]
- Current Bedrock access: [direct bedrock:InvokeModel from agent roles / other]

Please:
1. Analyze our codebase and identify every path that calls Bedrock
(model clients, SDKs, and any direct bedrock-runtime usage).
2. Generate a step-by-step plan split by role:
- Platform engineer: deploy the gateway + interceptor + ledger stack,
define starter POLICY items, set the response_finalize_failed alarm,
and plan the IAM change that removes direct model access from agents.
- Software engineer: the one connection change per framework
(auth_token/base_url for Strands, the ChatAnthropic Bearer workaround
for LangGraph, the environment block for Claude Code), with
max_retries=0 and a right-sized max_tokens per call site.
3. Create the implementation code and configuration.
4. Write test cases that verify:
- A under-budget request passes and settles real usage into the ledger
(integration test).
- An over-budget request returns 429 with retry_after in the body and
the usage counters do not move (enforcement test).
- A downgraded request reports the fallback model in the response
(downgrade test).
- A blocked user receives 403 on the next request (block test).
5. Give me a runbook: one request in, EVENT row visible in the ledger out,
and the weekly reconciliation query against account-level Bedrock usage.
Start by reading the codebase and mapping it to the guide, then propose the
plan before generating code.

References

AWS
Industry and standards
  • [12] Jin et al., S3: Increasing GPU Utilization during Generative Inference for Higher Throughput (output-length prediction versus worst-case reservation).  https://arxiv.org/abs/2306.06000 
Frameworks
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article