AWS Builder Center

Build a Serverless Receipt Processing Pipeline with Amazon S3, AWS Lambda, Amazon Textract, and Amazon DynamoDB

Manually typing receipt data into a spreadsheet is slow and error-prone. In this tutorial you’ll build a fully serverless, event-driven pipeline that extracts the vendor, date, subtotal, tax, and total from receipt images the moment they’re uploaded to Amazon S3, then stores the results in Amazon DynamoDB. You’ll define everything as code with AWS SAM, so you can deploy and delete the whole stack with a single command.

What you will learn

  • How to trigger AWS Lambda from S3 upload events
  • How to call Amazon Textract’s  AnalyzeExpense  API to read receipts and invoices
  • How to store structured results in DynamoDB
  • How to add error handling with a dead-letter queue (DLQ)
  • How to apply least-privilege IAM permissions
  • How to test, monitor, and clean up the stack

Architecture

User/App
│ upload receipt (JPEG/PNG/1-page PDF)
▼
┌──────────────┐ s3:ObjectCreated ┌───────────────┐
│ Amazon S3 │ ───────────────────► │ AWS Lambda │
│ uploads/ … │ │ (Python) │
└──────────────┘ └──────┬────────┘
│ AnalyzeExpense
▼
┌───────────────┐
│Amazon Textract│
└──────┬────────┘
│ structured fields
▼
┌───────────────┐
│ Amazon │
│ DynamoDB │
└───────────────┘
Failed invocations ──► Amazon SQS dead-letter queue
Flow:
  1. A receipt is uploaded to the  uploads/  prefix of an S3 bucket.
  1. S3 invokes the Lambda function asynchronously.
  1. Lambda calls Textract  AnalyzeExpense , which returns summary fields (vendor, total, etc.) and line items.
  1. Lambda writes a clean record to DynamoDB.
  1. If processing fails after retries, the event lands in an SQS queue for inspection.

Prerequisites

  • An AWS account and an IAM identity with permission to create the resources below
  • AWS CLI v2 configured ( aws configure )
  • AWS SAM CLI installed
  • Python 3.12 (or the latest Lambda-supported Python runtime available to you)
  • A Region where Amazon Textract is available. Check the AWS Regional Services list first.
  • A sample receipt image (JPEG or PNG), or a single-page PDF
Note: The synchronous  AnalyzeExpense  API supports JPEG, PNG, and single-page PDF/TIFF. Multi-page PDFs require the asynchronous API ( StartExpenseAnalysis ), which is a good extension at the end of this tutorial.

Step 1: Create the project

bash
mkdir receipt-pipeline && cd receipt-pipeline
mkdir src
touch template.yaml src/app.py src/requirements.txt

Step 2: Define the infrastructure with AWS SAM

Paste this into  template.yaml :
yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Serverless receipt processing with S3, Lambda, Textract and DynamoDB

Globals:
Function:
Runtime: python3.12
Timeout: 60
MemorySize: 256

Resources:
ReceiptBucket:
Type: AWS::S3::Bucket
Properties:
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256

ReceiptTable:
Type: AWS::DynamoDB::Table
Properties:
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: receiptId
AttributeType: S
KeySchema: - AttributeName: receiptId
KeyType: HASH

FailedEventsQueue:
Type: AWS::SQS::Queue
Properties:
MessageRetentionPeriod: 1209600 # 14 days

ProcessReceiptFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: src/
Handler: app.handler
Environment:
Variables:
TABLE_NAME: !Ref ReceiptTable
DeadLetterQueue:
Type: SQS
TargetArn: !GetAtt FailedEventsQueue.Arn
Policies:
- S3ReadPolicy:
BucketName: !Ref ReceiptBucket
- DynamoDBWritePolicy:
TableName: !Ref ReceiptTable
- Statement:
- Effect: Allow
Action: textract:AnalyzeExpense
Resource: '*'
Events:
ReceiptUploaded:
Type: S3
Properties: Bucket: !Ref ReceiptBucket
Events: s3:ObjectCreated:*
Filter:
S3Key:
Rules:
- Name: prefix
Value: uploads/

