AWS Builder Center
Real-Time Per-Tenant Cost Enforcement for Amazon Bedrock: A Gateway Pattern for Multi-Tenant ISVs

Real-Time Per-Tenant Cost Enforcement for Amazon Bedrock: A Gateway Pattern for Multi-Tenant ISVs

How do you cap Bedrock costs per tenant when all calls go through a single IAM role? A gateway pattern for ISVs with app-layer auth, hundreds of tenants, and no native enforcement option.

By Zeek Granston and Carlos Calderon



The problem

A multi-tenant ISV SaaS provider recently asked us: "How do we cap Bedrock costs per tenant when all our calls go through a single IAM role and our users authenticate at the application layer?"
They'd tried Cost Explorer tags for application-level tracking, and that worked fine for internal metrics. But at the tenant level, they needed real-time enforcement. Hundreds to thousands of tenants, a single IAM role invoking Bedrock, and no way to say "this tenant has hit their daily budget, stop serving them inference." Application Inference Profiles didn't scale. IAM deny policies required federated identity they didn't have.
Their question was direct: is there a cheat code we can install, or do we build it ourselves? The answer was somewhere in between. This post documents the pattern.

What you actually need (and what AWS gives you today)

AWS has solid cost visibility tools. They answer "what did we spend?" with precision. But if you're an ISV with app-layer authentication and a thousand tenants, you need something different. You need to answer: "should I allow this specific API call right now, or has this tenant burned through their budget?"
That's a fundamentally different question. Let's look at why the existing tools don't answer it:
Approach
Can be used to control spend
Stops overspend in real-time
Works at 1000+ tenants
Works with app-layer auth
CUR 2.0 + Cost Allocation Tags
✅
❌ (24-hr delay)
✅
✅
Application Inference Profiles
✅
❌
❌ (operational overhead at scale)
✅
IAM Deny Policies per tenant
✅
✅
❌
❌ (requires per-tenant IAM identity)
CloudWatch Alarms + Lambda
✅
Sort of (minutes of delay)
✅
✅
The gateway pattern
✅
✅
✅
✅
Let me unpack the pain points:
CUR and Cost Explorer are retrospective. Great for monthly chargeback reports. But "we'll know tomorrow that you overspent today" doesn't protect your margins.
Application Inference Profiles are designed for cost allocation across teams or projects. The default quota is 1,000 per account per region. If you have a thousand tenants across multiple regions, you'd need a profile per tenant per region, and managing that operationally (creating, tagging, mapping, rotating) becomes a burden. They also don't enforce limits natively. They track spend, they don't block it.
IAM deny policies require each tenant to map to a distinct IAM identity. But most ISVs don't work that way. Your users authenticate within your application. All your Bedrock calls go through one service role. IAM has no idea who "tenant-acme-corp" is.
CloudWatch Alarms get you close. They can trigger a Lambda when usage spikes. But there's a window of minutes between the overspend occurring and enforcement kicking in (log delivery latency, alarm evaluation period, Lambda invocation, IAM policy propagation). For high-volume workloads, that window is expensive.

The pattern: a lightweight gateway that blocks before the bill

The idea is simple. Before every Bedrock call, check a counter. If the tenant still has budget, let the call through. If not, block it. No Bedrock invocation means no cost incurred.
Here's what the flow looks like:
  1. Your app authenticates the user (your auth, your way)
  1. Before calling Bedrock, a Lambda checks DynamoDB: "does this tenant have tokens left today?"
  1. If yes, make the Bedrock call. Record the actual tokens used afterward.
  1. If no, return a 429. The tenant gets a "you've hit your daily limit" message.
That's it. No new products to adopt. No complex IAM federation to wire up. Just a DynamoDB table and a few lines of logic in the Lambda you probably already have.

