AWS Intelligent Document Processing: A Production Tutorial
[!NOTE] TL;DR: This tutorial deploys a production AWS intelligent document processing pipeline from raw PDF to validated DynamoDB records. Stack: S3 event trigger via EventBridge, Step Functions standard workflow with declarative retries, asynchronous Textract AnalyzeExpense, Bedrock Nova Lite with a forced tool call for schema enforcement, Pydantic validation, DynamoDB storage. Cost: about 11 USD per 1,000 pages at AWS list prices (checked Nov. 2026). Time: one afternoon, prerequisites below.
The intake bucket that lost three percent
Three percent of my client's supplier invoices never reached the accounting database. The finance team noticed before I did. This tutorial builds the pipeline that fixed it: an end-to-end AWS intelligent document processing setup where every failure path ends in a quarantine, not in silence.
The flow in one sentence: an S3 upload triggers a Step Functions execution, Textract runs the OCR asynchronously, Bedrock enforces a JSON schema through a forced tool call, Pydantic rejects anything malformed, and DynamoDB keeps the survivors. Measured at AWS list prices (Nov. 2026), the whole chain costs about 11 USD per 1,000 pages.
If you have never wired S3 to DynamoDB at all, start with my earlier Document AI Pipeline Tutorial: S3 PDF to DynamoDB. Here I focus on what that piece skipped: retry semantics, quarantine routing, and the money each retry costs you.
Prerequisites and stack
You need four things before typing anything: an AWS account (every service below is pay per use), Python 3.12 for the Lambda runtime, pydantic 2.x, and an S3 bucket that accepts nothing but PDFs under an invoices/ prefix. My examples run in eu-west-3, on boto3.
I manage the IAM side with Terraform. You can click the equivalent roles together in the console, but I am not going to pretend a hand-typed policy survives its first audit.
One warning before the code. The unit price of Textract (and this is where everybody gets it wrong) is identical for synchronous and asynchronous calls, according to the AWS Textract pricing page. Async is about capacity, not discounts.
The target architecture
The architecture is deliberately boring, which in production is a compliment. One event enters, one record exits, and every failure has a named parking spot.
flowchart LR
A[S3 intake bucket] -->|ObjectCreated| B[EventBridge rule]
B -->|StartExecution| C[Step Functions workflow]
C --> D[Lambda idp-start-textract]
D --> E[Textract async job]
E --> F[Lambda idp-textract-status]
F -->|IN_PROGRESS| G[Wait 10s]
G --> F
F -->|SUCCEEDED| H[Lambda idp-normalize-bedrock]
H --> I[Bedrock Nova Lite]
H -->|validated| J[DynamoDB idp-invoices]
C -->|Catch States.ALL| K[Lambda idp-quarantine]
K --> L[S3 quarantine prefix]
K --> M[DynamoDB idp-failures]
The polling loop is the one simplification I allowed myself. Although the SNS-to-SQS notification channel is the textbook answer at high volume (see the Textract asynchronous operations guide), polling kept the whole tutorial reproducible in an afternoon, and it degrades gracefully up to a few thousand documents a day.
Step 1: wire S3 into EventBridge
First, create the bucket and switch on EventBridge notifications for it. Then one rule captures object creations under invoices/ and starts the state machine.
aws s3api create-bucket --bucket doc-intake-prod --region eu-west-3 --create-bucket-configuration LocationConstraint=eu-west-3
aws s3api put-bucket-notification-configuration --bucket doc-intake-prod --notifications '{"EventBridgeConfiguration":{}}'
aws events put-rule --name idp-s3-intake --event-pattern '{"source":["aws.s3"],"detail-type":["Object Created"],"detail":{"bucket":{"name":["doc-intake-prod"]},"object":{"key":[{"prefix":"invoices/"}]}}}'
STATE_MACHINE_ARN="arn:aws:states:eu-west-3:111122223333:stateMachine:idp-invoices"
EVENTS_ROLE_ARN="arn:aws:iam::111122223333:role/idp-events-start-execution"
aws events put-targets --rule idp-s3-intake --targets "Id"="idp-pipeline","Arn"="$STATE_MACHINE_ARN","RoleArn"="$EVENTS_ROLE_ARN"
Two details the docs bury. The S3 key arrives URL-encoded in the event detail, so a file named facture 2026.pdf shows up as facture+2026.pdf and you must decode it before calling S3 again. And EventBridge delivers at-least-once: if your state machine fails at intake, nobody redelivers that event (more on this in the pitfalls).
Step 2: the state machine and its retry net
Here is the full Amazon States Language definition. It is longer than a Lambda chain, but the retries, the waits, and the error routing are all declared instead of hand-rolled.
{
"Comment": "Invoice IDP: async Textract, Bedrock normalization, typed storage",
"StartAt": "StartTextractJob",
"States": {
"StartTextractJob": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Parameters": {"FunctionName": "idp-start-textract", "Payload.$": "$"},
"ResultPath": "$.textract",
"Retry": [{"ErrorEquals": ["Lambda.ServiceException", "Lambda.SdkClientException", "Lambda.TooManyRequestsException"], "IntervalSeconds": 2, "BackoffRate": 2.0, "MaxAttempts": 6}],
"Catch": [{"ErrorEquals": ["States.ALL"], "ResultPath": "$.error", "Next": "QuarantineDocument"}],
"Next": "CheckTextractStatus"
},
"CheckTextractStatus": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Parameters": {"FunctionName": "idp-textract-status", "Payload": {"jobId.$": "$.textract.Payload.jobId"}},
"ResultPath": "$.status",
"Retry": [{"ErrorEquals": ["Lambda.ServiceException", "Lambda.SdkClientException", "Textract.ThrottlingException"], "IntervalSeconds": 3, "BackoffRate": 2.0, "MaxAttempts": 4}],
"Catch": [{"ErrorEquals": ["States.ALL"], "ResultPath": "$.error", "Next": "QuarantineDocument"}],
"Next": "JobDone"
},
"JobDone": {
"Type": "Choice",
"Choices": [
{"Variable": "$.status.Payload.jobStatus", "StringEquals": "SUCCEEDED", "Next": "NormalizeWithBedrock"},
{"Variable": "$.status.Payload.jobStatus", "StringEquals": "IN_PROGRESS", "Next": "WaitTenSeconds"}
],
"Default": "QuarantineDocument"
},
"WaitTenSeconds": {"Type": "Wait", "Seconds": 10, "Next": "CheckTextractStatus"},
"NormalizeWithBedrock": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Parameters": {"FunctionName": "idp-normalize-bedrock", "Payload": {"ocrText.$": "$.status.Payload.ocrText", "documentId.$": "$.detail.object.key"}},
"ResultPath": "$.record",
"Retry": [{"ErrorEquals": ["Lambda.ServiceException", "Lambda.SdkClientException", "BedrockThrottling"], "IntervalSeconds": 5, "BackoffRate": 2.0, "MaxAttempts": 4}],
"Catch": [{"ErrorEquals": ["States.ALL"], "ResultPath": "$.error", "Next": "QuarantineDocument"}],
"Next": "StoreRecord"
},
"StoreRecord": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Parameters": {"FunctionName": "idp-store-record", "Payload": {"record.$": "$.record.Payload"}},
"ResultPath": null,
"Retry": [{"ErrorEquals": ["Lambda.ServiceException", "Lambda.SdkClientException"], "IntervalSeconds": 2, "BackoffRate": 2.0, "MaxAttempts": 4}],
"Catch": [{"ErrorEquals": ["States.ALL"], "ResultPath": "$.error", "Next": "QuarantineDocument"}],
"End": true
},
"QuarantineDocument": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Parameters": {"FunctionName": "idp-quarantine", "Payload.$": "$"},
"ResultPath": null,
"Retry": [{"ErrorEquals": ["Lambda.ServiceException", "Lambda.SdkClientException"], "IntervalSeconds": 5, "BackoffRate": 2.0, "MaxAttempts": 3}],
"End": true
}
}
}
The retry parameters are not decorative. Defaults are IntervalSeconds 1, MaxAttempts 3, BackoffRate 2.0, and each attempt is billed as a state transition (the Step Functions error handling guide spells out the exact semantics). The transient Lambda error names (Lambda.ServiceException and friends) are the ones AWS itself recommends retrying. BedrockThrottling is my own handled error: the normalize Lambda catches the SDK ThrottlingException and re-raises it under that name, so the net catches it cleanly.
Note the difference between Retry and Catch. Retry absorbs transient noise. Catch is the permanent exit: after the retries are exhausted, the document lands in quarantine with its error payload attached.
Step 3: patient polling of Textract
The starter Lambda is four lines of substance. It reads the S3 coordinates from the EventBridge event and launches an asynchronous StartExpenseAnalysis job.
import boto3
textract = boto3.client("textract")
def handler(event: dict, context: object) -> dict:
bucket: str = event["detail"]["bucket"]["name"]
key: str = event["detail"]["object"]["key"]
job = textract.start_expense_analysis(DocumentLocation={"S3Object": {"Bucket": bucket, "Name": key}})
return {"jobId": job["JobId"], "bucket": bucket, "key": key}
The status Lambda polls GetExpenseAnalysis and, when the job is done, flattens the expense fields into plain text that a model can read. ValueText pairs become TYPE: value lines, line items become pipe-separated rows.
import boto3
textract = boto3.client("textract")
def expense_doc_to_text(doc: dict) -> str:
lines: list[str] = [f"{sf['Type']['Text']}: {sf.get('ValueText', '')}" for sf in doc.get("SummaryFields", [])]
for group in doc.get("LineItemGroups", []):
for line in group.get("LineItems", []):
cells = [f"{f['Type']['Text']}={f.get('ValueText', '')}" for f in line.get("LineItemExpenseFields", [])]
lines.append(" | ".join(cells))
return "\n".join(lines)
def handler(event: dict, context: object) -> dict:
job = textract.get_expense_analysis(JobId=event["jobId"])
if job["JobStatus"] != "SUCCEEDED":
return {"jobStatus": job["JobStatus"]}
parts: list[str] = [expense_doc_to_text(doc) for doc in job["ExpenseDocuments"]]
return {"jobStatus": "SUCCEEDED", "ocrText": "\n".join(parts)}
One honest gap: GetExpenseAnalysis paginates, and this handler reads only the first page of results. For invoices above roughly fifteen pages you must loop on NextToken, otherwise you truncate the line items without any error. Ask me how I know.
And remember the clock. Textract keeps asynchronous results for 7 days, then discards them with the calm of an airport lost-property office. After that, only your S3 original remains, and a redrive must re-run the job from scratch.
Step 4: schema enforcement with Bedrock
Here is the trick that killed my JSON parsing bugs. You do not ask the model to "please return JSON". You define one tool whose inputSchema is your target record, and you force the call with toolChoice. Bedrock then returns the arguments as a parsed dict, already shaped.
import boto3
from pydantic import BaseModel, Field, field_validator
class LineItem(BaseModel):
description: str = Field(..., min_length=1)
quantity: float = Field(..., gt=0.0)
unit_price: float = Field(..., gt=0.0)
class InvoiceRecord(BaseModel):
model_config = {"strict": True}
document_id: str = Field(..., description="S3 key, becomes the DynamoDB partition key.")
vendor_name: str = Field(..., min_length=1)
invoice_number: str = Field(..., min_length=1)
invoice_date: str = Field(..., pattern=r"^\d{4}-\d{2}-\d{2}$")
total_amount: float = Field(..., gt=0.0)
currency: str = Field(default="EUR", pattern=r"^[A-Z]{3}$")
line_items: list[LineItem] = Field(..., min_length=1)
@field_validator("total_amount")
@classmethod
def guard_absurd_totals(cls, value: float) -> float:
if value > 1_000_000.0:
raise ValueError("a total above 1,000,000 is almost always a parse error")
return value
INVOICE_SCHEMA = {"type": "object", "properties": {"vendor_name": {"type": "string"}, "invoice_number": {"type": "string"}, "invoice_date": {"type": "string"}, "total_amount": {"type": "number"}, "currency": {"type": "string"}, "line_items": {"type": "array", "items": {"type": "object", "properties": {"description": {"type": "string"}, "quantity": {"type": "number"}, "unit_price": {"type": "number"}}, "required": ["description", "quantity", "unit_price"]}}}, "required": ["vendor_name", "invoice_number", "invoice_date", "total_amount", "currency", "line_items"]}
TOOL_SPEC = {"toolSpec": {"name": "record_invoice", "description": "Record the structured invoice data extracted from the OCR text.", "inputSchema": {"json": INVOICE_SCHEMA}}}
bedrock = boto3.client("bedrock-runtime")
def handler(event: dict, context: object) -> dict:
response = bedrock.converse(
modelId="amazon.nova-lite-v1:0",
system=[{"text": "You extract invoice fields. Call record_invoice exactly once, plain numbers, ISO dates, currency as a 3-letter code."}],
messages=[{"role": "user", "content": [{"text": event["ocrText"]}]}],
toolConfig={"tools": [TOOL_SPEC], "toolChoice": {"tool": {"name": "record_invoice"}}},
inferenceConfig={"temperature": 0.0, "maxTokens": 2000},
)
tool_input: dict = response["output"]["message"]["content"][0]["toolUse"]["input"]
record = InvoiceRecord(document_id=event["documentId"], **tool_input)
return record.model_dump(mode="json")
Two things to know. Nova Lite (0.06 USD per million input tokens, 0.24 USD per million output, per the Amazon Nova Converse API docs and Bedrock pricing, Dec. 2026) does not support the newer outputConfig structured outputs on the runtime endpoint, so the forced tool call is the reliable path. And the Pydantic model is not optional garnish: the tool schema guarantees the shape, never the truth. When validation raises, the exception surfaces as States.TaskFailed, my Catch grabs it, and the invoice goes to quarantine instead of corrupting the table.
Step 5: typed storage in DynamoDB
The store Lambda receives the already-validated record. One partition key per document, one version row per processing attempt, a 90-day TTL on the audit trail. That versioning bit has saved me twice: when a downstream correction overwrites a field, the original extraction stays reachable.
import time
import boto3
table = boto3.resource("dynamodb").Table("idp-invoices")
def handler(event: dict, context: object) -> dict:
record: dict = event["record"]
table.put_item(Item={"pk": record["document_id"], "sk": "v1", "status": "validated", "payload": record, "ttl": int(time.time()) + 90 * 86400})
return {"stored": True, "pk": record["document_id"]}
The quarantine Lambda follows the same shape: copy the S3 object to quarantine/, write the error output to an idp-failures table, done. No magic.
Expected result and cost per 1,000 pages
Drop a two-page invoice into invoices/ and watch the execution. Within a minute or two, a validated record appears in DynamoDB, and the Step Functions graph shows every poll cycle, every transition, every retry. That graph is worth the state transitions it costs, because it was exactly this visibility that let me find my three percent: executions dying silently at intake, with no failure record anywhere.
| Stage | Unit price (AWS list) | Per 1,000 pages |
|---|---|---|
| Textract AnalyzeExpense | 0.01 USD per page | 10.00 USD |
| Textract FORMS (if your docs need it) | 0.05 USD per page | 50.00 USD |
| Bedrock Nova Lite | 0.06 USD / 0.24 USD per 1M tokens (in / out) | about 0.20 USD |
| Step Functions | 0.000025 USD per state transition | about 0.40 USD |
All unit prices from the AWS Textract pricing page and the Step Functions pricing page, checked Nov. 2026. The two derived figures are estimates from my own runs: roughly 1,900 tokens in and 400 tokens out per average invoice, and roughly 12 state transitions per document including a couple of poll cycles. Do not treat them as benchmarks, treat them as order of magnitude.
{
"type": "bar",
"data": {
"labels": ["Textract AnalyzeExpense", "Bedrock Nova Lite", "Step Functions"],
"datasets": [{ "label": "USD per 1,000 pages", "data": [10.0, 0.2, 0.4], "backgroundColor": ["#3b82f6", "#8b5cf6", "#10b981"] }]
},
"options": {
"responsive": true,
"plugins": { "title": { "display": true, "text": "Pipeline cost per 1,000 pages, AWS list prices, Nov. 2026" } },
"scales": { "y": { "title": { "display": true, "text": "USD" } } }
}
}
The free tiers soften the first month: 100 AnalyzeExpense pages per month for three months, and 4,000 state transitions free forever. At 12 transitions per document, your first 330 invoices a month cost you zero in orchestration.
The orphaned JobId and other traps
The orphaned JobId. If a state machine dies between StartTextractJob and the first poll (an account quota, a region blip), the Textract job still runs to completion. Its results then expire after 7 days, untouched. This is the orphaned JobId, and polling cannot see it because the poller never started. The fix in my production setups: write the JobId to DynamoDB at creation, and run a scheduled sweeper that finds JobIds with no terminal status.
The event nobody redelivers. EventBridge fires once, at best once. A failed StartExecution is not retried by anyone but you. Archive the rule to an EventBridge archive, or accept the gap.
Retries you pay for twice. Every retry is a state transition, and a retry loop that hides a design error will quietly mint money for AWS. Cap MaxAttempts, and treat a quarantine that fills up as a bug report, not background noise.
Schema-valid nonsense. A forced tool call returned me a perfectly typed record once, with an invoice date two years in the future and a total that matched no line item sum. The shape was valid. The invoice was not. Keep the Pydantic guards, and route records above the guardrails to a human review queue rather than to the table.
Limits of this setup
I ran this pipeline on supplier invoices (a French energy-sector client, anonymized here), on scanned PDFs of average quality. What I have not tested: heavily handwritten forms, non-Latin scripts, and mixed documents where one PDF bundles an invoice with delivery notes. For those, the page-splitting Map pattern I describe in the industrial IDP pipeline piece behaves better than whole-document jobs. The token and transition estimates above are mine, not AWS's, and pricing varies by region.
FAQ
How much does AWS intelligent document processing cost per 1,000 pages? About 11 USD end to end at list price: 10 USD for Textract AnalyzeExpense, roughly 0.20 USD for Nova Lite normalization, about 0.40 USD for Step Functions transitions (AWS pricing pages, Nov. 2026). If your documents need FORMS instead of expense analysis, Textract alone rises to 50 USD per 1,000 pages.
Synchronous or asynchronous Textract for PDFs? Asynchronous, and not for the price: sync and async cost the same per page. Async handles PDFs up to 3,000 pages and 500 MB directly from S3, while sync caps at one page and 10 MB.
Does a forced tool call guarantee correct data? No. It guarantees the JSON shape, never the values. Keep Pydantic validators behind the tool call, and route suspicious records to human review.
Why Step Functions instead of chained Lambdas? Retries with exponential backoff become declarative, error routing becomes a visible Catch clause, and every execution leaves a graph you can inspect. The cost is 0.000025 USD per state transition, retries included (AWS pricing, Nov. 2026).
What happens to a document that fails every retry? It lands in a quarantine S3 prefix, with its error payload in a failures table. EventBridge does not redeliver, so replay comes from the Step Functions redrive API or from an event archive.
Where this leaves you
More generally, the principle this tutorial attests is that a document pipeline is judged by its failure paths, not its happy path. Put the retries, the waits, and the quarantine routing in the orchestrator, keep the Lambdas typed and dumb, and make every silent loss impossible by construction. Your future self, grep-ing a DynamoDB failures table at 7 a.m., will thank you.
If you would rather not collect these trap stories on your own invoices, that is literally what I do: my Document AI services page describes the production pipelines I build, and /en/contact/ is one click away.
Prepared by Vector, SamAlgo's writing agent, augmented and curated from SamAlgo's research, code and publications.