Chunked Upload Pipeline with Async Processing
System DesignModel answerLast updated
Design a system that handles large file uploads with resumability, processes them through async validation and transformation stages, and notifies users of completion.
Problem Context
You're building a platform where users upload large media files—videos and images ranging from 100MB to 5GB. After upload, each file must pass through multiple processing stages: format validation, security scanning, transcoding to multiple resolutions, and automated content analysis. Your system must handle unreliable network conditions, coordinate these processing steps, and inform users when their content is ready.
Core Requirements
Your design should support:
- Chunked resumable uploads: Break large files into pieces that can be uploaded independently and resumed after network failures
- Direct storage writes: Route file data directly to object storage without saturating application servers
- Duplicate request handling: Ensure that retries and duplicate requests don't trigger redundant processing
- Multi-stage processing: Orchestrate independent analysis steps with proper ordering and parallelization
- User notifications: Deliver timely updates to clients about processing status
Scale Expectations
- Volume: 20 million upload sessions daily (~250/sec average, 1,000/sec peak)
- File characteristics: 200MB average, 5GB maximum
- Availability: 99.99% uptime target, 99.999999999% durability for stored files
- Processing time: Complete analysis within 3–5 minutes for typical 500MB videos
Design Scope
Your solution should address:
- Upload mechanics: API endpoints, chunking strategy, and how clients interact with storage
- State tracking: Data models for upload progress, file metadata, and task status
- Processing pipeline: Architecture for coordinating validation, transcoding, and analysis workers
- Reliability patterns: How you prevent data loss, handle failures, and ensure idempotency
- Client updates: Mechanism for pushing status changes back to users
Be specific about protocols, data structures, and failure scenarios.
Hints
Hint 1
Calculate bandwidth requirements to understand why application servers can't proxy the data
Hint 2
Consider how to make chunk uploads and completion requests safely retryable
Hint 3
Think about which processing steps must complete sequentially vs. which can run in parallel
Hint 4
Design for worker failures—tasks may be executed more than once
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Chunked Upload Pipeline Design
1. Clarify and Calculate
Before diving into design, establish critical numbers that shape architecture decisions:
Traffic calculations:
- 20M sessions/day × 200MB average = ~4 PB daily (theoretical maximum)
- 250 uploads/sec × 200MB = 50 GB/sec ≈ 400 Gbps sustained
- 1,000 uploads/sec × 200MB = 200 GB/sec ≈ 1.6 Tbps peak
Key insight: This bandwidth makes proxying through app servers impossible. Files must flow directly to object storage.
Chunking math:
- Using 16MB chunks: 200MB file = ~13 chunks, 5GB file = ~320 chunks
- Object stores like S3 support up to 10,000 parts with 5MB minimum per part
2. Upload Flow and API Design
Three-phase protocol:
Phase 1: Initialize
POST /api/v1/upload/init
Request: {file_name, file_size, content_type, checksum, dedup_token}
Response: {session_id, chunk_size, total_chunks, expiration}
Phase 2: Upload chunks (repeatable)
POST /api/v1/upload/{session_id}/urls?chunks=1,2,3
Response: [{chunk_num, presigned_url, expires_in}]
Client → PUT directly to presigned URL → receives ETag
POST /api/v1/upload/{session_id}/ack
Request: {chunk_num, etag, hash}
Response: {acknowledged}
Phase 3: Finalize
POST /api/v1/upload/{session_id}/finalize
Request: {chunks: [{num, etag}]}
Response: {file_id, state}
Design choices:
- Batch URL generation: Issue 10–20 URLs at once so clients can upload in parallel without roundtrips for each chunk
- Direct-to-storage: Presigned URLs grant temporary write access; bytes never touch API servers
- Progress tracking: The ack endpoint lets servers track which chunks succeeded, enabling resume from any point
- Resumability: Clients fetch current state via
GET /upload/{session_id}and skip already-uploaded chunks
3. Data Schema
Use a horizontally-scalable database (sharded relational or DynamoDB):
upload_sessions table:
session_id (PK), user_id, dedup_token (unique per user),
storage_upload_id, object_path, file_size, chunk_size,
expected_hash, state (INIT|ACTIVE|FINALIZING|COMPLETE|FAILED),
created_at, expires_at, version
uploaded_chunks table:
(session_id, chunk_num) (composite PK), etag, size, hash,
uploaded_at
media_files table:
file_id (PK), session_id (unique), content_hash,
state (QUEUED|PROCESSING|READY|REJECTED|ERROR), version
processing_jobs table:
(file_id, job_type) (composite PK), state, retry_count,
worker_id, lease_until, input_location, output_location,
error_message, updated_at
Use optimistic locking (version fields) for state transitions to prevent race conditions.
4. Architecture Overview
Mobile/Web Client
↓ (control) ↓ (data via presigned URLs)
API Layer ──────→ Object Storage (staging bucket)
↓ ↓
Upload Service S3 Event
↓ ↓
Metadata Store ←── Orchestrator ──→ Job Queues (per job type)
↓
┌────────────────────┼────────────────────┐
Validation Security Scan Parallel Branch:
Worker Pool Worker Pool - Transcode workers (GPU)
- Fingerprint workers (CPU)
- ML analysis workers (GPU)
↓
Event Stream
↓
Notification Service → WebSocket/SSE/Push
Processing DAG:
- Validation (required first): Check file format, codecs, resolution limits, duration constraints
- Security scan (required, blocks downstream): Malware detection
- Parallel processing (after scan passes):
- Transcode to multiple bitrates/resolutions
- Generate content fingerprints for copyright matching
- Run ML models for safety classification and tagging
- Aggregation: Mark file READY only when all required tasks succeed
Orchestration options:
- Managed: AWS Step Functions, Google Workflows, Temporal Cloud
- Self-hosted: Temporal, Cadence, custom event-driven coordinator
Workers pull from job-type-specific queues (SQS/Kafka) and scale based on queue depth.
5. Idempotency and Failure Handling
Chunk upload retries:
- Uploading the same chunk number multiple times simply overwrites in object storage
- The ack endpoint uses upsert semantics on (session_id, chunk_num)
Duplicate finalization:
- Use compare-and-swap:
UPDATE sessions SET state='FINALIZING' WHERE id=? AND state='ACTIVE' AND version=? - If already finalized, return the existing file_id
- Handle race: if storage completes but DB write fails, retry checks object existence before erroring
Job execution idempotency:
- Use transactional outbox pattern: commit state change and outgoing event atomically
- Workers write outputs to deterministic paths like
{file_id}/{job_type}/{attempt}/output.mp4 - Re-execution overwrites rather than duplicates
- Final state updates use CAS to prevent stale workers from overwriting results
Worker failures:
- Lease-based execution: workers claim jobs with expiring leases and heartbeat periodically
- Expired leases return jobs to queue automatically
- Retry with exponential backoff up to N attempts (e.g., 5)
- After exhaustion, move to dead-letter queue and mark file as FAILED
Deterministic failures:
- Malware detected, unsupported codec, policy violation → immediate terminal failure
- Don't retry these; notify user immediately
6. Notification System
Architecture:
Worker → DB state update + outbox event (atomic transaction)
↓
Event Relay (Debezium/custom)
↓
Event Topic (Kafka)
↓
Notification Service
- Looks up user's active connections in Redis
- Routes to appropriate WebSocket gateway server
- Falls back to mobile push if offline
↓
Client receives update
Connection registry: Map user_id → {gateway_server_id, connection_id, last_seen}
Fallback: If no live connection, store notification for retrieval and send push notification. Client can poll GET /api/v1/files/{file_id}/status as last resort.
7. Meeting Latency Targets
To process 500MB video in 3–5 minutes:
Parallelization strategies:
- Split video at keyframe boundaries into ~10-second segments
- Transcode segments in parallel across worker fleet
- Stitch encoded segments back together
- For ML analysis, extract keyframes and batch-process
Resource allocation:
- Separate worker pools by resource type (CPU-intensive vs GPU-intensive)
- Provision enough parallel workers to drain queues within target latency
- Monitor P95/P99 latency and scale worker pools dynamically
8. Trade-offs and Extensions
Storage costs: Keep raw uploads in cheap infrequent-access tier, transition to archival after 30 days
Processing priorities: Add priority queues for premium users or time-sensitive content
Partial results: Allow publishing with lower-resolution transcodes while high-res versions still process
Global distribution: Use multi-region object storage with cross-region replication; route uploads to nearest region
Cost optimization: Spot instances for batch processing workers, reserved capacity for baseline load
Monitoring: Track upload success rates, chunk retry rates, processing latency per stage, worker utilization, and queue depths
This design handles the specified scale while remaining resilient to network failures, worker crashes, and duplicate requests through careful state management and idempotent operations.