Outputs:
BucketName:
Value: !Ref ReceiptBucket
TableName:
Value: !Ref ReceiptTable
DeadLetterQueueUrl:
Value: !Ref FailedEventsQueue
Why these choices?
  • Public access blocked and encryption on: receipts often contain personal data.
  • On-demand DynamoDB: you pay per request, so there’s no capacity to plan for a workload with unpredictable traffic.
  • Prefix filter on  uploads/ : it keeps the function from triggering on its own outputs if you later write results back to the same bucket.
  • Scoped IAM policies: the function can only read from this bucket and write to this table. Textract’s  AnalyzeExpense  doesn’t support resource-level restrictions, so  Resource: '*'  is required for that single action.

Step 3: Write the Lambda function

Paste this into  src/app.py :
python
import json
import logging
import os
import urllib.parse
from datetime import datetime, timezone

import boto3

logger = logging.getLogger()
logger.setLevel(logging.INFO)

textract = boto3.client("textract")
table = boto3.resource("dynamodb").Table(os.environ["TABLE_NAME"])

WANTED_FIELDS = {
"VENDOR_NAME": "vendor",
"INVOICE_RECEIPT_DATE": "date",
"SUBTOTAL": "subtotal",
"TAX": "tax",
"TOTAL": "total",
}

def extract_summary(expense_doc):
"""Pick the first occurrence of each field we care about."""
result = {}
for field in expense_doc.get("SummaryFields", []):
field_type = field.get("Type", {}).get("Text")
if field_type in WANTED_FIELDS:
name = WANTED_FIELDS[field_type]
if name not in result:
value = field.get("ValueDetection", {}) result[name] = value.get("Text", "")
result[f"{name}_confidence"] = str(round(value.get("Confidence", 0), 1))
return result

def extract_line_items(expense_doc):
items = []
for group in expense_doc.get("LineItemGroups", []):
for line in group.get("LineItems", []):
item = {}
for field in line.get("LineItemExpenseFields", []):
key = field.get("Type", {}).get("Text")
if key in ("ITEM", "QUANTITY", "PRICE"):
item[key.lower()] = field.get("ValueDetection", {}).get("Text", "")
if item:
items.append(item)
return items

def handler(event, context):
for record in event["Records"]:
bucket = record["s3"]["bucket"]["name"]
key = urllib.parse.unquote_plus(record["s3"]["object"]["key"])
logger.info("Processing s3://%s/%s", bucket, key)

response = textract.analyze_expense(
Document={"S3Object": {"Bucket": bucket, "Name": key}}
)

docs = response.get("ExpenseDocuments", [])
if not docs:
raise ValueError(f"No expense data found in {key}")
expense_doc = docs[0]
item = {
"receiptId": key,
"processedAt": datetime.now(timezone.utc).isoformat(),
**extract_summary(expense_doc),
"lineItems": extract_line_items(expense_doc),
}

table.put_item(Item=item)
logger.info("Saved receipt %s", key)

return {"statusCode": 200, "body": json.dumps("ok")}
Design notes:
  •  unquote_plus  is essential: S3 event keys are URL-encoded, so a file named  my receipt.jpg  arrives as  my+receipt.jpg .
  • Values are stored as strings. DynamoDB’s Python SDK rejects  float  values, and keeping Textract’s raw text avoids rounding and currency-format issues. You can normalize later.
  • Confidence scores are saved so downstream logic can flag low-confidence extractions for human review.
  • Raising an exception on failure lets Lambda retry and then send the event to the DLQ.
Leave  src/requirements.txt  empty.  boto3  is included in the Lambda runtime.

Step 4: Build and deploy

