πŸ’‘
Hey β€” It's Sandip Das πŸ‘‹

This project teaches how to design scalable, event-driven, and container-orchestrated workloads using Fargate, Celery, and SQSβ€”exactly how real production systems handle high-volume document processing.

It also builds expertise in serverless OCR pipelines with Textract, giving hands-on experience with distributed workers, asynchronous task queues, and AWS-native automation patterns used in enterprise architectures.

⚑ Quick Reference

Keep the momentum going β€” everything you need on LearnXOps in one place:


πŸ‘£
60 Days of DevOps (Complete)
30 Days of MLOps (Complete)
90 Days of Cloud (in progress)

🧠 Learn here

About this project:

A scalable Web+API service for asynchronous document processing using AWS services.

This is a complete, production-ready document processing system with:

  • βœ… Backend API - FastAPI with authentication
  • βœ… Workers - Celery workers for async processing
  • βœ… Frontend - React SPA with modern UI
  • βœ… Infrastructure - All AWS resources via Terraform
  • βœ… Single Command Deployment - Everything deploys with ./deploy.sh

Project Architecture

Document processing on Fargate, Celery and SQS: two ALBs, API, frontend and Celery workers in private subnets, S3 to Lambda to SQS, workers calling Textract, Rekognition and SNS

Components:

1. API Layer (FastAPI on ECS Fargate)

REST API for file uploads and job management

Endpoints:

  • POST /upload - Upload files for processing
  • GET /status/{job_id} - Check processing status
  • GET /results/{job_id} - Retrieve processing results
  • GET /health - Health check
  • DELETE /jobs/{job_id} - Delete job and files

Technology:

  • FastAPI (Python)
  • Uvicorn ASGI server
  • ECS Fargate (serverless containers)
  • Application Load Balancer

Scaling:

  • Runs 1 task by default (api_desired_count)
  • Stateless, so you can add an autoscaling policy and run more tasks

2. Storage Layer (Amazon S3)

Durable storage for uploaded and processed files

Structure:

s3://bucket-name/
β”œβ”€β”€ uploads/
β”‚   └── {job_id}/
β”‚       └── {filename}
└── processed/
    └── {job_id}/
        β”œβ”€β”€ thumbnail.jpg
        └── results.json

Features:

  • Server-side encryption (AES-256)
  • Versioning enabled
  • Lifecycle policies:
    • Uploads deleted after 30 days
    • Processed files β†’ Standard-IA after 30 days, Glacier after 90 days
    • Permanent deletion after 365 days

3. Event Processing (Lambda)

Trigger processing when files are uploaded

Flow:

  1. S3 emits ObjectCreated event
  2. Lambda receives event
  3. Lambda enqueues Celery task to SQS
  4. Returns immediately (async processing)

Configuration:

  • Runtime: Python 3.11
  • Memory: 256 MB
  • Timeout: 60 seconds
  • Trigger: S3 ObjectCreated events on uploads/ prefix

4. Task Queue (Amazon SQS)

Reliable message broker for Celery

Configuration:

  • Visibility timeout: 3600s (1 hour)
  • Message retention: 14 days
  • Long polling: 20 seconds
  • Dead Letter Queue for failed messages

Features:

  • At-least-once delivery
  • FIFO not required (idempotent workers)
  • Failed messages become visible again after the visibility timeout; after 3 receives they move to the DLQ

5. Worker Layer (Celery on ECS Fargate)

Asynchronous document processing

Tasks:

  • process_document - Main orchestration task
  • extract_text_ocr - OCR via AWS Textract
  • generate_thumbnail - Image/video thumbnails
  • extract_metadata - File metadata extraction
  • analyze_image - AWS Rekognition analysis
  • send_notification - SNS email notifications

Processing Pipeline:

1. Download file from S3
2. Extract metadata (parallel)
3. Generate thumbnail (if applicable)
4. Run OCR (for documents/images)
5. Analyze image (for images)
6. Upload results to S3
7. Update DynamoDB status
8. Send SNS notification
9. Clean up temp files

