Build a High-Throughput File Storage Backend
System DesignModel answerLast updated
Design a backend system that ingests and serves large files at scale, handling millions of users with high availability and durability guarantees.
You're tasked with architecting a backend system that manages high-volume file operations for a global user base. The service must efficiently ingest large files (up to 50 GB), store them durably, and serve them quickly to users worldwide.
Your design should address:
- Requirements gathering: Define what the system must do (functional) and how well it must perform (non-functional, including latency, throughput, durability, and availability targets)
- Capacity estimation: Perform calculations to size the infrastructure—bandwidth needs, storage growth, request volume, and costs
- API contract: Specify endpoints for upload, download, and metadata operations
- Architecture: Propose the system's structure, including load distribution, stateless services, storage layers, caching strategy, content delivery, and message queues
- Scalability: Explain how each component scales horizontally and how to optimize for performance while controlling costs
- Security: Cover authentication, authorization, encryption (both in transit and at rest), rate limiting, and tenant isolation
- Reliability: Describe failure handling, retry logic, idempotency guarantees, consistency models, and disaster recovery plans
- Operations: Outline deployment strategy, observability (logging, metrics, tracing), incident response, and safe rollback procedures
- Edge cases: Identify and solve challenges like interrupted uploads, duplicate requests, slow clients, and network partitions
Be concrete. Use realistic numbers, make explicit trade-offs, and show how the pieces fit together.
Hints
Hint 1
Start by scoping the problem to a specific use case with concrete scale parameters—avoid designing in the abstract
Hint 2
The control plane (metadata, orchestration) and data plane (byte movement) have different scaling characteristics; consider separating them
Hint 3
CDN hit rates dramatically affect origin load and cost; calculate the impact of a 95% hit rate on bandwidth requirements
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: High-Throughput File Storage Backend
Approach: Narrow the Problem Space
System design interviews reward focus. Rather than describing every possible feature, I'll anchor on a concrete scenario: a file storage service similar to cloud object storage, supporting uploads up to 50 GB, global downloads, and basic metadata operations for 10 million daily active users.
The critical insight is recognizing this as a bandwidth-dominated, read-heavy workload where the data path must be separated from the control path.
1. Requirements Definition
Functional scope:
- Chunked, resumable uploads with integrity verification
- Range-request downloads (enabling video seeking and resume)
- Metadata operations: list files, delete, generate time-limited share links
- Optional async processing: virus scanning, thumbnail generation
Non-functional targets:
- Scale: 10M DAU, globally distributed
- Durability: 99.999999999% (eleven nines)
- Availability: 99.95% for reads, 99.9% for writes
- Performance: p99 time-to-first-byte under 200 ms (via CDN), upload speed limited only by client bandwidth
- Consistency: Strong consistency for metadata after commit; eventual consistency acceptable for CDN and derived data
2. Capacity Planning
Assume each user uploads one 20 MB file daily and downloads ten files:
- Daily ingest: 10M users × 20 MB = 200 TB/day
- Average ingest rate: 200 TB ÷ 86,400 s ≈ 2.3 GB/s
- Peak ingest (3× average): ~7 GB/s
- Daily egress: 10× ingest = 2,000 TB/day → 23 GB/s average, 69 GB/s peak
- Origin egress (assuming 95% CDN cache hit): 69 GB/s × 0.05 = 3.5 GB/s
- Annual storage growth: 73 PB raw data × 1.4 (erasure coding overhead) ≈ 100 PB
- Metadata volume: 3.65 billion records/year × 1 KB ≈ 3.6 TB
Key takeaways: CDN is mandatory. Bandwidth, not request count, drives scaling. Metadata fits comfortably in a sharded relational database. Storage cost dominates operational expenses, making tiering essential.
3. API Design
POST /v1/uploads
Body: {file_size, sha256, content_type}
Headers: Idempotency-Key
Returns: {upload_id, chunk_size, signed_urls[]}
PUT /v1/uploads/{upload_id}/chunks/{chunk_num}
Body: raw bytes
Headers: Content-MD5
Returns: {etag}
GET /v1/uploads/{upload_id}/status
Returns: {chunks_received: [1,2,3,5], missing: [4]}
POST /v1/uploads/{upload_id}/commit
Body: {chunks: [{num, etag}, ...]}
Returns: {file_id, version}
GET /v1/files/{file_id}
Headers: Range (optional)
Returns: 302 redirect to signed CDN URL or byte stream
DELETE /v1/files/{file_id}
Soft delete with async garbage collection
The signed URLs for chunk uploads point directly to object storage, bypassing the API tier for the byte path.
4. Data Model
Files table (sharded by tenant_id):
file_id, tenant_id, user_id, size_bytes, sha256, content_type, status (PENDING|ACTIVE|DELETED), storage_key, version, created_at, updated_at
Upload sessions:
upload_id, tenant_id, file_id, chunk_size, idempotency_key (unique index), expires_at, status
Chunks:
(upload_id, chunk_num) PRIMARY KEY, etag, size_bytes, uploaded_at- Re-uploading the same chunk number replaces the previous entry
Storage: Immutable objects in blob store, keyed by tenant_id/sha256_prefix/sha256. Within-tenant deduplication saves space; cross-tenant dedup leaks information.
5. Architecture
Users ──┬─► CDN (cache hit) ──► response
│
└─► (cache miss) ──► Origin tier ──► Object storage
┌─► Load balancer ──► API gateway (auth, rate limit)
│ ├─► Control plane: Upload/metadata service
│ │ └─► PostgreSQL (sharded), Redis cache
│ │
│ └─► Data plane: Signed URL generation
│ └─► Object storage (S3-compatible)
│
└─► Event stream (Kafka) ◄── Storage events
└─► Worker pool (scan, transcode, thumbnail)
Design rationale: The control plane handles orchestration and metadata in stateless API servers. The data plane moves bytes directly between clients and object storage using signed URLs, avoiding proxying through application servers. This separation allows independent scaling: the control plane scales on request volume; the data plane on bandwidth.
6. Deep-Dive Topics
Resumable Uploads
Clients split files into 8–64 MB chunks and upload in parallel (4–8 concurrent connections). On network failure, they call the status endpoint to identify missing chunks and retry only those. The commit operation verifies that all chunks arrived, computes the final checksum, and atomically transitions the file from PENDING to ACTIVE. Incomplete uploads expire after 48 hours; a background job deletes orphaned chunks.
Idempotency
Each POST /uploads includes an idempotency key (UUID). If the same key arrives twice, return the original upload session. Chunk uploads are inherently idempotent (keyed by chunk number). The commit operation uses a database constraint (WHERE status='PENDING') to ensure it executes exactly once. Asynchronous workers are at-least-once with deduplication keys like (file_id, version, task_type).
Consistency Model
Write the blob to storage first, then update metadata. A crash between these steps leaves an orphaned blob (cleaned by garbage collection), never a dangling pointer. Metadata uses synchronous replication within a region for read-after-write consistency. File modifications create new versions rather than in-place updates, preventing readers from seeing partial content. CDN cache invalidation happens on delete, or alternatively, use versioned URLs.
Handling Slow Clients
Use asynchronous I/O (epoll, io_uring) to handle thousands of connections per server without thread-per-connection overhead. Enforce read timeouts and minimum throughput thresholds (e.g., disconnect if transfer rate drops below 10 KB/s for 60 seconds). Apply backpressure: pause reading from the socket when downstream buffers fill, avoiding memory exhaustion. At the CDN layer, implement request coalescing to prevent thundering herds on viral content.
Horizontal Scaling
API servers are stateless and autoscale based on CPU and request rate. The metadata database shards by tenant_id; hot tenants can be further split by file_id hash. Object storage scales independently via built-in sharding. Workers scale on queue depth. CDN points of presence scale globally. The bottleneck shifts from compute to bandwidth as the system matures.
Cost Optimization
Erasure coding (e.g., Reed-Solomon 10+4) reduces storage costs to ~40% of triple replication while maintaining high durability. Lifecycle policies automatically move infrequently accessed files to cheaper tiers. A 95% CDN hit rate reduces origin bandwidth costs—typically the largest expense—by 20×. Per-tenant quotas and rate limits prevent abuse.
7. Security Architecture
Authentication: OAuth 2.0 or JWT tokens validated at the API gateway. Signed URLs for chunk uploads and downloads include object-specific permissions and short expiration times (15 minutes).
Authorization: Role-based access control checked on every metadata operation. Pre-upload authorization validates tenant quotas and user permissions before issuing signed URLs.
Encryption: TLS 1.3 for all connections. Object storage uses server-side encryption with tenant-specific keys managed by a KMS. Optional client-side encryption for sensitive data.
Isolation: Tenant data lives in separate storage prefixes. Database queries always include tenant_id in the WHERE clause. Rate limiting applies per-tenant to prevent noisy neighbors.
8. Failure Handling
Retry strategy: Clients use exponential backoff with jitter for transient failures. The API returns 503 with Retry-After headers when overloaded.
Disaster recovery: Asynchronous replication to a secondary region. Metadata snapshots every hour with point-in-time recovery. Object storage uses cross-region replication with versioning enabled.
Partial failures: Circuit breakers prevent cascading failures. Degrade gracefully: if thumbnail generation fails, still serve the file. Health checks remove unhealthy nodes from load balancer pools within seconds.
9. Observability and Operations
Metrics: Track upload success rate, chunk retry rate, p50/p95/p99 latency by endpoint, CDN hit rate, object storage error rates, queue depth, and per-tenant bandwidth.
Logging: Structured logs with trace IDs linking requests across services. Logs shipped to centralized aggregation (e.g., ELK stack).
Tracing: Distributed traces show the path of an upload from API entry through chunk storage to commit.
Deployment: Blue-green deployments for stateless services. Database schema changes use expand-contract pattern. Feature flags allow gradual rollout. Automated rollback triggered by error rate thresholds.
10. Edge Cases and Testing
- Interrupted uploads during commit: Transaction rollback leaves status as PENDING; client can retry commit with same chunk list
- Duplicate simultaneous uploads: Idempotency keys plus database unique constraints prevent duplicate records
- Clock skew: Use monotonic sequence numbers rather than timestamps for ordering
- Network partitions: Metadata database uses quorum reads/writes; accept write latency increase over split-brain
- Byzantine chunks: Verify checksums on both upload and download; reject mismatched data
Testing strategy: Chaos engineering (randomly kill pods, inject latency). Load testing with realistic file size distributions. Integration tests covering the full upload-commit-download cycle with injected failures at each step.
Time Complexity: Most operations are O(1) in request count (sharded databases, distributed object storage). Upload/download are O(n) in bytes, limited by network bandwidth, not system design.
Space Complexity: O(files × avg_size) for blob storage, O(files) for metadata. Chunking keeps memory usage O(chunk_size) regardless of file size.
This architecture handles the stated requirements while remaining cost-effective and operationally manageable. The separation of concerns—control plane, data plane, async workers—allows teams to scale and evolve each component independently.