┌─────────────────────────────────────────────────────────────────────┐
│ Your SaaS Application │
│ │
│ ┌──────────┐ ┌──────────────────────┐ ┌───────────────────┐ │
│ │ User │───▶│ Application Layer │───▶│ AI Services │ │
│ │ Request │ │ (Authentication) │ │ (Gateway Lambda) │ │
│ └──────────┘ └──────────────────────┘ └────────┬──────────┘ │
│ │ │
└────────────────────────────────────────────────────────┼─────────────┘
│
┌──────────────────────────────┼───────────┐
│ Enforcement Layer │ │
│ ▼ │
│ ┌─────────────────────────────────────┐ │
│ │ Budget Check Lambda │ │
│ │ │ │
│ │ 1. Extract tenant_id from context │ │
│ │ 2. Query DynamoDB for remaining cap │ │
│ │ 3. ALLOW or DENY │ │
│ └──────────┬───────────────┬───────────┘ │
│ │ │ │
│ ┌───────▼───────┐ ┌───▼──────────┐ │
│ │ DynamoDB │ │ Amazon │ │
│ │ │ │ Bedrock │ │
│ │ tenant_id (PK)│ │ │ │
│ │ date (SK) │ │ Claude / │ │
│ │ tokens_used │ │ Nova / │ │
│ │ daily_cap │ │ Other FMs │ │
│ │ tier │ │ │ │
│ └───────────────┘ └──────────────┘ │
│ │
└───────────────────────────────────────────┘
Worth emphasizing: this does NOT require you to adopt Amazon API Gateway as a separate product. If you already have a Lambda that calls Bedrock, you're adding a DynamoDB read before the call and a write after. The Lambda is the gateway.

Building it

The DynamoDB table

One table. Two keys. That's the whole data model.
The partition key is  tenant_id  (whoever your application says this user belongs to). The sort key is today's date. When a new day starts, there's no record for that tenant yet, so they get a fresh budget automatically. No cron job. No reset Lambda. The calendar does the work for you.
import boto3

dynamodb = boto3.resource('dynamodb')

table = dynamodb.create_table(
TableName='bedrock-tenant-budgets',
KeySchema=[
{'AttributeName': 'tenant_id', 'KeyType': 'HASH'},
{'AttributeName': 'date', 'KeyType': 'RANGE'}
],
AttributeDefinitions=[
{'AttributeName': 'tenant_id', 'AttributeType': 'S'},
{'AttributeName': 'date', 'AttributeType': 'S'}
],
BillingMode='PAY_PER_REQUEST'
)
Use  PAY_PER_REQUEST  billing. It scales with your tenant count without you ever thinking about capacity units.

Tenant tiers

Most ISVs don't give every customer the same budget. Define tiers that match your pricing model:
TIER_CONFIGS = {
"standard": {
"daily_token_cap": 100_000, # 100K tokens/day
"models_allowed": ["amazon.nova-lite-v1:0", "amazon.nova-micro-v1:0"],
"soft_limit_pct": 0.80
},
"premium": {
"daily_token_cap": 1_000_000, # 1M tokens/day
"models_allowed": ["anthropic.claude-3-5-sonnet-*", "amazon.nova-*"],
"soft_limit_pct": 0.90
},
"enterprise": {
"daily_token_cap": 10_000_000, # 10M tokens/day
"models_allowed": ["*"],
"soft_limit_pct": 0.95
}
}
Store these however makes sense for your stack. Environment variables work for a handful of tiers. A config table works at scale.

The pre-invocation check

This is the gatekeeper. It runs before every Bedrock call:
import boto3
import os
from datetime import datetime, timezone

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(os.environ['BUDGET_TABLE_NAME'])

def check_budget(tenant_id):
today = datetime.now(timezone.utc).strftime('%Y-%m-%d')
response = table.get_item(
Key={'tenant_id': tenant_id, 'date': today},
ConsistentRead=True
)
item = response.get('Item')
if item is None:
# First call of the day. Full budget available.
daily_cap = get_tenant_cap(tenant_id)
return {
'allowed': True,
'remaining_tokens': daily_cap,
'daily_cap': daily_cap,
'tokens_used': 0
}
tokens_used = item['tokens_used']
daily_cap = item['daily_cap']
remaining = daily_cap - tokens_used
if remaining <= 0:
return {
'allowed': False,
'remaining_tokens': 0,
'reason': f'Daily token cap of {daily_cap:,} exceeded',
'tokens_used': tokens_used,
'daily_cap': daily_cap
}
return {
'allowed': True,
'remaining_tokens': remaining,
'tokens_used': tokens_used,
'daily_cap': daily_cap,
'alert': (tokens_used / daily_cap) >= 0.80
}
Note the  ConsistentRead=True . You want the latest value, not a stale one from a few hundred milliseconds ago. The extra fraction of a millisecond is worth it.