Scaling:

  • Auto-scales on average CPU (target 70%)
  • Min: 2 workers
  • Max: 10 workers
  • Concurrency: 2 tasks per worker

6. AI/ML Services

AWS Textract

  • Extract text from PDFs and images
  • Table and form detection
  • Multi-page document support

AWS Rekognition

  • Object and scene detection
  • Content moderation
  • Text detection in images
  • Face detection (optional)

7. Data Layer (DynamoDB)

Jobs Table

Track job status and metadata

Schema:

{
  "job_id": "uuid",
  "status": "pending|processing|completed|failed",
  "s3_key": "uploads/job_id/file.pdf",
  "file_name": "document.pdf",
  "file_size": 1024000,
  "file_type": "application/pdf",
  "notification_email": "[email protected]",
  "created_at": "2024-01-01T00:00:00Z",
  "updated_at": "2024-01-01T00:05:00Z",
  "completed_at": "2024-01-01T00:05:00Z",
  "results": "{...}",
  "error": "error message if failed"
}

Indexes:

  • Primary: job_id
  • GSI: status + created_at (for querying by status)

Celery Results Table

Purpose: Store Celery task results

Configuration:

  • TTL enabled (auto-delete old results)
  • Pay-per-request billing

8. Notification Layer (Amazon SNS)

Email notifications on job completion

Flow:

  1. Worker completes processing
  2. Publishes message to SNS topic
  3. SNS delivers email to subscriber
  4. User receives notification with results

Message Format:

Subject: Document Processing Completed: {job_id}
Body:
  Job ID: abc-123-def
  Status: completed
  Results:
    - OCR Text: 1234 characters
    - Thumbnail: https://...
    - Labels: [document, text, business]

9. Monitoring (CloudWatch)

Logs:

  • /aws/ecs/doc-processor-api - API logs
  • /aws/ecs/doc-processor-worker - Worker logs
  • /aws/ecs/doc-processor-frontend - Frontend logs
  • /aws/lambda/doc-processor-s3-trigger - Lambda logs

Metrics:

  • ECS CPU/Memory utilization
  • ALB request count and latency
  • SQS queue depth and age
  • Lambda invocations and errors
  • DynamoDB read/write capacity

Alarms (recommended):

  • API error rate > 5%
  • Worker CPU > 80%
  • SQS queue depth > 100
  • Lambda errors > 10/min

Network Architecture

VPC Configuration

VPC: 10.0.0.0/16

Public Subnets (2 AZs):
β”œβ”€β”€ 10.0.1.0/24 (us-east-1a)
└── 10.0.2.0/24 (us-east-1b)
    └── ALB, NAT Gateways

Private Subnets (2 AZs):
β”œβ”€β”€ 10.0.10.0/24 (us-east-1a)
└── 10.0.11.0/24 (us-east-1b)
    └── ECS Tasks (API + Workers)

Security Groups:

  • ALB SG: Allow 80/443 from internet
  • ECS SG: Allow 8000 from ALB SG only
  • Egress: Allow all (for AWS service access)

VPC Endpoints:

  • S3 Gateway Endpoint (cost optimization)
  • Optional: Interface endpoints for other services

Data Flow

Upload Flow

1. Client β†’ ALB β†’ API
2. API validates file
3. API uploads to S3 (uploads/{job_id}/file)
4. API creates DynamoDB record
5. API returns job_id to client
6. S3 β†’ Lambda (event trigger)
7. Lambda β†’ SQS (enqueue task)
8. Worker polls SQS
9. Worker processes file
10. Worker updates DynamoDB
11. Worker sends SNS notification

Processing Flow

