Serverless AI Document Processing Pipeline with (Bedrock + S3 + Lambda + Step Functions)
Using Amazon Bedrock, S3, Lambda, and Step Functions to Create a Production-Ready Serverless AI Document Processing Pipeline
Topic 1: Serverless AI Document Processing Pipeline with (Bedrock + S3 + Lambda + Step Functions)
Using Amazon Bedrock, S3, Lambda, and Step Functions to Create a Production-Ready Serverless AI Document Processing Pipeline
Invoices, contracts, and PDFs are not self-processing. Using Amazon Bedrock (Claude), Step Functions, and S3, I developed a fully serverless pipeline that can classify, extract, validate, and route unstructured documents at scale with complete auditability and dead-letter error recovery. This is the precise code and architecture.
Cover Image Description: Dark-background architectural diagram with glowing flow lines connecting an S3 bucket icon → Lambda → Step Functions state machine nodes → Bedrock AI brain icon → DynamoDB and SNS endpoints. AWS color palette (orange, blue, white). Cinematic depth-of-field blur on the background.
The Problem
Unstructured documents are overwhelming your staff. Invoices, contracts, purchase orders, and other PDFs from suppliers, partners, or internal tools come in an S3 bucket. Someone must open each one, identify what it is, extract the pertinent fields, and push data downstream. A human can handle it at low volume. It causes a bottleneck at scale that is difficult to resolve with hiring.
With no retry logic, no validation, no routing, no audit trail, and Bedrock token costs that accrue quietly, the naive engineering solution, a single Lambda that calls a model and dumps output somewhere breaks down quickly.
Instead of using the LLM as a black box that consumes everything, you actually need an organized, observable pipeline where each step is independently tested, failures are recoverable, and the LLM is used exactly where it brings value.
This tutorial creates that pipeline from the ground up.
Architecture Overview
S3 (document upload)
│
▼
Lambda (entry point + payload packaging)
│
▼
Step Functions State Machine
├── State 1: Classify (Bedrock → document type)
├── State 2: Extract (Bedrock → structured JSON)
├── State 3: Validate (Lambda → schema enforcement)
├── State 4: Route (Choice state → DynamoDB / SNS / S3)
└── State 5: Error Handler → SQS Dead Letter Queue
The spine of the architecture is the Step Functions state machine. Each logical step is an explicit state that is classified, extracted, validated, and routed. This is important for three reasons: CloudWatch tracks each state transition separately, you can retry specific states without restarting the entire pipeline, and the execution history provides you with a complete audit log of every document processed.
Only States 1 and 2 use Bedrock. This is deliberate. There is no need to spend tokens on logic that a Lambda can process in microseconds because validation and routing are deterministic.
Prerequisites & Setup
- AWS CLI v2 configured with a profile that has AdministratorAccess (tighten this post-build)
- Bedrock model access enabled for `anthropic.claude-3-sonnet-20240229-v1:0` in your target region
- Python 3.12 runtime for Lambda functions
- Terraform >= 1.6 or AWS SAM CLI if you prefer examples use raw CloudFormation/Boto3 for portability
- An S3 bucket for document uploads (referred to as `doc-intake-bucket` below)
Enable Bedrock model access via console: Bedrock → Model access → Manage model access → Claude 3 Sonnet → Request access. This is a one-time gate that catches many teams off-guard.
Phase 1: S3 Trigger and Lambda Entry Point
S3 Event Notification Configuration
When a file lands in the intake bucket, the pipeline begins. Set up a Lambda function to receive an S3 event notification:
json
{
"LambdaFunctionConfigurations": [
{
"LambdaFunctionArn": "arn:aws:lambda:us-east-1:123456789012:function:DocPipelineEntryPoint",
"Events": ["s3:ObjectCreated:*"],
"Filter": {
"Key": {
"FilterRules": [
{ "Name": "suffix", "Value": ".pdf" }
]
}
}
}
]
}
Apply with:
bash
aws s3api put-bucket-notification-configuration \
--bucket doc-intake-bucket \
--notification-configuration file://s3-notification.json
Limit the filter to `.pdf`. A misconfigured upstream system may trigger your pipeline with a 3-byte `.DS_Store` file if you permit `*, in which case you will have to pay for a complete Bedrock invocation to classify nothing.
Lambda Entry Point
This Lambda performs three tasks: it reads the object metadata, obtains the S3 key, and initiates a Step Functions execution. The document body, which takes place inside the state machine and can be independently retried, is not read by it.
python
import json
import boto3
import uuid
from datetime import datetime
sfn = boto3.client('stepfunctions')
STATE_MACHINE_ARN = "arn:aws:states:us-east-1:123456789012:stateMachine:DocProcessingPipeline"
def handler(event, context):
record = event['Records'][0]
bucket = record['s3']['bucket']['name']
key = record['s3']['object']['key']
file_size = record['s3']['object']['size']
# Reject empty files immediately don't waste a state machine execution
if file_size == 0:
print(f"Skipping empty file: {key}")
return
execution_input = {
"executionId": str(uuid.uuid4()),
"bucket": bucket,
"key": key,
"uploadedAt": datetime.utcnow().isoformat(),
"fileSizeBytes": file_size
}
response = sfn.start_execution(
stateMachineArn=STATE_MACHINE_ARN,
name=f"doc-{execution_input['executionId']}",
input=json.dumps(execution_input)
)
print(f"Started execution: {response['executionArn']}")
Pro Tip: Use a deterministic prefix (`doc-{uuid}`) when naming your executions. When debugging at a high volume, anonymous executions render the Step Functions console useless. Additionally, take note that the execution names of Step Functions must be distinct for each state machine; this is easily handled by using a UUID suffix.
IAM Role for Entry Lambda
json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "states:StartExecution",
"Resource": "arn:aws:states:us-east-1:123456789012:stateMachine:DocProcessingPipeline"
},
{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:GetObjectAttributes"],
"Resource": "arn:aws:s3:::doc-intake-bucket/*"
}
]
}
Do not grant `states:*` or `s3:*`. Lambda does not directly read anything from S3; it merely initiates executions. If the function is ever called with a malicious payload, granting more extensive access here results in a blast radius.
Phase 2: Step Functions State Machine
State Machine Definition (ASL)
All four processing stages are wired with explicit error handling and a dead-letter path in the whole Amazon States Language description that follows.
json
{
"Comment": "Serverless document processing pipeline",
"StartAt": "ClassifyDocument",
"States": {
"ClassifyDocument": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:ClassifyDoc",
"Retry": [
{
"ErrorEquals": ["Lambda.ServiceException", "Lambda.TooManyRequestsException"],
"IntervalSeconds": 2,
"MaxAttempts": 3,
"BackoffRate": 2
}
],
"Catch": [{ "ErrorEquals": ["States.ALL"], "Next": "SendToDeadLetter" }],
"Next": "ExtractFields"
},
"ExtractFields": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:ExtractFields",
"Retry": [
{
"ErrorEquals": ["BedrockThrottlingException"],
"IntervalSeconds": 5,
"MaxAttempts": 4,
"BackoffRate": 1.5
}
],
"Catch": [{ "ErrorEquals": ["States.ALL"], "Next": "SendToDeadLetter" }],
"Next": "ValidateOutput"
},
"ValidateOutput": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:ValidateDoc",
"Catch": [{ "ErrorEquals": ["States.ALL"], "Next": "SendToDeadLetter" }],
"Next": "RouteDocument"
},
"RouteDocument": {
"Type": "Choice",
"Choices": [
{
"Variable": "$.documentType",
"StringEquals": "INVOICE",
"Next": "WriteToInvoiceTable"
},
{
"Variable": "$.documentType",
"StringEquals": "CONTRACT",
"Next": "NotifyLegalTeam"
}
],
"Default": "SendToDeadLetter"
},
"WriteToInvoiceTable": {
"Type": "Task",
"Resource": "arn:aws:states:::dynamodb:putItem",
"Parameters": {
"TableName": "ProcessedInvoices",
"Item": {
"executionId": { "S.$": "$.executionId" },
"vendor": { "S.$": "$.extractedFields.vendor" },
"amount": { "N.$": "$.extractedFields.totalAmount" },
"invoiceDate": { "S.$": "$.extractedFields.invoiceDate" }
}
},
"End": true
},
"NotifyLegalTeam": {
"Type": "Task",
"Resource": "arn:aws:states:::sns:publish",
"Parameters": {
"TopicArn": "arn:aws:sns:us-east-1:123456789012:LegalDocAlerts",
"Message.$": "States.Format('New contract received: {}', $.key)"
},
"End": true
},
"SendToDeadLetter": {
"Type": "Task",
"Resource": "arn:aws:states:::sqs:sendMessage",
"Parameters": {
"MessageBody.$": "States.JsonToString($)"
},
"End": true
}
}
}
For DynamoDB writes and SNS publishes, use SDK integrations (the `:::dynamodb:putItem` and `:::sns:publish` resource patterns) straight from Step Functions. This removes two Lambda functions that would otherwise only be thin wrappers over a single Boto3 call.
Potential Problems: If Bedrock delivers a `documentType` value that is not in your options, the `RouteDocument` Choice state falls through to `SendToDeadLetter`. This is deliberate, but keep an eye on your DLQ. Your categorization prompt is likely drifting and returning synonyms (`Invoice` vs. `INVOICE`) if you begin to notice a large DLQ volume. Before Bedrock output reaches this stage, normalize it to uppercase in your classification Lambda.
Phase 3: Bedrock Integration for Classification and Extraction
Document Classification Lambda
After reading the PDF from S3 and converting it to base64, this Lambda delivers it to Bedrock along with a categorization prompt. Direct PDF input is supported by Claude 3 Sonnet using the `document` content block type.
python
import boto3
import base64
import json
s3 = boto3.client('s3')
bedrock = boto3.client('bedrock-runtime', region_name='us-east-1')
CLASSIFY_PROMPT = """You are a document classification system.
Analyze the document and respond with ONLY a JSON object in this exact format:
{"documentType": "<TYPE>", "confidence": <0.0-1.0>}
Valid types: INVOICE, CONTRACT, PURCHASE_ORDER, RECEIPT, UNKNOWN
Do not include any explanation or additional text."""
def handler(event, context):
bucket, key = event['bucket'], event['key']
obj = s3.get_object(Bucket=bucket, Key=key)
pdf_bytes = obj['Body'].read()
pdf_b64 = base64.standard_b64encode(pdf_bytes).decode('utf-8')
response = bedrock.invoke_model(
modelId='anthropic.claude-3-sonnet-20240229-v1:0',
body=json.dumps({
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 100,
"messages": [
{
"role": "user",
"content": [
{
"type": "document",
"source": {
"type": "base64",
"media_type": "application/pdf",
"data": pdf_b64
}
},
{"type": "text", "text": CLASSIFY_PROMPT}
]
}
]
})
)
result = json.loads(response['body'].read())
classification = json.loads(result['content'][0]['text'])
# Normalize and pass forward
return {
**event,
"documentType": classification['documentType'].upper(),
"classificationConfidence": classification['confidence']
}
For categorization, hard-cap `max_tokens` at `100`. Less than thirty tokens are needed for a type label and confidence score. Teams unintentionally burn through Bedrock quotas by leaving this uncapped; if the prompt doesn't constrain it, the model will verbosely explain its reasons.
Structured Extraction Lambda
python
EXTRACT_PROMPT = """Extract structured data from this document.
Respond ONLY with a valid JSON object matching this schema exactly:
{
"vendor": "string",
"invoiceNumber": "string",
"invoiceDate": "YYYY-MM-DD",
"dueDate": "YYYY-MM-DD",
"lineItems": [{"description": "string", "quantity": number, "unitPrice": number}],
"subtotal": number,
"taxAmount": number,
"totalAmount": number,
"currency": "USD"
}
If a field cannot be determined, use null. Do not include commentary."""
def handler(event, context):
bucket, key = event['bucket'], event['key']
obj = s3.get_object(Bucket=bucket, Key=key)
pdf_b64 = base64.standard_b64encode(obj['Body'].read()).decode('utf-8')
response = bedrock.invoke_model(
modelId='anthropic.claude-3-sonnet-20240229-v1:0',
body=json.dumps({
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 1024,
"messages": [
{
"role": "user",
"content": [
{
"type": "document",
"source": {"type": "base64", "media_type": "application/pdf", "data": pdf_b64}
},
{"type": "text", "text": EXTRACT_PROMPT}
]
}
]
})
)
result = json.loads(response['body'].read())
raw_text = result['content'][0]['text'].strip()
# Strip markdown fences if model wraps output despite instructions
if raw_text.startswith("```"):
raw_text = raw_text.split("```")[1]
if raw_text.startswith("json"):
raw_text = raw_text[4:]
extracted = json.loads(raw_text)
return {**event, "extractedFields": extracted}
The fence-stripping block is a true failure mode, not a sign of defensive paranoia. Claude sometimes wraps JSON in markdown code fences even with specific directives, especially when the `temperature` defaults are active. Remove these, or the document will be thrown and routed to the DLQ by your `json.loads`.
What Could Go Wrong: When dealing with particularly big PDFs, Bedrock's synchronous `invoke_model` will time out. Although Bedrock's request timeout for Claude Sonnet via `invoke_model` is 30 seconds, Lambda's maximum execution time is 15 minutes. Use `invoke_model_with_response_stream` or pre-chunk the PDF before sending it to Bedrock for documents longer than about 20 pages.
Production Hardening
IAM Least Privilege for the State Machine
The Step Functions execution role should be scoped tightly:
json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "lambda:InvokeFunction",
"Resource": [
"arn:aws:lambda:us-east-1:123456789012:function:ClassifyDoc",
"arn:aws:lambda:us-east-1:123456789012:function:ExtractFields",
"arn:aws:lambda:us-east-1:123456789012:function:ValidateDoc"
]
},
{
"Effect": "Allow",
"Action": "dynamodb:PutItem",
"Resource": "arn:aws:dynamodb:us-east-1:123456789012:table/ProcessedInvoices"
},
{
"Effect": "Allow",
"Action": "sns:Publish",
"Resource": "arn:aws:sns:us-east-1:123456789012:LegalDocAlerts"
},
{
"Effect": "Allow",
"Action": "sqs:SendMessage",
"Resource": "arn:aws:sqs:us-east-1:123456789012:doc-pipeline-dlq"
}
]
}
The `bedrock:InvokeModel` scoped to the particular model ARN and `s3:GetObject` scoped to the intake bucket are required for each Lambda's execution role independently. Keep the LLM invocation border inside Lambda, where you can record, wrap, and rate-limit it, and never give Bedrock access to the Step Functions role itself.
Bedrock Cost Control
Pricing for the Claude 3 Sonnet is $15 per million output tokens and $3 per million input tokens as of this writing. About 8,000–12,000 input tokens are needed to convert a 10-page PDF invoice. At 10,000 documents each day, the input expenses alone before output come to $300–$450 per day.
Mitigation strategies:
1. Page cap: If a document is longer than fifteen pages, divide it up and only classify the first five pages. Full-document classification is not required for contracts.
2. Deduplication: Hash the ETag of the S3 object. Return the cached result from DynamoDB and completely bypass Bedrock if a document has previously been successfully processed.
3. Model tier routing: Use Claude 3 Haiku ($0.25/million input tokens) for classification, and save Sonnet exclusively for extraction on verified high-value document categories.
4. Output caps: Use an aggressive setting for `max_tokens`. 100 is required for classification. Seldom does the extraction of a typical invoice surpass 600.
python
# ETag-based dedup check before Bedrock invocation
def is_already_processed(etag: str, table) -> bool:
try:
result = table.get_item(Key={'etag': etag})
return 'Item' in result
except Exception:
return False # On DynamoDB failure, proceed don't skip processing
Cold Start Mitigation
Categorization and extraction Lambdas have a non-trivial initialization cost; on a cold start with 512MB of memory, loading Boto3, setting up the Bedrock client, and importing JSON libraries takes 400–800ms. For pipelines where latency is an issue:
- During business hours, use Application Auto Scaling to set Lambda provided concurrency to `2` on both functions.
- Allocate a minimum of 1024 MB of RAM. The Boto3 client initialization time is decreased because the CPU allocation scales with memory.
Testing End-to-End: Invoice Processing Walkthrough
Upload a real invoice PDF to the intake bucket:
bash
aws s3 cp sample-invoice.pdf s3://doc-intake-bucket/invoices/acme-inv-2024-001.pdf
Watch the Step Functions execution in real time:
bash
aws stepfunctions list-executions \
--state-machine-arn arn:aws:states:us-east-1:123456789012:stateMachine:DocProcessingPipeline \
--status-filter RUNNING
Once complete, verify the DynamoDB write:
bash
aws dynamodb scan \
--table-name ProcessedInvoices \
--filter-expression "vendor = :v" \
--expression-attribute-values '{":v": {"S": "Acme Corp"}}' \
--query "Items[0]"
Expected output:
json
{
"executionId": {"S": "a3f7c2d1-..."},
"vendor": {"S": "Acme Corp"},
"amount": {"N": "4750.00"},
"invoiceDate": {"S": "2024-11-15"}
}
Upload a damaged PDF or a zero-byte file as a backup plan. Zero-byte files are rejected by the entry Lambda before Step Functions is called. The `ClassifyDoc` Lambda will report a `json.JSONDecodeError` on the Bedrock response, initiate the `Catch` block, and land the execution state in `SendToDeadLetter` for a damaged PDF that passes the size check. Examine it:
bash
aws sqs receive-message \
--attribute-names All
The message body will contain the full Step Functions state at the time of failure bucket, key, execution ID, and the error cause. This is the audit trail.
What I'd Do Differently at Scale
Async Bedrock over synchronous: Lambda concurrency pressure is caused by synchronous `invoke_model` calls at high throughput. Change to Bedrock's async inference API and separate the extraction process into a Lambda that is triggered by SQS and polls for task completion. As a result, the state machine can wait inexpensively (Step Functions).waitForTaskToken` pattern) as opposed to keeping an open Lambda execution.
Multi-modal pre-screening: Use a lightweight Textract `DetectDocumentText` pass to determine whether a PDF is text-extractable before submitting it to Bedrock. When an image is scanned without any text included, Bedrock will return garbage and waste tokens. Compared to a Claude extraction that fails and you have to attempt again, Textract is significantly less expensive at $1.50 for 1,000 pages.
Separate state machines for each type of document: Create type-specific state machines after categorization is stable and document types are clearly specified. Compared to an invoice, a contract workflow requires distinct extraction fields, validation rules, and routing. A monolithic state machine with intricate choice logic quickly becomes brittle.
Schema versioning on extracted output: Each DynamoDB record should have a `schemaVersion` field. Old and new records coexist peacefully when the extraction prompt is updated or new fields are added, and downstream consumers can handle both shapes.
Conclusion
With the aforementioned architecture, you can have a production-grade document processing pipeline with no servers to maintain, complete execution auditability through Step Functions history, isolated failure recovery, and a Bedrock pricing model that you can analyze before the AWS bill shows up. To modify the state machine ASL for your document types, clone the reference implementation.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article