AWS Builder Center

Get Cost Savings and SLA Guarantees from Batch Inference on Bedrock

Amazon Bedrock batch inference saves up to 50% on per-token costs but offers no completion-time guarantee. This post shows how to build a Step Functions workflow that tries batch first and automatically falls back to on-demand if your deadline is at risk.

AI ML Solutions Architect -HCLS

Get Cost Savings and SLA Guarantees from Batch Inference on Bedrock

There's a well-known tension in production ML pipelines: cost versus reliability.  Amazon Bedrock batch inference  cuts your per-token bill by up to 50% for select models compared to on-demand — but it gives you zero SLA guarantees. This post walks through an architecture that tries batch first for the savings, then falls back to on-demand automatically if the deadline is at risk. The combination of the two offers you the ability to work towards your required SLAs.
A batch job can vary greatly, with some taking just a few minutes while others can run for several hours. There's no way to know ahead of time. For offline workloads that can truly wait — document indexing, nightly enrichment, historical re-ranking — that's fine. But many real pipelines have a softer deadline. You need results ready before the morning dashboard runs, before the report goes out, before the downstream job kicks off. "Sometime today" isn't good enough.
Two common approaches both fall short. You can submit everything as on-demand requests and pay full price. Or you can submit your batch job and hope that it finishes within the timeframe you need. What you actually want is to try batch first — it's cheaper — but implement a strategic switch if the deadline is at risk. That's the objective this post sets out to describe and illustrate.

Solution overview

The idea is simple: submit your work as a Bedrock batch job, but wrap it in an  AWS Step Functions  state machine that's watching the clock. Three independent mechanisms — an  Amazon CloudWatch  alarm, an  Amazon EventBridge  rule, and a built-in Step Functions timeout — all three working together to monitor the active batch job and ensure it's not at risk of exceeding the given timeframe. If any of them fires, the system stops the batch job, figures out which records still need processing, and redrives them through on-demand. No manual intervention, no pager.

Prerequisites

To deploy this solution, you need the following:
  • An  AWS account  with permissions to create Step Functions, Lambda, DynamoDB, S3, CloudWatch, EventBridge, and SNS resources
  •  AWS CDK v2  installed and bootstrapped in your target account and region
  • Basic familiarity with Step Functions, Lambda, and Amazon Bedrock

The shape of the problem

The challenging part isn't that the batch job completes in time, you process the results, and you're done — it's what happens outside of this expected path.
What does "deadline at risk" actually mean? You need to account for drain time — the time it takes to stop a running batch job and process remaining records on-demand — plus a safety buffer. The safety buffer is additional time you reserve beyond the drain estimate to absorb variability: network hiccups, cold starts on the on-demand path, or a larger-than-expected set of unprocessed records. Without it, you'd be cutting the deadline so close that any small surprise pushes you past your SLA. So the cutoff isn't "SLA minus five minutes," it's:
BATCH_CUTOFF = SLA_TOTAL − on_demand_drain_time − safety_buffer
If the batch job hasn't completed by  BATCH_CUTOFF , you need to act.
There are three distinct ways things can go wrong. The job can take too long. It can get stuck — submitted but with zero tokens in flight and pending items sitting idle. Or it can reach a terminal failure state:  Failed  (processing errors),  Expired  (the job was queued but never started before the timeout window closed), or  PartiallyCompleted  (processing stopped before all records were handled). Each mode needs the same recovery action, but each is detected differently.
When you fall back to on-demand, you also can't rerun everything. Some records may have already been processed by batch before it was stopped. You need to reconcile what completed versus what didn't, and only redrive the remainder.

In a nutshell

The Step Functions state machine does the following:
  1. SubmitBatchJob kicks off the Bedrock batch job, RecordJob saves the job ARN to DynamoDB for tracking.
  1. WaitForBatchCompletion pauses the execution with  waitForTaskToken . The machine goes dormant here — no polling.
  1. Something wakes it up (more on that in a moment). CheckOutcome looks at what happened:
  • If the batch completed, skip straight to merging results.
  • If it failed, expired, or timed out — enter the fallback path.
  1. The fallback: StopBatchJob kills the running job, ReconcileRecords diffs what was processed versus what wasn't.
  1. RedriveOnDemand takes the leftover records and runs them through Bedrock's on-demand API in parallel (Distributed Map, capped at 20 concurrent invocations).
  1. MergeResults combines batch output + on-demand output into a single result set in S3.

The architecture