Worker receives task from SQS
β”œβ”€β†’ Download file from S3
β”œβ”€β†’ Extract metadata
β”‚   └─→ File size, type, dimensions
β”œβ”€β†’ Generate thumbnail
β”‚   β”œβ”€β†’ Images: PIL resize
β”‚   β”œβ”€β†’ Videos: ffmpeg frame extract
β”‚   └─→ PDFs: pdf2image + resize
β”œβ”€β†’ Run OCR (if applicable)
β”‚   └─→ AWS Textract DetectDocumentText
β”œβ”€β†’ Analyze image (if applicable)
β”‚   β”œβ”€β†’ AWS Rekognition DetectLabels
β”‚   β”œβ”€β†’ AWS Rekognition DetectModerationLabels
β”‚   └─→ AWS Rekognition DetectText
β”œβ”€β†’ Upload results to S3
β”œβ”€β†’ Update DynamoDB (status=completed)
└─→ Send SNS notification
One document start to finish: browser upload, API to S3 and DynamoDB, S3 event to Lambda and SQS, worker processing with Textract and Rekognition, results to S3, status to DynamoDB, SNS email, and status polling

How Celery Document Processing Works

The system uses Celery for asynchronous document processing with the following workflow:

1. File Upload & Trigger

User uploads file β†’ API stores in S3 β†’ S3 event triggers Lambda β†’ Lambda enqueues Celery task to SQS

2. Task Queue (SQS)

  • Lambda sends task message to Amazon SQS queue
  • SQS acts as the Celery broker for reliable message delivery
  • Workers poll SQS for new tasks

3. Worker Processing Pipeline

# Main task: process_document(job_id, s3_key)
1. Download file from S3
2. Extract metadata (file size, type, dimensions)
3. Generate thumbnail (images/videos/PDFs)
4. Run OCR via AWS Textract (if applicable)
5. Analyze image via AWS Rekognition (if applicable)
6. Upload results to S3 (processed/{job_id}/)
7. Update DynamoDB job status to 'completed'
8. Send SNS email notification
9. Clean up temporary files

4. Task Execution

  • Celery Workers: Run as ECS Fargate containers
  • Concurrency: 2 tasks per worker (configurable)
  • Auto-scaling: Workers scale on average CPU (target 70%)
  • Retry Logic: If a task fails, SQS makes the message visible again after the 1-hour visibility timeout
  • Dead Letter Queue: After 3 receives, the message moves to the DLQ

5. Result Storage

  • Job Status: Stored in DynamoDB doc-processor-jobs table
  • Task Results: Stored in DynamoDB doc-processor-celery-results table
  • Processed Files: Stored in S3 processed/{job_id}/ prefix
  • Thumbnails: Accessible via pre-signed URLs (1-hour expiry)

6. Status Tracking

pending β†’ processing β†’ completed/failed
  • Users can check status via /status/{job_id} endpoint
  • The job details view polls every 3 seconds while a job is processing
  • Email notification sent on completion

Example Task Flow

1. User uploads "document.pdf"
2. API: Creates job record with status='pending'
3. S3: Triggers Lambda on ObjectCreated event
4. Lambda: Enqueues task {"job_id": "abc-123", "s3_key": "uploads/abc-123/document.pdf"}
5. Worker: Picks up task from SQS
6. Worker: Updates status to 'processing'
7. Worker: Extracts text using Textract
8. Worker: Generates thumbnail using pdf2image
9. Worker: Uploads thumbnail.jpg to S3
10. Worker: Updates job with results and status='completed'
11. Worker: Sends SNS notification
12. User: Receives email and views results in dashboard

IAM Roles

ECS Task Execution Role:
└─→ Pull ECR images
└─→ Write CloudWatch logs

API Task Role:
β”œβ”€β†’ S3: Read/Write
β”œβ”€β†’ DynamoDB: Read/Write (jobs table)
└─→ SQS: SendMessage

Worker Task Role:
β”œβ”€β†’ S3: Read/Write
β”œβ”€β†’ DynamoDB: Read/Write (both tables)
β”œβ”€β†’ SQS: ReceiveMessage, DeleteMessage
β”œβ”€β†’ Textract: DetectDocumentText, AnalyzeDocument
β”œβ”€β†’ Rekognition: DetectLabels, DetectModerationLabels
└─→ SNS: Publish

