Call Amazon Bedrock from an app with scoped access
Call a Bedrock model, or a local stub, with a least-privilege role, and account for model choice, logging, quotas and cost.
By Invicly Tech, , in AWS Cloud Engineering. About 14 minutes to read.
In short
Amazon Bedrock lets your application call foundation models from several providers through one AWS API, so you do not run any model servers yourself. The application signs each request with an IAM role, picks a model or inference profile, and pays per token. The engineering work is scoping that role tightly, choosing a model that fits the task, deciding what gets logged, and staying inside token quotas and budget.
Think of it like this: Bedrock is like a phone switchboard for models: your app dials one number, says which model it wants, and the switchboard connects the call and bills you by the minute.
Explained simply
A foundation model is a large model that someone else has already trained, such as a model that writes or summarises text. Amazon Bedrock is the AWS service that hosts many of these models from different providers. Your code sends text to Bedrock and gets text back. You never see a server, a GPU or a model file.
Because it is an AWS API, Bedrock uses the same rules as S3 or DynamoDB. Every request is signed with AWS credentials, and IAM decides whether it is allowed. For an app, those credentials come from a role, such as the execution role of a Lambda function. You never put access keys in code.
You pay per token. A token is a small chunk of text, roughly three quarters of an English word on average. Both the text you send and the text the model writes count. A long prompt with a short answer can still be expensive if you send it thousands of times a day.
In our file-processing service, the worker could ask a model to write a two-sentence summary of each uploaded text file and store it in DynamoDB next to the other results. This module shows how to do that with a tight role, a sensible model choice, careful logging, and a stub that lets you build and test without paying for real calls.
Press Play on a diagram to walk through it one step at a time.
- Worker Lambda to STS / IAM: Uses the temporary credentials of its execution role1Uses the temporary credentials of its execution role
- Worker Lambda to Bedrock runtime: Converse: model ID, messages, maxTokens2Converse: model ID, messages, maxTokens
- Bedrock runtime to STS / IAM: Checks bedrock:InvokeModel on that model ARN3Checks bedrock:InvokeModel on that model ARN
- Bedrock runtime to Worker Lambda: Reply text, stopReason, usage token counts4Reply text, stopReason, usage token counts
- Worker Lambda to CloudWatch: Logs file ID, model ID and token counts, not the text5Logs file ID, model ID and token counts, not the text
- Bedrock runtime to CloudWatch: Publishes InputTokenCount and OutputTokenCount metrics6Publishes InputTokenCount and OutputTokenCount metrics
- Real answers and real token costs
- Needs a role allowed to invoke the model
- Some third-party models need a one-time subscription
- Subject to tokens-per-minute quotas
- Returns a fixed reply in the Converse response shape
- Free and works offline
- Good for unit tests and CI
- Tells you nothing about answer quality or latency
- 1Organisation SCP
Denies models or Regions the company has not approved
- 2Application role policy
Allows InvokeModel on one model ARN only
- 3App code
Model ID from config, maxTokens capped, retries with backoff
- 4Service quotas
Tokens and requests per minute per model
- 5Budget alert
Emails you when monthly spend crosses a threshold
In depth
Getting access and scoping the role
In commercial Regions, most Bedrock serverless models are available without an access request. The first call to a third-party model sold through AWS Marketplace starts a subscription in the background, so whoever makes that first call needs the aws-marketplace Subscribe, Unsubscribe and ViewSubscriptions permissions, and the account needs a valid payment method. Some older Anthropic models also need a one-time use case form per account or organisation. After the model is enabled, the application role only needs the invoke actions.
Write that application policy around the exact resources. A foundation model ARN has no account ID, for example arn:aws:bedrock:eu-west-1::foundation-model/ followed by the model ID. If you call a cross-Region inference profile, allow the profile ARN and the foundation model ARN in every Region the profile can route to. To block a model completely, deny bedrock:InvokeModel on it in IAM or an SCP; denying the Marketplace subscribe action alone does not stop the first call.
- Converse needs bedrock:InvokeModel
- ConverseStream needs bedrock:InvokeModelWithResponseStream
- Resource: named model or profile ARNs, not *
- Keep Marketplace permissions on an admin role, not the app role
Choosing a model for the task
Start from the job, not from a leaderboard. Summarising a short invoice needs a small, fast, cheap text model. Extracting fields into JSON needs a model that follows formats reliably. Reading scanned images needs a model that accepts image input. Check the model card for supported Regions, input types, context window, and whether it works with the Converse API and tool use.
Then test two or three candidates on 20 to 50 real-looking samples, using synthetic data rather than customer files. Score the answers against what a good reply looks like, and record latency and token counts. Pick the cheapest model that passes. Keep the model ID in configuration, such as an environment variable or Parameter Store, so changing models later is a config change and a redeploy rather than a code change.
- 1Define the task
Input type, output format, latency budget
- 2Shortlist
Two or three models available in your Region
- 3Test on samples
Same prompt, 20 to 50 synthetic files
- 4Score
Correctness, format, latency, tokens
- 5Pin in config
Model ID in an environment variable
Deciding what to log
There are two separate logs to think about. Your application log, in CloudWatch Logs, should hold the file ID, model ID, request ID, latency, stop reason and token counts. It should not hold the prompt or the reply, because those carry customer content.
Bedrock model invocation logging is an account and Region setting, off by default. When on, it records the full request and response for Converse, ConverseStream, InvokeModel and InvokeModelWithResponseStream calls on the bedrock-runtime endpoint, plus the caller's role ARN and token counts. It can write to CloudWatch Logs, S3 or both, in the same account and Region. Bodies larger than 100 KB and binary data go to S3 only. Turn it on when you need an audit trail or evaluation data, and treat the destination like a sensitive database: KMS encryption, a narrow reader role and a retention period.
- App log: IDs, latency, stopReason, usage
- Invocation log: full bodies, so restrict and expire it
- Set a CloudWatch Logs retention period; the default is never expire
Quotas, throttling and token cost
Bedrock limits throughput per model and Region, mostly as tokens per minute. At the start of each request it deducts your input tokens plus maxTokens. As the reply is written it adjusts that, and at the end it returns the unused part. Some models also count each output token as several quota tokens, called the burndown rate, though you are billed only for real tokens. So a request with a 300-token prompt and maxTokens of 8,000 reserves 8,300 tokens even if the reply is 60 tokens long.
When you go over, the call fails with ThrottlingException. Set maxTokens close to the longest reply you expect, retry with backoff, and let the SQS queue absorb bursts by limiting how many workers run at once. Check your current values in Service Quotas, because quotas vary by account and are not raised automatically. Estimate cost as files per day times average input and output tokens times the per-token prices on the Bedrock pricing page.
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Grant scoped model access~35m
- 2Choose a model for the task~35m
- 3Call the Converse API~35m
- 4Decide what to log~35m
- 5Check quotas and token cost~35m
Key points
- Calling Converse needs bedrock:InvokeModel; ConverseStream needs bedrock:InvokeModelWithResponseStream.
- Scope the Resource to the exact model or inference profile ARNs your app uses, never bedrock:* on *.
- The Converse API gives one request and response shape across models, so switching models is mostly a config change.
- Model invocation logging is off by default; turning it on records full prompts and replies, so treat the log store as sensitive data.
- Each request first reserves input tokens plus maxTokens against your quota, so an oversized maxTokens causes throttling early.
Key terms
Tap a card to flip it. 0/6 known
Examples
import os, boto3
br = boto3.client("bedrock-runtime", region_name=os.environ["AWS_REGION"])
resp = br.converse(
modelId=os.environ["MODEL_ID"], # model or inference profile ID from config
system=[{"text": "Summarise the file in two sentences."}],
messages=[{"role": "user", "content": [{"text": "Invoice 1042 from Contoso, total 310 EUR, due 30 days."}]}],
inferenceConfig={"maxTokens": 200, "temperature": 0.2},
)
print(resp["output"]["message"]["content"][0]["text"])
print(resp["stopReason"], resp["usage"]) # e.g. end_turn {'inputTokens': ..., 'outputTokens': ...}A Converse call with the model ID read from configuration. Run it only in a sandbox account with a budget alert.
A least-privilege policy for the summariser role
The worker Lambda only summarises text with one model in one Region. Step 1: find the model ID on the model card. Step 2: write a policy that allows bedrock:InvokeModel on that ARN only. Step 3: attach it to the worker's execution role next to its S3, SQS and DynamoDB permissions. Step 4: test that a call to a different model ID fails with AccessDeniedException. That denial is your evidence the scope works. Cleanup: the policy costs nothing, but remove it when you delete the lab.
{
"Version": "2012-10-17",
"Statement": [{
"Sid": "SummariseWithOneModel",
"Effect": "Allow",
"Action": "bedrock:InvokeModel",
"Resource": "arn:aws:bedrock:eu-west-1::foundation-model/<model-id>"
}]
}A local stub so tests and CI never call Bedrock
You want unit tests and the CI pipeline to run without AWS credentials or cost. Step 1: put the Bedrock call behind a small function. Step 2: when an environment variable says to use the stub, return a dictionary with the same keys the real Converse response has. Step 3: your code reads output, stopReason and usage the same way in both cases. Step 4: run the real model only in a manual sandbox test with a budget alert. The stub proves your plumbing; it proves nothing about answer quality.
import os
def summarise(client, text: str) -> dict:
if os.environ.get("USE_FAKE_MODEL") == "1":
return {
"output": {"message": {"role": "assistant", "content": [{"text": "Stub summary."}]}},
"stopReason": "end_turn",
"usage": {"inputTokens": len(text) // 4, "outputTokens": 3, "totalTokens": len(text) // 4 + 3},
}
return client.converse(
modelId=os.environ["MODEL_ID"],
messages=[{"role": "user", "content": [{"text": text}]}],
inferenceConfig={"maxTokens": 200},
)Quick reference
- Runtime client: boto3.client("bedrock-runtime"); control plane: boto3.client("bedrock")
- Converse needs bedrock:InvokeModel; ConverseStream needs bedrock:InvokeModelWithResponseStream
- Foundation model ARN: arn:aws:bedrock:REGION::foundation-model/MODEL_ID (no account ID)
- Inference profile: allow the profile ARN plus the model ARN in each Region it routes to
- Quota check at request start: input tokens + maxTokens; unused tokens are returned at the end
- Throttled calls raise ThrottlingException: retry with backoff and cap worker concurrency
- Invocation logging is off by default and logs full bodies; encrypt, restrict and set retention
- aws bedrock list-foundation-models --by-output-modality TEXT lists text models in your Region
Common mistakes
- Granting the managed AmazonBedrockFullAccess policy to an application role when it only needs to invoke one model.
- Allowing an inference profile ARN but forgetting the foundation model ARNs in each Region that profile routes to, which gives AccessDeniedException.
- Logging full prompts in application logs, which copies customer file contents into a store with weaker access rules.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
List the text models available in your sandbox Region and pick one candidate for summarising short invoices. Record its model ID and whether it supports the Converse API.
- Exercise 2medium
Write a function that calls Converse, logs only the file ID, model ID, latency, stopReason and token counts as one JSON line, and returns the summary text.
- Exercise 3hard
Estimate the monthly token cost and the peak tokens-per-minute need for 20,000 files a month, with a 600-token prompt, 120-token replies, maxTokens of 200, and a peak of 40 files per minute. Use placeholder prices of P_in and P_out per 1,000 tokens.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Do I still have to request model access in the Bedrock console?
- In commercial Regions, most models are enabled on first use if the caller has the right AWS Marketplace permissions and the account has a payment method. Some older Anthropic models still need a one-time use case form. The Model access page is now for AWS GovCloud (US).
- Is Bedrock included in the AWS Free Tier?
- Do not assume it is. Model calls are billed per token, and the new account credit rules change over time, so check the Free Tier and Bedrock pricing pages, set a budget alert, and use the local stub for most of your testing.
- Does AWS use my prompts to train the models?
- AWS states that Bedrock does not use your prompts and replies to train its base models or share them with model providers. Read the current Bedrock data protection page for the exact wording before you send real customer data.
- Should my app call InvokeModel or Converse?
- Use Converse for chat and text tasks, because one code path works across models. Use InvokeModel when a model or feature needs its own native request body, such as some embedding or image models.