For the full Step Functions state machine diagram, see the  Serverlessland pattern page .
An  Amazon Simple Storage Service  (Amazon S3) upload triggers the Registrar Lambda, which starts the Step Functions state machine. The machine submits the batch job to Amazon Bedrock, records the job ARN in  Amazon DynamoDB , and then enters a wait state. It stays there, completely dormant, until something wakes it up.
Three independent mechanisms can do the waking.
Amazon CloudWatch alarm. A  CloudWatch alarm  watches Bedrock's native  AWS/Bedrock/Batch  metrics — specifically  NumberOfRecordsPendingProcessing  and  NumberOfInputTokensProcessedPerMinute . When records are pending but no tokens have been processed for a sustained period, the alarm fires through  Amazon Simple Notification Service  (Amazon SNS) to a Trigger Lambda.
Note: These throughput metrics are available for current Bedrock models. Check the  CloudWatch metrics documentation  for your specific model before relying on this mechanism.
Amazon EventBridge.  EventBridge  listens for  Batch Inference Job State Change  events from  aws.bedrock  and routes terminal states ( Completed ,  Failed ,  Expired ,  PartiallyCompleted ) to a Resume Lambda.
Step Functions timeout. Step Functions fires a  States.Timeout  when  BATCH_CUTOFF  is reached — no external dependency required.
Whichever fires first, the state machine resumes and checks the outcome. If the batch completed successfully, it skips straight to downstream processing. Otherwise it enters the fallback path: stop the batch job (you're  only charged for tokens already processed ), run ReconcileRecords to identify unprocessed inputs, then redrive them through a  Distributed Map  calling Bedrock's on-demand API in parallel. The outputs are merged. The system always reaches a clean terminal state.

Two patterns that make this work

The Callback Pattern

AWS Step Functions has a mode called   waitForTaskToken   where you pause the state machine and hand out a unique token — a receipt — that an external process redeems later. The state machine goes completely dormant: no polling loop, no scheduled Lambda checking on the job every minute.
When the right thing happens, the external Lambda sends the token back to Step Functions along with a status payload, and the machine wakes up exactly where it stopped. The token is saved to DynamoDB when the wait state is entered, so all three wakeup sources can find it independently. It doesn't matter which fires first — they all set a  status  field in the payload that  CheckOutcome  uses to route accordingly.
 waitForTaskToken  is only supported on  Standard Workflows , not Express. That's the right choice here: Standard Workflows are billed per state transition, not duration, so a dormant execution waiting hours for a batch job costs essentially nothing. The  TimeoutSeconds  on the wait state is the SLA enforcement mechanism — if nobody redeems the token in time, Step Functions raises  States.Timeout  and the catch route kicks off the fallback automatically.

The Saga Pattern

The  Saga Pattern  addresses what happens when things go wrong mid-execution. Rather than relying on atomic transactions — which don't exist across distributed AWS services — you define a compensating action at each step.
In the fallback path, the  StopBatchJob  state routes its catch to  ReconcileRecords  rather than back to  FallbackEntry . By the time that state runs, the job may already be stopped (EventBridge fires after a terminal state). Routing the catch forward keeps execution moving regardless — it's idempotent. Similarly, the  SubmitBatchJob  catch goes directly to  FallbackEntry  rather than failing the execution, and individual  InvokeOnDemand  failures inside the Distributed Map are tolerated up to five percent — partial success is better than total failure when records have genuinely bad inputs.
The goal is that no matter where execution fails, there is a defined path to a clean terminal state. You never end up with an orphaned batch job running in the background, missing records, or a state machine stuck in limbo.

Notable implementation details

Distributed Map with JSONL ItemReader. The on-demand redrive reads directly from a JSONL file in Amazon S3 containing only the unprocessed record keys. Step Functions  natively supports JSONL as an ItemReader input type  — no Lambda fan-out, no intermediate queue. The Map state reads the file, batches items, and manages concurrency natively with  MaxConcurrency .
Independent detection layers. The  BATCH_CUTOFF  timeout fires inside the state machine, but the stuck-job detection is completely independent — a CloudWatch alarm evaluating a Bedrock-published metric, with no dependency on the state machine. If the alarm system fails, the timeout still fires. If Step Functions has an issue, the alarm can still detect a stuck job. The two mechanisms cover different failure modes and do not share a single point of failure.
AWS CDK construct structure. The stack is organized into five L3 constructs —  StorageConstruct ,  BedrockServiceConstruct ,  LambdaComputeConstruct ,  OrchestrationConstruct , and  MonitoringConstruct  — each owning a coherent slice of the infrastructure. This makes it straightforward to extend individual layers without touching the rest of the stack.

When to use this pattern

This architecture isn't appropriate for every workload. If your downstream process has no deadline, It is pure offline analytics, background enrichment with no consumer waiting — use batch directly. The  cost savings  are real and the added complexity isn't justified.
The pattern is well-suited when you have a soft deadline that truly matters, but is not governed by the necessity for real-time inferencing. Document summarization pipelines that feed a report at 8 AM. Personalization that updates nightly. Any workload where "done by morning" is a real requirement but sub-second latency is not.
It also generalizes beyond Bedrock: try the Spot Fleet first, fall back to On-Demand  Amazon Elastic Compute Cloud  (Amazon EC2). Try the async queue, fall back to synchronous processing. Anywhere you have a primary path that is cheap but unpredictable, and a fallback that is reliable but expensive, the same architecture applies — Callback Pattern for efficient waiting, Saga Pattern for guaranteed termination.

Cleaning up

To avoid ongoing charges, remove the resources created by this solution:
  1. Delete the AWS CDK stack: cdk destroy
  1. Verify that the Amazon S3 buckets have been emptied and deleted. If bucket deletion fails (due to non-empty buckets), manually empty and delete them from the  Amazon S3 console .
  1. Confirm that the CloudWatch alarm, EventBridge rule, and SNS topic have been removed by checking the respective service consoles.

Conclusion

The core insight is that you don't have to choose between cost and reliability at design time. You can defer the choice until runtime, with a cutoff that reflects your actual SLA. Most of the time, batch finishes and you keep the savings. When it doesn't, the system handles it without any manual intervention.
That's the part that matters in production: not that you built a fallback, but that the fallback runs itself.
The full working implementation — CDK stack, Lambda functions, and Step Functions ASL definition — is available on  Serverlessland .
If you've solved this problem differently — or if you're running into edge cases I haven't covered — I'd love to hear about it in the comments.

References



Subha Venugopal is an AI/ML Solutions Architect at AWS. She is passionate about improving healthcare delivery and making it accessible to everyone, regardless of socioeconomic and geographical constraints.
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