Lambda Execution Role:
β”œβ”€β†’ S3: GetObject
β”œβ”€β†’ SQS: SendMessage
└─→ CloudWatch: Logs

Cost Optimization

Strategies

  1. Fargate Spot (not enabled in the repo): up to 70% off worker tasks
  2. S3 Lifecycle: Auto-archive old files
  3. DynamoDB On-Demand: Pay per request
  4. VPC Endpoints: Reduce NAT costs
  5. CloudWatch Retention: 7 days (configurable)
  6. ECR Lifecycle: Keep last 10 images

Estimated Monthly Cost

Assumptions: 10,000 documents/month, avg 5MB each; us-east-1 on-demand prices with the repo's default task counts

Service Cost
ECS Fargate (API, 1 Γ— 0.5 vCPU / 1 GB) $18
ECS Fargate (Workers, 2 Γ— 1 vCPU / 2 GB) $72
ECS Fargate (Frontend, 1 Γ— 0.25 vCPU / 0.5 GB) $9
ALBs (API + frontend) $33
NAT Gateways (2) $66
Public IPv4 addresses (6) $22
S3 Storage (50GB) $1.15
S3 Requests $0.50
DynamoDB $2.50
SQS Free tier
Lambda Free tier
Textract (10K pages) $15
Rekognition (10K images Γ— 3 APIs) $30
SNS (email) <$1
CloudWatch $5
Data Transfer $5
Total ~$280/month

The always-on pieces (Fargate tasks, two load balancers, NAT gateways) are most of the bill. Fargate Spot for workers, one NAT gateway for dev, or scaling workers to zero when the queue is empty cut it the most.


Let's deploy this project

Prerequisites

  • AWS CLI configured with appropriate credentials
  • Terraform >= 1.0
  • Docker
  • Python 3.11+

Project Structure

.
β”œβ”€β”€ api/                    # FastAPI application
β”‚   β”œβ”€β”€ main.py            # API endpoints & authentication
β”‚   β”œβ”€β”€ models.py          # Pydantic models
β”‚   └── config.py          # Configuration
β”œβ”€β”€ frontend/               # React web application
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ components/    # React components
β”‚   β”‚   β”‚   β”œβ”€β”€ Auth/      # Login/Signup
β”‚   β”‚   β”‚   β”œβ”€β”€ Dashboard/ # Job management
β”‚   β”‚   β”‚   └── Upload/    # File upload
β”‚   β”‚   β”œβ”€β”€ services/      # API client
β”‚   β”‚   └── App.jsx        # Main app
β”‚   β”œβ”€β”€ package.json
β”‚   └── vite.config.js
β”œβ”€β”€ worker/                 # Celery workers
β”‚   β”œβ”€β”€ celery_app.py      # Celery configuration
β”‚   β”œβ”€β”€ tasks.py           # Processing tasks
β”‚   └── processors/        # Processing modules
β”‚       β”œβ”€β”€ metadata_processor.py
β”‚       β”œβ”€β”€ thumbnail_processor.py
β”‚       β”œβ”€β”€ ocr_processor.py
β”‚       └── image_processor.py
β”œβ”€β”€ lambda/                 # Lambda functions
β”‚   └── s3_trigger.py      # S3 event handler
β”œβ”€β”€ terraform/              # Infrastructure as Code
β”‚   β”œβ”€β”€ main.tf            # Main configuration
β”‚   β”œβ”€β”€ variables.tf       # Input variables
β”‚   β”œβ”€β”€ outputs.tf         # Output values
β”‚   β”œβ”€β”€ vpc.tf             # VPC & networking
β”‚   β”œβ”€β”€ ecs.tf             # ECS cluster & services
β”‚   β”œβ”€β”€ frontend.tf        # Frontend ECS service
β”‚   β”œβ”€β”€ s3.tf              # S3 buckets
β”‚   β”œβ”€β”€ lambda.tf          # Lambda functions
β”‚   β”œβ”€β”€ dynamodb.tf        # DynamoDB tables
β”‚   β”œβ”€β”€ sns.tf             # SNS topics
β”‚   β”œβ”€β”€ sqs.tf             # SQS queues
β”‚   └── iam.tf             # IAM roles & policies
β”œβ”€β”€ docker/                 # Docker configurations
β”‚   β”œβ”€β”€ api.Dockerfile     # API container
β”‚   β”œβ”€β”€ worker.Dockerfile  # Worker container
β”‚   β”œβ”€β”€ frontend.Dockerfile # Frontend container
β”‚   └── nginx.conf         # Nginx config for frontend
β”œβ”€β”€ deploy.sh              # Deployment script
β”œβ”€β”€ cleanup.sh             # Cleanup script
β”œβ”€β”€ Makefile               # Build & deployment tasks
β”œβ”€β”€ requirements.txt       # Python dependencies
β”œβ”€β”€ .env.example           # Environment variables template
└── README.md              # Documentation

