Build a Multi-Region Distributed Storage Platform
System DesignModel answerLast updated
Design a cloud storage system handling file uploads, synchronization, and sharing with strong durability, partition tolerance, and global availability.
You're tasked with architecting a distributed storage platform similar to enterprise file-sharing services. Users should be able to upload files, organize them in folders, keep them synchronized across multiple devices, share with collaborators, and access version history.
Your design should address:
-
Requirements clarification: Define functional capabilities and quantify non-functional targets (durability SLAs, latency percentiles, availability zones, throughput expectations, and consistency guarantees).
-
Component architecture: Identify the major services, data stores, message buses, and client responsibilities. Explain how they communicate.
-
API contracts and data schemas: Specify the key endpoints and how you model files, revisions, namespaces, and access control.
-
Data distribution: Describe your sharding strategy, replication topology, and consistency model. Address transactions, preventing duplicate processing, and handling schema changes over time.
-
Performance layers: Explain where and how you cache data at the client, edge network, and application tiers.
-
Traffic management: Cover load distribution, request routing across regions, and horizontal scaling policies.
-
Resilience patterns: Detail timeout policies, retry strategies with backoff, cascading failure prevention, graceful degradation, and disaster recovery targets (recovery point and time objectives).
-
Operations and security: Outline monitoring, logging, tracing, request throttling, authentication, authorization, and encryption approaches.
-
Growth planning: Estimate capacity needs from user and traffic assumptions, identify cost optimization opportunities, and sketch a phased scaling approach.
-
Risk assessment: Call out the most likely bottlenecks, failure modes, and how you'd mitigate them.
Throughout, justify your choices and discuss the trade-offs between alternatives.
Hints
Hint 1
Choose a specific problem domain immediately—generic designs without concrete use cases rarely succeed
Hint 2
Separate metadata operations from content operations; they have different consistency, durability, and throughput characteristics
Hint 3
Content-addressed storage enables deduplication, resumable uploads, and simplified caching
Hint 4
Sharding by user namespace allows single-shard transactions and avoids distributed coordination on the critical path
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Multi-Region Distributed Storage Platform
This answer demonstrates strong system design by choosing cloud file storage with cross-device sync as the concrete domain, then systematically working through each architectural concern with specific numbers and justifications.
1. Requirements and Scale Estimation
Functional Scope
- File operations: upload, download, delete, organize into folders
- Multi-device synchronization with conflict detection
- Collaboration via file/folder sharing
- Maintain version history for rollback
Non-Functional Targets (State Numbers)
- Durability: 99.999999999% (11 nines) for stored content—data loss is catastrophic
- Availability: 99.99% uptime for reads/downloads, 99.9% for writes
- Latency: metadata queries p99 < 200ms; sync notifications delivered within 2 seconds
- Consistency: Strong consistency per user/folder namespace to prevent conflicting edits; content blocks are immutable and eventually consistent
Capacity Math
Starting assumptions: 100M total users, 20M daily active, average 2GB stored per user
- Storage: 200PB logical data. With erasure coding (1.4× overhead) and cross-region replication: ~400PB physical
- Upload volume: 20M users × 10 files/day × 1MB average = 200TB/day ingress, ~2.5GB/s sustained, peak ~10K uploads/s
- Metadata QPS: list/sync operations roughly 30× write rate, so ~100K QPS at peak
Key insight: Content volume is massive but simple to scale (append-only blobs). Metadata is smaller but requires strong consistency and complex queries—design them as separate systems.
2. Architecture Overview
Clients (desktop/mobile/web)
↓ HTTPS
CDN & Edge Layer
↓
API Gateway (auth, rate limiting, routing)
↓
┌────────────┬──────────────┬───────────────────┬─────────────┐
│ Metadata │ Block │ Notification │ Permissions │
│ Service │ Service │ Service │ Service │
└─────┬──────┴──────┬───────┴────────┬──────────┴──────┬──────┘
│ │ │ │
Sharded SQL Object Store Event Stream ACL Store
(namespaces) (immutable) (Kafka/Pulsar)
↓
Async Consumers:
thumbnails, search indexing,
virus scanning, analytics
Design Decisions
Separate metadata from content flow: Clients upload content as fixed-size blocks (4MB chunks) identified by SHA-256 hash directly to Block Service via pre-signed URLs. After upload completes, they commit a file version record to Metadata Service.
Benefits: Natural deduplication, resumable uploads, and the metadata tier never handles bulk data.
Event-driven architecture: Every metadata mutation appends to an ordered change log per namespace. Downstream services (sync, notifications, indexing) consume this log.
Benefits: Decouples expensive async work (thumbnail generation, scanning) from user-facing write path; provides exactly-once semantics for side effects.
3. API Design and Data Model
Core Endpoints
POST /blocks/verify {hashes: []} → {missing: []}
PUT /blocks/{hash} (binary, pre-signed) → 201
POST /files/commit {namespace, path, → {version} | 409
block_refs[],
parent_version,
idempotency_token}
GET /namespaces/{id}/changelog?after=cursor → {changes[], next}
GET /files/{id}/content → {signed_urls[]}
Schema (Sharded by namespace_id)
Metadata tables:
files(namespace_id, file_id, path, current_version, is_deleted)versions(namespace_id, file_id, version, block_list, size, created_by, created_at)changelog(namespace_id, sequence, operation, file_id, version)permissions(namespace_id, principal_id, access_level)
Block registry (separate KV store): blocks(hash → storage_location, reference_count)
4. Partitioning and Consistency
Sharding Strategy
Partition metadata by namespace_id (a user's root folder or shared workspace). All operations within one namespace route to a single shard, enabling ACID transactions without distributed coordination.
Trade-off: Very large shared folders (hot namespaces) can overwhelm a shard. Mitigation: Sub-shard by directory prefix when a namespace exceeds size threshold (e.g., 100K files).
Use a directory service that maps namespace → shard, allowing transparent shard splits and rebalancing without client-visible rehashing.
Replication Topology
Each shard runs a consensus group (Raft or Multi-Paxos, similar to Spanner or CockroachDB):
- 3 synchronous replicas across availability zones within primary region (strong consistency)
- 1+ asynchronous replicas in secondary region (disaster recovery)
Writes go to the leader; strongly consistent reads also hit the leader. Reads tolerating bounded staleness (e.g., <1 second) can use local followers.
Consistency Model
- Commits are compare-and-set operations: Client provides
parent_version; if it doesn't match current, return 409 conflict. Client resolves by creating a "conflicted copy" rather than silently overwriting. - Transactional outbox pattern: Single database transaction writes to
files,versions, andchangelog. Change data capture (CDC) propagates changelog entries to Kafka, avoiding dual-write inconsistency. - Idempotency: Blocks are naturally idempotent (content-addressed). Commits include an
idempotency_tokenstored for 24h; retries return the original result. Consumers track(namespace_id, sequence)to deduplicate.
Schema Evolution
Use expand-contract migrations: (1) add new nullable column, (2) dual-write to both old and new, (3) backfill historical data, (4) switch reads to new column, (5) remove old column. For events, use versioned schemas (Protocol Buffers or Avro) with backward compatibility requirements.
5. Caching Strategy
- Client tier: Local block cache and metadata database. Clients store the last-seen change cursor and fetch only incremental deltas on sync.
- CDN/Edge: Immutable blocks are perfect CDN candidates—hash-keyed, long TTL, no invalidation needed. Downloads return short-lived signed URLs pointing to CDN.
- Application tier: Redis cache for ACL lookups and popular folder listings. Invalidate on changelog events, use short TTLs (30-60s) to bound staleness. Never cache the CAS read used in commits—it must hit the authoritative leader.
6. Load Balancing and Scaling
Request routing: GeoDNS directs users to nearest region. Layer 7 load balancers use least-connections algorithm across stateless service pods.
Namespace routing: Gateway directs write requests to the region hosting the namespace's Raft leader. Read requests can be served locally from followers with bounded-staleness guarantees.
Horizontal scaling: Stateless tiers (API gateway, block service, notification service) autoscale on CPU and request rate. Metadata shards scale through planned shard splits, not reactive autoscaling—splitting a live shard requires careful coordination.
7. Failure Handling and Recovery
Timeout and retry policy: Every request carries a deadline propagated to downstream services. Retries use exponential backoff with jitter, are capped at 3 attempts, and only apply to idempotent operations. Enforce a retry budget (~10% of baseline traffic) to prevent retry storms.
Circuit breakers: Wrap dependencies like thumbnail service and search indexer. When open, degrade gracefully—uploads succeed but previews show a placeholder.
Backpressure: Bounded queues with priority-based shedding. Background sync polls back off before interactive requests do. Kafka consumer lag triggers worker scaling. Gateway returns 429 or 503 with Retry-After header during overload.
Disaster recovery:
- RPO (Recovery Point Objective): Near-zero for metadata via synchronous replication; <5 minutes for blocks via async cross-region copy.
- RTO (Recovery Time Objective): <15 minutes to promote secondary region's async replicas to leaders and reroute traffic.
- Regular restore drills from snapshots to validate procedures.
8. Observability and Security
Monitoring: Expose RED metrics (rate, errors, duration) for every service. Track infrastructure metrics (CPU, memory, disk, network). Set alerts on SLO violations (p99 latency, error rate >0.1%, durability checks).
Logging and tracing: Structured logs with correlation IDs. Distributed tracing (OpenTelemetry) for request flows across services. Audit log in append-only storage for compliance.
Rate limiting: Token bucket per user and per IP. Higher limits for premium tiers. Return 429 with Retry-After when exceeded.
Authentication: OAuth 2.0 / OIDC for user identity. Short-lived JWT access tokens, long-lived refresh tokens in httpOnly cookies.
Authorization: Role-based access control stored per namespace. Hierarchical permissions (owner → editor → viewer). Check ACLs at gateway for performance.
Encryption: TLS 1.3 in transit. AES-256 at rest for both metadata and blocks. Optional client-side encryption where clients hold keys.
9. Capacity Planning and Cost
Storage costs dominate: 400PB × $0.023/GB/month (standard tier) ≈ $9M/month. Optimize by tiering: hot data (accessed in 30 days) in standard tier, cold data in archive tier ($0.004/GB/month).
Compute costs: ~2,000 service instances × $0.05/hour ≈ $70K/month. Egress is significant: 200TB/day downloads × $0.08/GB ≈ $500K/month. Mitigation: aggressive CDN caching (95% hit rate reduces egress by 20×).
Phased scaling:
- MVP (1M users): Single-region, 10 metadata shards, basic replication
- Growth (10M users): Add secondary region, 100 shards, CDN integration
- Scale (100M users): Multi-region active-active, 1000 shards, tiered storage, ML-based caching
10. Bottlenecks and Mitigations
Hot namespaces: Large shared folders can overload a shard. Mitigation: Monitor shard load; sub-shard by directory when a namespace exceeds thresholds.
Thundering herd on popular files: Viral content causes cache misses and origin overload. Mitigation: Cache warming, request coalescing (multiple concurrent requests deduplicated), and admission control.
Metadata shard splits: Require coordination and can cause brief write unavailability. Mitigation: Over-provision shards; split proactively based on growth projections rather than reactively.
Cross-region consistency: Async replication has lag. During regional failover, recent writes may be lost. Mitigation: Synchronous multi-region writes for critical namespaces (slower but more durable); clearly document RPO to users.
Cost explosion: Storage and egress costs grow superlinearly. Mitigation: Lifecycle policies to archive cold data, egress optimization via CDN and compression, and usage quotas.
This design balances strong consistency where needed (metadata), eventual consistency where acceptable (content), and graceful degradation under failure. The separation of concerns, immutable content addressing, and event-driven architecture provide a foundation that scales to billions of files and petabytes of data.