Recording what was actually used

After Bedrock responds, record the real token count. Not an estimate. The  usage  field in Bedrock's response gives you exact input and output token counts.
from datetime import datetime, timezone

def record_usage(tenant_id, input_tokens, output_tokens, model_id):
today = datetime.now(timezone.utc).strftime('%Y-%m-%d')
total_tokens = input_tokens + output_tokens
try:
table.update_item(
Key={'tenant_id': tenant_id, 'date': today},
UpdateExpression='''
SET tokens_used = if_not_exists(tokens_used, :zero) + :tokens,
daily_cap = if_not_exists(daily_cap, :cap),
last_updated = :now,
last_model = :model
''',
ExpressionAttributeValues={
':tokens': total_tokens,
':zero': 0,
':cap': get_tenant_cap(tenant_id),
':now': datetime.now(timezone.utc).isoformat(),
':model': model_id
}
)
except Exception as e:
# Don't fail the user's request over a bookkeeping error.
# The next pre-check will catch the discrepancy.
print(f"Warning: Failed to record usage for {tenant_id}: {e}")
Two things to notice here:
First,  if_not_exists(tokens_used, :zero) + :tokens  is an atomic counter. If two requests land at the same millisecond, DynamoDB handles it correctly. No transactions needed.
One caveat: atomic counters are not idempotent. If Lambda retries a request on a transient 500 error, the token count may be incremented twice. For most ISVs this is an acceptable tradeoff (worst case: a tenant's budget depletes slightly faster than actual usage). For strict enforcement, add a condition expression to the UpdateItem or use  TransactWriteItems  with a  ClientRequestToken  for idempotency.
Second, if this write fails, the user still gets their response. The counter will be slightly behind, but the next pre-check catches it. Worst case: one extra request slips through before the cap kicks in. For most ISVs, that's a fine tradeoff.

Putting it together

Here's what your AI services Lambda looks like with the gateway wired in:
import boto3
import json

bedrock_runtime = boto3.client('bedrock-runtime')

def ai_service_handler(event, context):
tenant_id = event['tenant_id']
model_id = event['model_id']
messages = event['messages']
# Check the budget
budget = check_budget(tenant_id)
if not budget['allowed']:
return {
'statusCode': 429,
'body': json.dumps({
'error': 'TOKEN_BUDGET_EXCEEDED',
'message': budget['reason'],
'resets_at': 'midnight UTC'
})
}
# Make the Bedrock call
response = bedrock_runtime.converse(
modelId=model_id,
messages=messages
)
# Record what we used
usage = response['usage']
record_usage(
tenant_id=tenant_id,
input_tokens=usage['inputTokens'],
output_tokens=usage['outputTokens'],
model_id=model_id
)
# Return the response with usage context
return {
'statusCode': 200,
'body': json.dumps({
'response': response['output']['message']['content'][0]['text'],
'usage': {
'input_tokens': usage['inputTokens'],
'output_tokens': usage['outputTokens'],
'remaining_budget': budget['remaining_tokens'] - (usage['inputTokens'] + usage['outputTokens'])
}
})
}
Clean. Readable. No new infrastructure required beyond the DynamoDB table.

Multi-region? Deploy per region.

If you're running in five regions, you deploy five stacks. Each region's DynamoDB table tracks that region's usage independently. A CloudFormation template makes this trivial:
AWSTemplateFormatVersion: '2010-09-09'
Description: Per-tenant Bedrock cost enforcement

Resources:
BudgetTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: !Sub 'bedrock-tenant-budgets-${AWS::Region}'
BillingMode: PAY_PER_REQUEST
KeySchema:
- AttributeName: tenant_id
KeyType: HASH
- AttributeName: date
KeyType: RANGE
AttributeDefinitions:
- AttributeName: tenant_id
AttributeType: S
- AttributeName: date
AttributeType: S
TimeToLiveSpecification:
AttributeName: ttl
Enabled: true
If you need a global cap (tenant gets 1M tokens across all regions combined), look at DynamoDB Global Tables. You'll get eventual consistency across regions, which means a tenant could slightly exceed their global cap if they're hitting multiple regions simultaneously. In practice, that's rarely a problem.

What about LiteLLM?

If you'd rather not build this yourself,  LiteLLM  is an open-source LLM proxy that handles per-tenant budgets, token tracking, and multi-model routing out of the box. AWS has a  reference architecture  for deploying it as a self-hosted gateway in your VPC.
The tradeoff is straightforward:
Choose LiteLLM if you want something running in days, don't need deep customization, and are comfortable with an open-source dependency in your critical path.
Choose the custom Lambda + DynamoDB pattern if you already have a Lambda calling Bedrock (most ISVs do), want zero operational overhead beyond what you already manage, and prefer not to introduce a new proxy layer with its own PostgreSQL and Redis dependencies.
Both work. The custom pattern just integrates more cleanly when you already have the Lambda.

Layer your defenses

The gateway handles real-time enforcement. But don't stop there. Use the native AWS tools for what they're good at:
For real-time blocking: The gateway pattern (this post). First line of defense.
For monthly reconciliation: CUR 2.0 with cost allocation tags at the application level. This powers your finance team's chargeback reports.
For anomaly detection: CloudWatch alarms on your custom token-usage metrics. Catch unexpected spikes that haven't hit a cap yet.
For customer-facing dashboards: Query DynamoDB directly. It has the real-time data your customers want to see.

Things you'll discover in production

Latency is a non-issue. On the warm path, the DynamoDB read adds 5-10ms. Bedrock inference takes 500ms to 30 seconds. Your users will never notice the budget check. If cold starts are a concern for your enforcement Lambda, use provisioned concurrency.
Race conditions are manageable. The atomic counter handles concurrency correctly. In extreme cases (hundreds of concurrent requests from one tenant at the exact moment they hit their cap), you might overshoot by a few requests. The math:  max_overrun = concurrent_in_flight_requests x max_tokens_per_request . For most workloads, this is negligible. Note that Lambda SDK retries on transient errors can also double-count a write. If strict accuracy matters, use a condition expression or TransactWriteItems with a ClientRequestToken.
Token counts come from Bedrock, not from you. The  usage  field in the Converse API response gives you exact input and output token counts. Don't estimate. Don't tokenize client-side. Use the source of truth.
The enforcement layer costs almost nothing. For 1,000 tenants making 100 requests per day: about $2.50/month total for DynamoDB reads, writes, and the additional Lambda time. Compare that to one tenant burning $500 in a single afternoon without controls.

Wrapping up

The gap between cost visibility and cost control is where ISVs lose money. AWS gives you excellent tools to understand what you spent. This pattern gives you the ability to decide, in real-time, whether to allow the next request.
It's a DynamoDB table, a budget check before the Bedrock call, and a usage write after. No new products. No IAM rearchitecture. No quota limitations. It works with whatever auth system you already have, scales to whatever tenant count you're headed toward, and costs less per month than a cup of coffee.
If you're embedding Bedrock into a multi-tenant product today, build this before your first customer discovers they can burn through your inference budget unchecked. Future-you will be grateful.

Get started

  1. Deploy the DynamoDB table in your dev account
  1. Add the budget check to your existing AI services Lambda
  1. Define tier caps that match your current pricing
  1. Add CloudWatch metrics on allow/deny rates for visibility
  1. If you'd rather skip the build, deploy the  LiteLLM reference architecture 

Related reading




About the authors

 Zeek Granston  is an AI/ML Solutions Architect focused on building effective artificial intelligence and machine learning solutions. He stays current with industry trends to deliver practical results for clients. Outside of work, Zeek enjoys building AI applications, and playing basketball


 Carlos Calderon
  is a Solutions Architect at AWS, serving as a technical advisor to ISV and SaaS companies on cloud architecture and generative AI. With a background in leading AWS data center operations, he works with customers from architecture through deployment and mentors SAs and engineers across the builder community.
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