
Building an Automated Document Extraction Pipeline with Amazon Textract and Lambda
Learn how to build an event-driven, serverless document processing pipeline using Amazon S3, AWS Lambda, and Amazon Textract to extract structured text and form data at scale.
Manually transcribing data from scanned invoices, receipts, or student application forms is slow, error-prone, and impossible to scale. Traditional OCR tools often dump raw, unstructured text that still requires complex regex rules to parse.
By combining Amazon S3, AWS Lambda, and Amazon Textract, you can build a fully serverless, event-driven pipeline that automatically extracts key-value pairs and tables the moment a document is uploaded.
Architecture Overview
This pipeline eliminates polling and idle compute by reacting directly to storage events:
- Ingestion (Amazon S3): A user or upstream service uploads a PDF, PNG, or JPEG document to an input S3 bucket.
- Event Trigger (AWS Lambda): An
s3:ObjectCreated:*event notification automatically invokes a Python Lambda function with the bucket name and object key.
- AI Extraction (Amazon Textract): The Lambda function calls the Textract
analyze_documentAPI to detect raw text, form fields (key-value pairs), and structured tables.
- Persistence (Amazon DynamoDB): Extracted metadata and structured fields are stored in DynamoDB for downstream querying or dashboard display.
Step 1: Set Up Storage and Permissions
- Create an Amazon S3 bucket (e.g.,
doc-extraction-pipeline-input) to receive incoming files.
- Create an Amazon DynamoDB table named
ExtractedDocumentswithDocumentId(String) as the partition key.
- Create an IAM execution role for your Lambda function with permissions for:
-
s3:GetObjecton your input bucket
-
textract:AnalyzeDocument
-
dynamodb:PutItemon yourExtractedDocumentstable
Step 2: Implement the Lambda Extraction Function
Create a Python 3.12 Lambda function and attach an S3 trigger configured for the
.pdf , .png , and .jpg suffixes. Use boto3 to pass the S3 object reference directly to Textract:import json
import urllib.parse
import boto3
from datetime import datetime, timezone
s3 = boto3.client("s3")
textract = boto3.client("textract")
dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table("ExtractedDocuments")
def lambda_handler(event, context):
record = event["Records"][0]
bucket = record["s3"]["bucket"]["name"]
key = urllib.parse.unquote_plus(record["s3"]["object"]["key"])
# Analyze document for forms and tables directly from S3
response = textract.analyze_document(
Document={"S3Object": {"Bucket": bucket, "Name": key}},
FeatureTypes=["FORMS", "TABLES"]
)
# Collect detected lines of text
extracted_lines = [
block["Text"]
for block in response["Blocks"]
if block["BlockType"] == "LINE"
]
# Store structured output in DynamoDB
table.put_item(
Item={
"DocumentId": key,
"ProcessedAt": datetime.now(timezone.utc).isoformat(),
"LineCount": len(extracted_lines),
"ExtractedText": "\n".join(extracted_lines)
}
)
return {
"statusCode": 200,
"body": json.dumps({"document": key, "lines_extracted": len(extracted_lines)})
Step 3: Test and Verify the Pipeline
- Upload a sample invoice or form to your S3 bucket via the AWS Console or CLI (
aws s3 cp sample-form.png s3://doc-extraction-pipeline-input/).
- Open Amazon CloudWatch Logs to verify the Lambda execution completed without errors.
- Check the Explore items view in your
ExtractedDocumentsDynamoDB table to inspect the parsed text lines.
Why This Serverless Pattern Works Well
- Zero Infrastructure Management: There are no servers or GPU instances to provision; every service scales automatically with upload volume.
- Pay-Per-Page Pricing: You only pay for the exact pages Textract analyzes and the milliseconds your Lambda function runs.
- Easy AI Extensions: You can chain the extracted DynamoDB text directly into Amazon Comprehend for entity recognition or Amazon Bedrock for automated summarization.
Step 4: Parse Structured Key-Value Pairs (Forms)
In the code above, we collected raw
LINE blocks. However, the real power of analyze_document with FeatureTypes=["FORMS"] is extracting explicit key-value relationships (such as Invoice Number: INV-2049 or Total Amount: $450.00 ).You can map
KEY and VALUE blocks using their relationship IDs:def extract_key_values(blocks):
block_map = {block["Id"]: block for block in blocks}
key_values = {}
for block in blocks:
if block["BlockType"] == "KEY_VALUE_SET" and "KEY" in block.get("EntityTypes", []):
key_text = get_text(block, block_map)
value_block = find_value_block(block, block_map)
value_text = get_text(value_block, block_map) if value_block else ""
if key_text:
key_values[key_text.strip(":")] = value_text.strip()
return key_values
def find_value_block(key_block, block_map):
for rel in key_block.get("Relationships", []):
if rel["Type"] == "VALUE":
return block_map.get(rel["Ids"][0])
return None
def get_text(result, block_map):
words = []
for rel in result.get("Relationships", []):
if rel["Type"] == "CHILD":
for child_id in rel["Ids"]:
word = block_map.get(child_id)
if word and word["BlockType"] == "WORD":
words.append(word["Text"])
return " ".join(words)Production Best Practices & Edge Cases
Before deploying this pipeline into a production workload, consider these architectural safeguards:
- Multi-Page PDFs (Async API):
analyze_documentworks synchronously for single-page images and single-page PDFs. For multi-page PDF documents, switch to the asynchronousstart_document_analysisAPI paired with an Amazon SNS topic and Amazon SQS queue so Lambda never hits its 15-minute execution timeout.
- Dead-Letter Queues (DLQ): Configure an SQS Dead-Letter Queue on your Lambda function so corrupted uploads or temporary throttling errors are captured for replay instead of silently failing.
- Least-Privilege S3 Bucket Policies: Enforce server-side encryption (
SSE-S3orSSE-KMS) on your input bucket and restrict your Lambda IAM role tos3:GetObjecton a specific prefix (e.g.,uploads/*) rather than the entire bucket.
- Cost Optimization: If you only need raw text without form key-value pairs or tables, use
detect_document_textinstead ofanalyze_document—it is significantly cheaper per page.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article