bash
sam build
sam deploy --guided
For the guided prompts, choose a stack name such as  receipt-pipeline , pick your Region, and accept the defaults. Allow SAM to create the required IAM roles. When the deployment finishes, note the  BucketName  and  TableName  outputs.

Step 5: Test the pipeline

Upload a sample receipt:
bash
aws s3 cp ./sample-receipt.jpg s3://<BucketName>/uploads/sample-receipt.jpg
Wait a few seconds, then check DynamoDB:
bash
aws dynamodb scan --table-name <TableName>
You should see an item with the vendor, date, totals, confidence scores, and line items.
To watch the function run:
bash
sam logs --stack-name receipt-pipeline --tail

Step 6: Test the failure path

Upload a file that isn’t a receipt, such as a blank image. Textract may return no usable data, the function raises an error, and Lambda retries. After retries are exhausted, the event appears in the DLQ:
bash
aws sqs receive-message --queue-url <DeadLetterQueueUrl>
In production, add a CloudWatch alarm on the queue’s  ApproximateNumberOfMessagesVisible  metric so you’re notified when documents fail.

Security best practices

  • Least privilege: the function’s role is limited to one bucket, one table, and one Textract action.
  • No public access: S3 Block Public Access is enabled on the bucket.
  • Encryption: S3 uses server-side encryption by default. DynamoDB encrypts at rest by default, and you can switch to a customer-managed AWS KMS key if your compliance needs require it.
  • Data lifecycle: add an S3 lifecycle rule to expire raw receipts after your retention period.
  • Sensitive data: avoid logging full extracted values. Log keys and IDs instead.

Cost considerations

This architecture is pay-per-use. Costs come from Textract pages analyzed (typically the largest component), Lambda invocations and duration, DynamoDB on-demand requests and storage, and S3 storage and requests. Pricing varies by Region and changes over time, so use the AWS Pricing Calculator and the Textract pricing page to estimate your cost before scaling up. If you stay within the AWS Free Tier limits for your account, small experiments cost very little.

Troubleshooting

Symptom
Likely cause
Fix
Lambda never triggers
Wrong prefix or deployment issue
Upload to  uploads/ , and confirm the S3 event notification exists on the bucket
 AccessDeniedException  from Textract
Missing permission
Confirm  textract:AnalyzeExpense  is in the function role
 UnsupportedDocumentException 
Unsupported format or multi-page PDF
Use JPEG, PNG, or a single-page PDF
 File not found  for keys with spaces
Key not URL-decoded
Keep the  unquote_plus  call
 Float types are not supported 
Writing floats to DynamoDB
Store as strings or use  Decimal 
Empty or partial fields
Blurry or rotated image
Re-scan at higher quality, and check the confidence scores

Clean up

To avoid ongoing charges, empty the bucket first (CloudFormation can’t delete a non-empty bucket), then delete the stack:
bash
aws s3 rm s3://<BucketName> --recursive
sam delete --stack-name receipt-pipeline

Next steps and extensions

  1. Add an API: put Amazon API Gateway in front of a second Lambda function to query receipts by vendor or date, with a Global Secondary Index on  vendor .
  1. Support multi-page PDFs: switch to  StartExpenseAnalysis , and use Amazon SNS to notify Lambda on completion.
  1. Human review: route low-confidence results to a review queue with Amazon Augmented AI (A2I).
  1. Notifications: publish to Amazon SNS when a receipt total exceeds a threshold.
  1. Reporting: export data to Amazon S3 and query it with Amazon Athena.
  1. CI/CD: deploy automatically with GitHub Actions or AWS CodePipeline.

Conclusion

You’ve built an event-driven, serverless document-processing pipeline that scales automatically, costs nothing when idle, and is fully reproducible as code. The same pattern of upload, event, process, store works for invoices, forms, ID documents, and many other workloads. Try swapping Textract for another AI service, or chain more steps with AWS Step Functions.
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