
Amazon BedrockAuthorCloudBrum editorial teamLast reviewedReading time~12 minLevelBeginner to advanced
Amazon Web Services · AI and machine learning · Foundation models, RAG and agents
Amazon Bedrock lets you call foundation models from many companies through one AWS service, with no model servers to run. You pick a model (Amazon’s Nova, Anthropic’s Claude, Meta, Mistral, DeepSeek, OpenAI’s open-weight models and more), send messages through the Converse API and pay by the token. Knowledge Bases bring in your documents, Guardrails apply safety rules, and Agents and AgentCore handle tools and multi-step work. Most surprises come from quotas, which count the longest answer you allow before the call even starts, and from the pieces that are billed on the side.
On this page (17 sections)
Mind map: Amazon Bedrock at a glance
Free to share. The downloaded image includes the CloudBrum link.
Key features (summary)
- Many models, one accountModels from Amazon, Anthropic, Meta, Mistral AI, DeepSeek, OpenAI and other providers sit behind the same service and the same IAM. Trying another one is mostly a change to a single string.
- One way to talk to chat modelsThe Converse API takes messages, a system prompt and tool definitions in a common shape, and returns the answer, the stop reason and the token counts. InvokeModel stays for models and tasks that need their own request format, such as embeddings or images.
- Your documents as contextPoint a knowledge base at files in S3 and other sources. Bedrock splits and embeds them, keeps the vectors in a store, and finds the best passages when someone asks. The retrieve-and-generate call returns an answer with citations.
- Safety rules in one placeA guardrail bundles content filters, denied topics, word lists, sensitive information filters and a check that answers stay close to your source text. It can sit on a model call, an agent or a knowledge base, and ApplyGuardrail checks text from any source.
- Agents and AgentCoreAgents plan steps and call your systems through action groups, each backed by an OpenAPI schema or a Lambda function. AgentCore is the newer toolkit for running agents built with any framework, with Runtime, Gateway, Memory and Identity among its parts.
- Cross-Region inferenceAn inference profile lets Bedrock send each request to a Region in its group that has capacity. Profiles are geographic (the apac. prefix, for example) or global, and some newer models can only be called through one.
- Make a model fit your workFine-tune a model, keep pre-training it on your text, import one you trained elsewhere, or distil a large model into a smaller one, where the model supports it. A fine-tuned model is usually served through Provisioned Throughput, though some models can be deployed on demand.
- Pay as you go, or reserveOn-demand tokens are the default. Batch jobs cost about half on supported models, Flex and Priority tiers trade price for speed on some, and Provisioned Throughput reserves capacity by the hour for steady traffic.
Basic concepts
- Foundation model
- A large pretrained model for text, images or embeddings that you call instead of training your own.
- Model ID
- The string that names a model in a call, such as amazon.nova-lite-v1:0.
- Inference profile
- A named route that spreads requests over several Regions. Its ID, with a prefix such as apac. or global., goes where the model ID would.
- Converse API
- The common chat call. It takes messages, a system prompt, tools and a guardrail, and returns the reply, stopReason and usage.
- Token
- A piece of text, often a short word or part of one. Prices and quotas are counted in tokens, and output tokens cost more than input tokens on most models.
- Context window
- The most tokens a model can take in one request, prompt and answer together.
- Embedding
- A list of numbers that stands for the meaning of a text, used to find similar passages.
- Knowledge base
- A managed pipeline that reads your documents, makes embeddings, stores them in a vector store and retrieves passages for a question.
- Guardrail
- A set of filters for prompts and answers, kept as a draft and published as numbered versions.
- Agent and action group
- An agent plans and calls tools. An action group is one set of tools, defined by an OpenAPI schema or a Lambda function.
- Provisioned Throughput
- Reserved capacity measured in model units and billed by the hour, with no commitment, a one-month or a six-month term.
- Batch inference
- A job that runs many prompts from a file in S3 and writes the answers back, at a lower price and without a quick reply.
- Prompt caching
- Reuse of a long, unchanged start of a prompt across calls, which cuts both cost and delay on models that support it.
- Model invocation logging
- An optional record of prompts and answers in S3 or CloudWatch Logs. It is off until you turn it on.
How to create & configure it
Make a first call, then add a guardrail and monitoring, with the AWS CLI
- Choose a Region and a modelCheck the model’s entry in the Bedrock catalogue for the Regions it runs in and whether it needs an inference profile. For India, Mumbai (ap-south-1) and Hyderabad (ap-south-2) are closest, and some models are reachable there only through a geographic or global profile.
- Sort out accessServerless models have been switched on by default in commercial Regions since October 2025. Anthropic models still want a one-time use-case form per account, and models sold through AWS Marketplace need Marketplace permissions on their first call. Have an administrator do both before the team starts.
- Give the caller the least it needsAllow bedrock:InvokeModel only on the inference profile and the foundation model you picked. A profile that spans Regions needs the model allowed in each destination Region.
- Call the Converse APIStart from the CLI or the console playground, with a small maxTokens. Read stopReason and usage in the reply, so you see why it ended and what it used.
- Add a guardrailCreate one with the content filters and sensitive data rules you need, publish a numbered version, and attach that version to the call.
- Decide about invocation loggingA log holds every prompt and answer, so pick the destination, the encryption and the retention first. Leave it off for tests that use real customer text until you’re ready.
- Check your quotasFind the tokens-per-minute and requests-per-minute values for your model and Region before launch, and ask for more well ahead of a busy day.
- Watch and cap spendAlarm on InvocationThrottles, chart InputTokenCount and OutputTokenCount, and put a budget alert on Bedrock.
- Add your data and tools lastBring in a knowledge base or an agent once the plain call works. Each brings its own cost, permissions and ways to fail.
Tip: judge models on your own questions, not on a public leaderboard. Keep ten to thirty real questions with the answers you expect, and run them again whenever the model or the prompt changes. See the code references for the same setup as Terraform.
Common issues after configuration
| Symptom | Likely cause | What to check / fix |
|---|---|---|
| AccessDeniedException saying you don’t have access to the model | The model isn’t enabled for the account, the Anthropic use-case form is missing, Marketplace permissions are absent, or the IAM policy doesn’t name the model or profile | Submit the form once, let a Marketplace-enabled user make the first call, and allow the exact inference profile and foundation model ARNs. |
| ValidationException: invocation with on-demand throughput isn’t supported | The model can only be called through an inference profile | Use the profile ID (for example one starting apac., us. or global.) in place of the bare model ID, and allow the profile in IAM. |
| ThrottlingException at low traffic | A tokens-per-minute quota is used up early because the call reserves input tokens plus maxTokens when it starts, and Claude-type models can count output tokens at a higher rate | Set maxTokens close to the real answer size, retry with backoff, spread calls over time, request a quota increase, or use a cross-Region profile or Provisioned Throughput. |
| ModelNotReadyException, ServiceUnavailableException or a timeout | The model is scaling up or capacity is tight | Retry with exponential backoff and jitter, raise the client read timeout for long answers, and have a fallback model ready. |
| ValidationException: input is too long | Prompt, history and retrieved text together pass the context window | Trim old turns, summarise history, retrieve fewer passages, or move to a model with a larger window. |
| The answer stops mid-sentence | stopReason is max_tokens | Raise maxTokens if you really need the rest, or ask for a shorter answer in the prompt. |
| stopReason is guardrail_intervened | A guardrail blocked the input or the output | Read the trace to see which filter fired, tune the filter or the wording, and show users the blocked message you chose. |
| The knowledge base returns nothing, or the wrong passages | The data source wasn’t synced after files changed, chunks are too large or small for the questions, or a metadata filter excludes the right files | Run a new ingestion job and read its status, try other chunking, test retrieval on its own before blaming the model. |
| It works in the console but not from Lambda or ECS | The role lacks bedrock:InvokeModel on the profile and on the models in every destination Region, or a service control policy blocks a Region | Compare the role with the policy in step 3, and read the error’s Region and resource. |
| Answers differ on every run | Temperature and other sampling settings allow variation | Lower temperature for factual work, and keep a fixed set of test questions to compare runs. |
| The bill is higher than expected | Long prompts and histories, big outputs, a vector store with a minimum charge, Provisioned Throughput left on, or per-call extras | Chart token counts per feature, cap maxTokens, cache repeated prompt starts, delete idle capacity, and read the line items for Guardrails, the vector store and AgentCore. |
Use cases: when and where to use it
Good fit
- Chat, summaries, drafting and extraction inside an application, without running model servers
- Question answering over your own documents, with citations
- Teams that want to switch between several model families without rewriting the app
- Workloads that must stay in an AWS account, with IAM, PrivateLink and KMS around the calls
- Agents that call internal APIs under tight permissions
- Overnight batch jobs such as tagging or summarising a large archive
Consider something else
- Training or hosting a model of your own → Amazon SageMaker
- A fixed task such as reading text from scans → the ready-made AI services (Textract, Comprehend, Rekognition, Transcribe), which are often cheaper and steadier
- Search over text without a language model → Amazon OpenSearch Service
- Wiring model calls to events and schedules → Amazon EventBridge and AWS Lambda
- The same job on other clouds → compare Microsoft Foundry and the Gemini API and Model Garden
- Training your own models on Google Cloud → the machine learning page for the Gemini Enterprise Agent Platform (Vertex AI)
Pros: why consider it?
Why teams choose it
- No model servers to size, patch or scale
- Many model families behind one API and one set of permissions
- Guardrails, Knowledge Bases and agents are part of the same service
- Inputs and outputs aren’t used to train the base models or handed to the model providers, according to AWS
- Fits the rest of AWS: IAM, KMS, PrivateLink, CloudWatch, CloudTrail
- Batch, caching and tiers give several ways to bring the price down
Trade-offs to weigh
- Quotas count the longest answer you allow, and throttling shows up before real traffic does
- Model lists, versions and Regions change fast, and older models are retired
- The price has many parts, and some of them hide on other lines of the bill
- Some models can only be reached through an inference profile, which moves requests between Regions
- Anthropic and Marketplace models add an access step the first time
- Agent and knowledge base behaviour is harder to test than a plain model call
Common threats, vulnerabilities & risks
| Risk | Severity | Why it matters | Mitigation |
|---|---|---|---|
| Prompt injection through documents and user text | High | A web page, a PDF or a user message can carry instructions that try to override yours and make the model leak data or call a tool. | Treat model output as untrusted input, keep tools narrow, turn on the prompt-attack filter, and ask a person to approve actions that change things. |
| An agent with wide permissions | High | An agent role that can read every bucket or call every API turns one bad answer into a real incident. | Give each action group its own role with the few actions it needs, and log every tool call. |
| Personal or secret data in prompts and logs | High | Prompts often include customer details, and invocation logs keep them. | Mask or block sensitive data with a guardrail, encrypt logs with KMS, set a short retention period and limit who can read them. |
| No spending limit | High | A loop, a bug or a public endpoint can run thousands of long calls overnight. | Cap maxTokens, rate-limit users, set budgets and alarms on token metrics, and keep API keys out of reach. |
| Confident wrong answers | Medium | A model can state something false in a calm tone, and retrieval does not remove that risk. | Ground answers in a knowledge base, show citations, use the contextual grounding check, and test with questions whose answers you know. |
| Long-lived Bedrock API keys | Medium | A long-term key tied to an IAM user can leak and may never expire. | Prefer short-term keys or IAM roles, and use a service control policy to deny long-term keys. |
| A model is retired or changed | Medium | Providers retire versions, and a newer model may answer differently. | Pin the model version, keep your test questions, watch the AWS Health Dashboard for lifecycle notices and plan the switch well before the end date. |
| Requests leave the Region you expected | Low–Med | A global inference profile can send requests to any supported commercial Region. | Use a geographic profile or a single-Region model when rules limit where data may go, and check your SCPs. |
| A knowledge base that shows too much | Low–Med | Anyone who can query a knowledge base can get passages from every file in it. | Build separate knowledge bases per audience, or filter on metadata, and keep restricted files out. |
Performance optimisation
- Pick the smallest model that passes your tests. Small models answer sooner and cost less, and plenty of tasks never need the largest one.
- Stream the answer so people see words at once, even when the full reply takes seconds.
- Keep prompts short and put the long, unchanging part first so prompt caching can reuse it.
- Set maxTokens to what the answer needs. It speeds up the call and spares your quota.
- Use batch inference for work nobody is waiting for.
- Send calls through a cross-Region inference profile when one Region runs out of capacity.
- Retrieve fewer, better passages from a knowledge base and test chunk sizes on real questions.
- Run independent calls in parallel up to your requests-per-minute quota, and add backoff for the rest.
Reduce monthly cost
FinOps is the habit of managing cloud spend together with engineering. These are the FinOps checks that matter most for Amazon Bedrock.
- Start with the smallest model that gives acceptable answers, and compare cost per correct answer, not price per token alone.
- Send offline work to batch on models that support it, for about half the on-demand price.
- Turn on prompt caching for long system prompts and documents that repeat between calls.
- Trim the history and retrieved text you send, because input tokens are billed again on every turn.
- Cap output length with maxTokens and ask for short answers where short is enough.
- Check the vector store behind a knowledge base. Some stores carry a minimum monthly charge even when idle, and deleting a knowledge base may leave the store running.
- Delete Provisioned Throughput you aren’t using, and compare its hourly cost with on-demand at your real traffic.
- Use Flex or intelligent prompt routing where the model supports them.
- Evaluate guardrails per policy. Each filter is metered by text unit, and a blocked prompt is still charged for the check.
- Tag by team, set a budget alert, and review token metrics weekly.
Rates and tiers change often, and the pages I read disagreed on some figures. This page therefore describes the bill and its ratios without dollar amounts. Read the live rates for your model and Region (see Pricing).
Security optimisation
- Call Bedrock with IAM roles, and allow only the models and profiles each app needs.
- Prefer short-term Bedrock API keys if you must use keys, and block long-term ones with a service control policy.
- Use PrivateLink (VPC endpoints) so calls stay off the public internet.
- Encrypt with KMS keys you control for custom models, knowledge base data, vector indexes and logs, since each is set separately.
- Attach a guardrail with a prompt-attack filter and sensitive information rules to user-facing apps.
- Turn on invocation logging only with a destination you have locked down, and set a retention period.
- Send CloudTrail events to a protected account and alert on changes to guardrails, logging and model access.
- Choose geographic inference profiles when data location rules apply.
- Give each agent action group its own narrow role and validate every tool input.
- Review third-party and Marketplace models' terms and data handling before approving them.
Governance & compliance
Guardrails
- A shared Terraform module that creates the invoke policy, a guardrail, a log group and an alarm for each app
- A service control policy that limits which Regions and which models accounts may use, and denies long-term API keys
- A model approval list: who owns each model, which data it may see and when it was last reviewed
- A prompt and test set stored with the code, so a change to model or wording is checked against the same questions
Continuous checks (CloudTrail, CloudWatch and your own scripts)
- A scheduled script that lists guardrails and flags apps that call models without one
- Alarms on InvocationThrottles, client errors and unusually high OutputTokenCount
- A CloudTrail alert for changes to logging, model access and guardrails
- A weekly report of token use by team and by model
- A check for models in use that AWS has retired or plans to retire
AWS CloudTrail records who changed Bedrock settings and, where you turn on the right event types, who called the APIs. CloudWatch holds the runtime metrics, and AWS Artifact has compliance reports. AWS runs the models' hosting and the service. Which model you pick, what you put in prompts, how you test answers and what an agent may do are yours.
Reduce carbon footprint
- Use the smallest model that does the job. Compute grows with model size, and so does the energy behind it.
- Cache repeated prompt starts and answers, so the same work isn’t done twice.
- Send overnight work as a batch job instead of thousands of single calls.
- Delete idle Provisioned Throughput and unused knowledge base stores.
- Where data rules and delay allow, run in a Region with a cleaner power grid.
- No per-request energy figure for a hosted model has been published that we could verify, so none appears here.
Pricing
Purchase options
On demand Per token
You pay for input tokens and output tokens at a rate set for each model. Output tokens cost more than input tokens on most models, and models with caching bill cached input and cache writes at their own rates.
Batch About half the on-demand price
Asynchronous jobs on supported models. Results come back within a window you choose (24 to 168 hours in one source I read), at roughly half the standard rate.
Service tiers Flex lower, Priority higher
On selected models, Flex costs less and starts more slowly, and Priority costs more for quicker, steadier replies. Not every model offers them.
Provisioned Throughput Per model unit, per hour
Reserved capacity in model units, with no commitment, a one-month or a six-month term. It bills every hour used or not, and a fine-tuned model is usually served this way.
Around the model Billed separately
Guardrails by text unit, Knowledge Bases by vector store and queries, AgentCore by component, and Marketplace models at the seller’s price. An embedding call is a model call too.
What you actually pay for
- Input and output tokens for every model call, including the embedding calls a knowledge base makes
- Provisioned Throughput model units for each hour they exist
- Guardrail checks, even when the check blocks the prompt
- The vector store behind a knowledge base, plus its storage and queries
- AgentCore components, Marketplace model fees, logs, S3 and data transfer
AWS publishes the rate for every model, Region and mode on its pricing page, and the figures differ by model and move over time. See the official Amazon Bedrock pricing page and the AWS Pricing Calculator.
Important code references
A first Bedrock setup: list what you can call, ask a question through the Converse API, create and publish a guardrail, attach it, turn on invocation logging, read your token quotas and alarm on throttled calls. The CLI tab runs them in order. Terraform builds the invoke policy, the guardrail and its version, the log group, the logging role and the alarm. The Python tab adds retries, streaming and the ApplyGuardrail check, and the C# tab sends a guarded Converse call and exits with 1 when the guardrail steps in. Replace the Region and the model with ones your account can use.
# Placeholders: replace the Region and the model. Use a model ID or inference profile ID that "aws bedrock list-foundation-models" and "list-inference-profiles" show for your account.
REGION=ap-south-1
MODEL_ID=apac.amazon.nova-lite-v1:0
# 1. What can I call here? Text models you can use on demand, and the inference profiles (a profile spreads requests over several Regions).
aws bedrock list-foundation-models --region $REGION --by-output-modality TEXT --by-inference-type ON_DEMAND \
--query "modelSummaries[].[providerName,modelId]" --output table
aws bedrock list-inference-profiles --region $REGION --query "inferenceProfileSummaries[].inferenceProfileId" --output text
# 2. Ask a question through the Converse API. Keep maxTokens close to what you need, because it counts against your quota when the call starts.
aws bedrock-runtime converse --region $REGION --model-id $MODEL_ID \
--system '[{"text":"Answer in at most three sentences."}]' \
--messages '[{"role":"user","content":[{"text":"What is a guardrail in Amazon Bedrock?"}]}]' \
--inference-config '{"maxTokens":200,"temperature":0.2}' \
--query "{answer:output.message.content[0].text,stop:stopReason,tokens:usage}"
# 3. A guardrail: block hateful or attack-style prompts, mask email addresses, block card numbers. Then publish a numbered version to use.
GUARDRAIL_ID=$(aws bedrock create-guardrail --region $REGION --name support-bot \
--blocked-input-messaging "Sorry, I can't help with that request." --blocked-outputs-messaging "Sorry, I can't share that answer." \
--content-policy-config '{"filtersConfig":[{"type":"HATE","inputStrength":"HIGH","outputStrength":"HIGH"},{"type":"PROMPT_ATTACK","inputStrength":"HIGH","outputStrength":"NONE"}]}' \
--sensitive-information-policy-config '{"piiEntitiesConfig":[{"type":"EMAIL","action":"ANONYMIZE"},{"type":"CREDIT_DEBIT_CARD_NUMBER","action":"BLOCK"}]}' \
--query guardrailId --output text)
GUARDRAIL_VERSION=$(aws bedrock create-guardrail-version --region $REGION --guardrail-identifier $GUARDRAIL_ID --query version --output text)
# 4. The same question with the guardrail attached. If the guardrail steps in, stopReason is guardrail_intervened.
aws bedrock-runtime converse --region $REGION --model-id $MODEL_ID \
--messages '[{"role":"user","content":[{"text":"My card number is 4111 1111 1111 1111, can you remember it?"}]}]' \
--guardrail-config guardrailIdentifier=$GUARDRAIL_ID,guardrailVersion=$GUARDRAIL_VERSION \
--query "{answer:output.message.content[0].text,stop:stopReason}"
# 5. Keep a record of prompts and answers in CloudWatch Logs. Anything users type ends up in that log group, so lock it down and set a retention period.
aws bedrock put-model-invocation-logging-configuration --region $REGION --logging-config '{"cloudWatchConfig":{"logGroupName":"/bedrock/invocations","roleArn":"arn:aws:iam::123456789012:role/bedrock-invocation-logs"},"textDataDeliveryEnabled":true,"imageDataDeliveryEnabled":false,"embeddingDataDeliveryEnabled":false}'
# 6. Your token quotas for this Region. If the call above is throttled, this is where the ceiling is.
aws service-quotas list-service-quotas --region $REGION --service-code bedrock \
--query "Quotas[?contains(QuotaName, 'tokens per minute')].[QuotaName,Value]" --output text | head -5
# 7. Throttled calls in the last hour. The dimension is the model ID or inference profile ID you call.
aws cloudwatch get-metric-statistics --region $REGION --namespace AWS/Bedrock --metric-name InvocationThrottles \
--dimensions Name=ModelId,Value=$MODEL_ID --statistics Sum --period 300 \
--start-time $(date -u -d '-1 hour' +%FT%TZ) --end-time $(date -u +%FT%TZ)
# 8. An alarm for the same signal.
aws cloudwatch put-metric-alarm --region $REGION --alarm-name bedrock-throttles --namespace AWS/Bedrock --metric-name InvocationThrottles \
--dimensions Name=ModelId,Value=$MODEL_ID --statistic Sum --period 300 --evaluation-periods 2 --threshold 20 \
--comparison-operator GreaterThanThreshold --treat-missing-data notBreaching
# Placeholders: set the Region and the model. A least-privilege policy for the app, a guardrail with a published version,
# invocation logs in CloudWatch, and an alarm on throttled calls.
variable "region" {
type = string
default = "ap-south-1"
}
variable "model_id" {
type = string
default = "apac.amazon.nova-lite-v1:0"
}
provider "aws" {
region = var.region
}
data "aws_caller_identity" "current" {}
# The app may call only this inference profile and the foundation models behind it, nothing else in Bedrock.
resource "aws_iam_policy" "invoke" {
name = "bedrock-invoke-nova-lite"
policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Action = ["bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream"]
Resource = [
"arn:aws:bedrock:${var.region}:${data.aws_caller_identity.current.account_id}:inference-profile/${var.model_id}",
"arn:aws:bedrock:*::foundation-model/amazon.nova-lite-v1:0",
]
}]
})
}
resource "aws_bedrock_guardrail" "support_bot" {
name = "support-bot"
blocked_input_messaging = "Sorry, I can't help with that request."
blocked_outputs_messaging = "Sorry, I can't share that answer."
content_policy_config {
filters_config {
type = "HATE"
input_strength = "HIGH"
output_strength = "HIGH"
}
filters_config {
type = "PROMPT_ATTACK"
input_strength = "HIGH"
output_strength = "NONE"
}
}
sensitive_information_policy_config {
pii_entities_config {
type = "EMAIL"
action = "ANONYMIZE"
}
pii_entities_config {
type = "CREDIT_DEBIT_CARD_NUMBER"
action = "BLOCK"
}
}
}
# Applications call a numbered version, so a later edit of the draft cannot change live behaviour.
resource "aws_bedrock_guardrail_version" "v1" {
guardrail_arn = aws_bedrock_guardrail.support_bot.guardrail_arn
description = "First published version"
}
resource "aws_cloudwatch_log_group" "invocations" {
name = "/bedrock/invocations"
retention_in_days = 30
}
data "aws_iam_policy_document" "logs_trust" {
statement {
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = ["bedrock.amazonaws.com"]
}
condition {
test = "StringEquals"
variable = "aws:SourceAccount"
values = [data.aws_caller_identity.current.account_id]
}
}
}
resource "aws_iam_role" "logs" {
name = "bedrock-invocation-logs"
assume_role_policy = data.aws_iam_policy_document.logs_trust.json
}
resource "aws_iam_role_policy" "logs" {
role = aws_iam_role.logs.id
policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Action = ["logs:CreateLogStream", "logs:PutLogEvents"]
Resource = "${aws_cloudwatch_log_group.invocations.arn}:*"
}]
})
}
# Prompts and answers land in this log group, so treat it as sensitive data.
resource "aws_bedrock_model_invocation_logging_configuration" "this" {
logging_config {
text_data_delivery_enabled = true
image_data_delivery_enabled = false
embedding_data_delivery_enabled = false
cloudwatch_config {
log_group_name = aws_cloudwatch_log_group.invocations.name
role_arn = aws_iam_role.logs.arn
}
}
}
resource "aws_cloudwatch_metric_alarm" "throttles" {
alarm_name = "bedrock-throttles"
namespace = "AWS/Bedrock"
metric_name = "InvocationThrottles"
dimensions = { ModelId = var.model_id }
statistic = "Sum"
period = 300
evaluation_periods = 2
threshold = 20
comparison_operator = "GreaterThanThreshold"
treat_missing_data = "notBreaching"
}
output "guardrail_id" {
value = aws_bedrock_guardrail.support_bot.guardrail_id
}
output "guardrail_version" {
value = aws_bedrock_guardrail_version.v1.version
}
# pip install boto3
# Asks a model a question through the Converse API, retries when Bedrock throttles, streams an answer,
# and checks a piece of text against a guardrail without calling a model at all.
import os
import boto3
from botocore.config import Config
REGION = os.environ.get("AWS_REGION", "ap-south-1")
MODEL_ID = os.environ.get("MODEL_ID", "apac.amazon.nova-lite-v1:0") # replace with a model or inference profile your account can use
# "adaptive" retries slow the client down when Bedrock answers ThrottlingException, instead of hammering it.
runtime = boto3.client("bedrock-runtime", region_name=REGION,
config=Config(retries={"mode": "adaptive", "max_attempts": 8}, read_timeout=120))
def ask(question, system="Answer in at most three sentences.", max_tokens=300, guardrail=None):
"""Returns (text, stop_reason, usage). max_tokens counts against your quota when the request starts, so keep it close to what you need."""
request = {
"modelId": MODEL_ID,
"system": [{"text": system}],
"messages": [{"role": "user", "content": [{"text": question}]}],
"inferenceConfig": {"maxTokens": max_tokens, "temperature": 0.2},
}
if guardrail:
request["guardrailConfig"] = {"guardrailIdentifier": guardrail[0], "guardrailVersion": guardrail[1]}
reply = runtime.converse(**request)
text = "".join(block.get("text", "") for block in reply["output"]["message"]["content"])
return text, reply["stopReason"], reply["usage"]
def ask_streaming(question, max_tokens=300):
"""Prints the answer as it arrives, and returns the token usage that comes with the last event."""
stream = runtime.converse_stream(
modelId=MODEL_ID,
messages=[{"role": "user", "content": [{"text": question}]}],
inferenceConfig={"maxTokens": max_tokens},
)
usage = {}
for event in stream["stream"]:
if "contentBlockDelta" in event:
print(event["contentBlockDelta"]["delta"].get("text", ""), end="", flush=True)
if "metadata" in event:
usage = event["metadata"]["usage"]
print()
return usage
def allowed(text, guardrail_id, guardrail_version, source="INPUT"):
"""True when the guardrail lets the text through. ApplyGuardrail works on any text, including text from models that do not run on Bedrock."""
reply = runtime.apply_guardrail(guardrailIdentifier=guardrail_id, guardrailVersion=guardrail_version, source=source,
content=[{"text": {"text": text}}])
return reply["action"] != "GUARDRAIL_INTERVENED"
def cost(usage, per_million_input, per_million_output):
"""Rough price of one call. Take the two prices from the pricing page for your model and Region."""
return (usage["inputTokens"] * per_million_input + usage["outputTokens"] * per_million_output) / 1_000_000
if __name__ == "__main__":
answer, stop, used = ask("What does a guardrail do in Amazon Bedrock?")
print(answer)
print("stop reason:", stop, "| tokens in/out:", used["inputTokens"], used["outputTokens"])
if stop == "max_tokens":
print("The answer was cut off. Raise max_tokens only if you need the rest.")
// dotnet add package AWSSDK.BedrockRuntime
// Sends one question through the Converse API with a guardrail attached, then reports the stop reason and the token counts.
// Exits with 1 when the guardrail blocked the request, so a pipeline can notice.
using Amazon;
using Amazon.BedrockRuntime;
using Amazon.BedrockRuntime.Model;
string modelId = Environment.GetEnvironmentVariable("MODEL_ID") ?? "apac.amazon.nova-lite-v1:0"; // replace with a model or inference profile you can use
string? guardrailId = Environment.GetEnvironmentVariable("GUARDRAIL_ID");
string guardrailVersion = Environment.GetEnvironmentVariable("GUARDRAIL_VERSION") ?? "1";
using var client = new AmazonBedrockRuntimeClient(RegionEndpoint.APSouth1);
var request = new ConverseRequest
{
ModelId = modelId,
System = new List<SystemContentBlock> { new SystemContentBlock { Text = "Answer in at most three sentences." } },
Messages = new List<Message>
{
new Message
{
Role = ConversationRole.User,
Content = new List<ContentBlock> { new ContentBlock { Text = "What does a guardrail do in Amazon Bedrock?" } }
}
},
InferenceConfig = new InferenceConfiguration { MaxTokens = 300, Temperature = 0.2f }
};
if (!string.IsNullOrEmpty(guardrailId))
{
request.GuardrailConfig = new GuardrailConfiguration
{
GuardrailIdentifier = guardrailId,
GuardrailVersion = guardrailVersion,
Trace = GuardrailTrace.Enabled
};
}
ConverseResponse response = await client.ConverseAsync(request);
Console.WriteLine(string.Join("", response.Output.Message.Content.Select(block => block.Text)));
Console.WriteLine($"stop reason: {response.StopReason.Value} | tokens in/out: {response.Usage.InputTokens}/{response.Usage.OutputTokens}");
if (response.StopReason == StopReason.Guardrail_intervened)
{
Console.WriteLine("The guardrail blocked this request.");
return 1;
}
if (response.StopReason == StopReason.Max_tokens)
{
Console.WriteLine("The answer was cut off at the token limit.");
}
return 0;
Best videos to explore
Videos picked for this service. Each one is labelled with its source, opens on YouTube if you prefer, and loads only when you press play.
Interview questions
BasicWhat is Amazon Bedrock?
It’s the AWS service for using foundation models without hosting them. You choose a model from providers such as Amazon, Anthropic, Meta, Mistral AI, DeepSeek and OpenAI, call it through an API, and pay for what you use. Features such as Knowledge Bases, Guardrails and Agents add your documents, safety rules and tools.
BasicWhat is the Converse API?
It’s the common way to chat with Bedrock models. You send a system prompt, messages and optional tools in one format, and get back the reply, the reason it stopped and the token counts. Switching models usually means changing the model ID.
BasicDoes Bedrock use my prompts to train its models?
According to AWS, no. Your inputs and outputs aren’t used to train the base models and aren’t shared with the model providers. If you turn on invocation logging, the records go to your own S3 bucket or log group, so you are responsible for protecting them.
IntermediateWhat is an inference profile and why do I need one?
It’s a named route that lets Bedrock send a request to any Region in a group that has capacity. Some models can only be called through a profile, and you get a validation error about on-demand throughput if you use the bare model ID. Geographic profiles keep requests inside an area such as Asia Pacific, and global profiles may use any supported commercial Region.
IntermediateWhy am I throttled when my traffic is small?
Quotas count tokens. When a call starts, Bedrock reserves the input tokens plus the maxTokens you allow, and afterwards it settles on what was actually used, with output tokens counted at a model-specific rate. A large maxTokens on many calls fills the tokens-per-minute quota fast, so set it close to the real answer length.
IntermediateHow does a knowledge base work?
It reads your files from a source such as S3, splits them into chunks, turns the chunks into embeddings and stores them in a vector store. At question time it finds the closest chunks and passes them to the model, and the retrieve-and-generate call returns an answer with citations. You must sync the source again after files change.
AdvancedHow would you design a safe customer-facing assistant on Bedrock?
Put the model behind your own API with authentication and per-user rate limits. Attach a guardrail with prompt-attack and sensitive information rules, ground answers in a knowledge base with citations, give any agent narrow action groups, and log with encryption and a short retention. Cap maxTokens, alarm on throttles and token spikes, and keep a test set you rerun whenever the model or prompt changes.
AdvancedWhen would you choose Provisioned Throughput over on-demand?
When traffic is steady and high enough that reserved model units cost less than tokens, when you need predictable capacity, or when you serve a fine-tuned model, which usually runs on it. Compare the hourly price with your measured monthly tokens, remember it bills whether or not you call, and start without a commitment before taking a one-month or six-month term.
AdvancedHow do you control cost on a Bedrock application?
Use the smallest model that passes your tests, cache repeated prompt starts, trim history and retrieved text, and cap output length. Send offline work to batch, remove idle Provisioned Throughput, and check the vector store and guardrail line items. Chart token counts per feature, set budgets, and compare cost per correct answer instead of price per token.
AdvancedHow do you test and release changes to a prompt or a model?
Keep a fixed set of questions with expected answers or scoring rules, run it against the current and the new setup, and compare accuracy, refusals, length, delay and cost. Roll out to a small share of traffic first, watch the error and guardrail metrics, and keep the previous model ID and prompt ready to restore.
Similar or alternative services on other clouds
| Capability | AWS | Azure | Google Cloud |
|---|---|---|---|
| Service | Amazon Bedrock | Microsoft Foundry (formerly Azure AI Foundry), with Foundry Models | Gemini API and Model Garden on Vertex AI (now the Gemini Enterprise Agent Platform) |
| Chat model API | Converse and InvokeModel | Responses and chat completions APIs on a deployment | Gemini API (generateContent) through the Google Gen AI SDK |
| Model choice | Amazon, Anthropic, Meta, Mistral AI, DeepSeek, OpenAI and others | Models sold by Azure, plus partner and community models | Gemini, partner models such as Claude, and open models |
| Your own data (RAG) | Knowledge Bases | Foundry IQ and Azure AI Search | RAG Engine and Vertex AI Search |
| Safety filters | Guardrails and ApplyGuardrail | Content filters and Prompt Shields | Safety settings and Model Armor |
| Agents | Agents and AgentCore | Foundry Agent Service | Agent Engine and the Agent Development Kit |
| Reserved capacity | Provisioned Throughput (model units) | Provisioned throughput (PTUs) | Provisioned Throughput (GSUs) |
| Spread over Regions | Inference profiles, geographic or global | Global Standard and Data Zone deployments | Global endpoint or a regional endpoint |
| Typical identity | IAM roles | Microsoft Entra ID roles | IAM service accounts |
Typical companions are Amazon S3 for documents, AWS Lambda for glue code, Amazon CloudWatch for metrics and alarms and AWS KMS for keys. To train or host a model of your own, look at Amazon SageMaker.
Did you find this article helpful?
Your answer helps us improve this page for the next reader.
Sources and further reading
CloudBrum wrote this page in its own words, using the provider’s public documentation listed below as the reference. Features, limits, names and prices change, so confirm anything that matters on the provider’s own pages before you decide.
- What is Amazon Bedrock?Amazon Web Services
- Access Amazon Bedrock foundation modelsAmazon Web Services
- How Amazon Bedrock Guardrails worksAmazon Web Services
- How Amazon Bedrock Agents worksAmazon Web Services
- How tokens are counted in Amazon BedrockAmazon Web Services
- Global cross-Region inferenceAmazon Web Services
- Prompt caching for faster model inferenceAmazon Web Services
- Monitor bedrock-runtime inference using CloudWatch metricsAmazon Web Services
- Amazon Bedrock pricingAmazon Web Services
- Terraform AWS provider: aws_bedrock_guardrailHashiCorp