Deployment

Clone Repo:

git clone https://github.com/sd031/AWS-Python-Celery-Bases-Document-Processing-Service.git
cd AWS-Python-Celery-Bases-Document-Processing-Service

Run the deployment script:

chmod +x deploy.sh
./deploy.sh

That's it! The script will:

  1. βœ… Create the ECR repositories
  2. βœ… Build and push the API, worker and frontend images
  3. βœ… Deploy all AWS infrastructure (Terraform)
  4. βœ… Restart the ECS services on the new images
  5. βœ… Check the API health endpoint
  6. βœ… Output all URLs and endpoints

Time: 15-20 minutes

Deployment Output

After deployment, you'll see:

========================================
Deployment Summary
========================================
Backend API: http://doc-processor-alb-XXXXX.us-east-1.elb.amazonaws.com
Frontend URL: http://doc-processor-frontend-alb-XXXXX.us-east-1.elb.amazonaws.com


========================================
Next Steps:
========================================
1. Access Frontend

Visit the Frontend URL from the deployment output:

 http://doc-processor-frontend-alb-XXXXX.us-east-1.elb.amazonaws.com


2. Create Account

- Click "create a new account"
- Enter name, email, password
- Click "Sign up"

3. Upload Document

- Drag and drop a file (or click browse)
- Supported formats:
  - PDF documents
  - Images: PNG, JPG, GIF, WebP, TIFF, BMP
  - Videos: MP4, MOV, AVI
- Click "Upload and Process"

4. Watch Progress

- Job appears in "Recent Jobs" list
- Progress bar shows 0-100%
- Status updates every 3 seconds
- Stages:
  - 🟑 Pending
  - πŸ”΅ Processing (20% β†’ 40% β†’ 70% β†’ 100%)
  - 🟒 Completed
  - πŸ”΄ Failed (if error)

5. View Results

Click on completed job to see:
- Document Info: Type, size, dates
- Metadata: Pages, author, creator, etc.
- OCR Text: Full extracted text
- Thumbnail: Preview image
- Labels: AI-detected objects (for images)

🚨 Cleanup

To destroy all resources:

./cleanup.sh


Challenges:

  1. Add HTTPS Support - Configure ACM certificates and enable HTTPS on both ALBs for secure communication
  2. Implement WebSocket Updates - Replace polling with WebSocket connections for real-time job status updates
  3. Add Batch Processing - Allow users to upload and process multiple files simultaneously in a single request
  4. Create Admin Dashboard - Build an admin panel to monitor all users, jobs, and system metrics across the platform
  5. Multi-Region Deployment - Extend the architecture to support multi-region deployment with cross-region replication for disaster recovery

🀷🏻 How to Participate?

βœ… Complete the tasks and challenges.
βœ… Document your progress and key takeaways on GitHub ReadMe, Medium, or Hashnode.
βœ… Share the above in a LinkedIn post tagging me (Sandip Das), and use #90DaysOfCloud to engage with the community!


⚑ Quick Reference

Keep the momentum going β€” everything you need on LearnXOps in one place:

Share this post