Build a Cloud File Sync and Storage Platform
System DesignModel answerLast updated
Architect a scalable system for storing, synchronizing, and sharing files across devices with versioning, conflict resolution, and offline support.
You're tasked with architecting a cloud-based file storage and synchronization platform similar to modern file-sync services. Users should be able to upload files and folders, keep them synchronized across their devices, collaborate through sharing, and recover previous versions.
Your system must support:
- Core synchronization: Upload and download files; monitor local filesystem changes; propagate updates to all connected devices
- Efficient transfers: Handle large files through chunking and resumable transfers; sync only changed portions of files; eliminate duplicate data storage
- History and recovery: Maintain version history for each file; support restoration of deleted or previous versions
- Conflict handling: Resolve simultaneous edits from multiple devices, including changes made while offline
- Offline operation: Allow clients to work disconnected and reconcile changes upon reconnection
- Collaboration: Enable sharing files and folders with individuals or groups; support public links with permissions and expiration
- Real-time updates: Notify devices of changes immediately via push mechanisms with appropriate fallbacks
- Security: Protect data in transit and at rest; compare server-side versus client-side encryption approaches
- Mobile optimization: Respect battery, bandwidth, and background execution constraints; support selective synchronization
- Resource management: Track and enforce storage quotas; account for savings from deduplication and compression
- Data organization: Design schemas for files, chunks, versions, permissions, deletion records, and change tracking
- Consistency guarantees: Define what users see when reading and writing from different devices simultaneously
- Operational scale: Plan for hundreds of millions of users; address sharding, hot partitions, monitoring, disaster recovery, and schema evolution
Focus on the fundamental architecture, critical trade-offs, and how components interact. Real-time collaborative document editing is out of scope.
Hints
Hint 1
Separate metadata (filenames, permissions, versions) from content (actual file bytes) into different storage systems
Hint 2
Use content-addressable storage where chunks are identified by their cryptographic hash to enable deduplication
Hint 3
Maintain an append-only change log per user or shared folder to enable efficient synchronization and conflict detection
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
The key architectural insight is separating metadata from content. File data becomes immutable, content-addressed chunks in blob storage, while the namespace—paths, versions, permissions—lives in a consistent metadata store with an append-only change log. This separation enables efficient sync, versioning, deduplication, and conflict resolution.
Requirements and Scale Assumptions
Functional requirements:
- Store and sync files across devices
- Chunk-based transfer with delta sync
- Version history and restoration
- Sharing with permissions and links
- Offline editing capability
- Change notifications
- Quota enforcement and selective sync
Non-functional targets:
- 99.999999999% durability (11 nines)
- 99.9% metadata availability
- Sub-5-second sync latency for typical files
- Never silently drop writes
Capacity estimates:
- 500M users, 100M daily active, ~2.5 devices per user
- 10 GB average per user = ~5 EB logical storage
- 30–40% savings from deduplication and compression → ~3 EB stored
- With erasure coding overhead (1.4×) → ~4 EB raw
- 100M DAU × 20 file operations/day = 2B operations/day (~23K/sec average, ~70K/sec peak)
- Metadata queries (polling, listings) are 10–50× higher volume
The system is primarily constrained by metadata query throughput and total blob storage capacity.
API Design
POST /commit
Body: {namespace_id, path, parent_version, chunk_hashes[], size, timestamp}
Response: {version_id} | {missing_chunks: [...]} | {conflict, current_version}
PUT /chunks/{content_hash}
(Idempotent upload, resumable)
GET /chunks/{content_hash}
(Returns signed CDN URL)
GET /changelog?namespace_id&since_cursor
Response: {changes[], next_cursor, more}
GET /poll?cursors[]
(Long-poll for changes across multiple namespaces)
POST /share
Body: {namespace_id, path, user|link_token, permission_level, expiration}
POST /revert
Body: {file_id, target_version}
The commit flow uses a two-phase protocol:
- Client sends chunk list
- Server identifies missing chunks
- Client uploads only missing chunks
- Client resubmits commit
- Version becomes visible atomically once all chunks are durable
Data Model
Namespace (namespace_id, owner, type) — The unit of sharding, permissions, and change tracking. A shared folder becomes its own namespace.
ChangeLog (namespace_id, sequence_number↑, path, file_id, version_id, chunk_list, size, content_hash, deleted, device_id, timestamp) — Append-only log with monotonically increasing sequence numbers. Client cursors reference the last sequence seen.
FileVersion (file_id, version_id, chunk_list, creator, timestamp) — Immutable version records retained per retention policy.
ChunkMetadata (content_hash → storage_key, size, compression_algo, encryption_key_id, reference_count)
Permission (namespace_id, path_prefix, principal, role) and ShareToken (token_hash, target_resource, permissions, expiration, password_hash)
DeviceMount (user_id, namespace_id, local_mount_path)
Quota (user_id, logical_bytes, billable_bytes)
Architecture Components
Client sync agent: Monitors filesystem (inotify/FSEvents/ReadDirectoryChangesW), chunks and hashes files, maintains local SQLite index mapping paths to versions and chunks, keeps a write-ahead log of pending operations.
API gateway: Handles authentication, rate limiting, and routing.
Metadata service: Sharded, strongly-consistent store (MySQL with sharding, Vitess, or Spanner-like system). Sharded by namespace_id. Each shard uses Raft or semi-synchronous replication for consistency.
Blob storage: Object storage system (S3-compatible or custom erasure-coded store) with CDN for downloads.
Notification hub: Manages long-polling connections, WebSockets, and triggers push notifications (APNs/FCM).
Background workers: Garbage collection for unreferenced chunks, version expiration, thumbnail generation, search indexing, quota accounting.
Key Design Decisions
Chunking and Deduplication
Use content-defined chunking (FastCDC or Rabin fingerprinting) with average 4 MB chunks (range 1–16 MB). Fixed-size chunks fail when insertions at the beginning shift all subsequent boundaries.
Chunks are identified by SHA-256 hash, making deduplication a simple lookup. Uploads resume at chunk boundaries. Compress chunks (zstd) before encryption.
Deduplication scope trade-off:
- Global dedup maximizes savings but enables confirmation-of-file attacks (checking if a file exists anywhere)
- Mitigation: Use per-user dedup for small files, or require proof-of-ownership before skipping uploads
- For enterprise, per-organization dedup balances savings and security
Conflict Resolution and Offline Support
Every commit includes a parent_version field. The metadata shard serializes commits per namespace, providing linearizable consistency without vector clocks—the server is the single authority.
On conflict, the server rejects the commit. The client preserves both versions, saving its version as filename (conflicted copy from Device, timestamp).ext and committing it as a new file.
Offline edits queue in the client's write-ahead log as (operation, path, parent_version, local_hash, operation_id). On reconnect, operations replay in order. Each operation is idempotent via client-generated operation_id.
Delete-edit conflicts favor preservation: the edit wins and the file is restored.
Versioning and Restoration
Deletions append tombstone entries to the changelog. File chunks remain immutable.
Restoration creates a new version pointing to an old chunk list—no data copying required. This is instant and storage-efficient.
Garbage collection decrements chunk reference counts when versions expire. Implement as mark-and-sweep with a grace period, since reference counts can drift under concurrent operations.
Sharing and Permissions
Shared folders are independent namespaces with their own changelogs. ACL checks verify namespace membership with role-based permissions inherited down the tree. Path-specific overrides use longest-prefix matching.
Share links are 128-bit cryptographic tokens, stored hashed, with associated permissions (view/edit), expiration, and optional password protection.
Downloads use time-limited signed CDN URLs (valid 15–60 minutes).
Revocation is immediate at the metadata layer. CDN URL expiration provides defense-in-depth.
Change Notifications
Push notifications are hints only—they indicate "namespace X changed" without carrying data or being reliable.
Clients then pull /changelog?since_cursor. Correctness depends solely on the cursor mechanism, not push delivery.
Desktop clients maintain long-poll or WebSocket connections. Mobile clients receive platform push notifications (APNs/FCM), which the OS may throttle.
Fan-out uses a namespace → subscribed-devices mapping. For large shared folders, coalesce notifications over 1–2 second windows to reduce amplification.
Encryption
In transit: TLS 1.3 for all connections.
At rest: Envelope encryption—per-chunk data keys wrapped by KMS-managed key-encryption keys.
Server-side encryption (SSE):
- Server manages keys
- Enables deduplication, server-side search, previews, thumbnails
- Protects against storage breaches but not compromise of the service itself
Client-side encryption (CSE):
- Client manages keys; server stores opaque encrypted blobs
- Breaks deduplication, server-side search, and previews
- Provides protection even if the service is compromised
- Users must manage key backup and recovery
Most services default to SSE with optional CSE for high-security users willing to trade features for privacy.
Mobile Optimization
- Selective sync: Users choose which folders sync to mobile devices
- On-demand download: Files appear as placeholders; download on access
- Battery-aware scheduling: Batch operations; defer non-urgent sync
- Network-aware transfers: Pause large uploads on cellular; resume on WiFi
- Background execution: Use platform-appropriate background task APIs; respond to push notifications within execution-time budgets
Consistency Model
Within a namespace: Linearizable. The metadata shard serializes all commits; clients see a consistent ordering via the changelog sequence.
Across namespaces: Eventually consistent. Changes to separate shared folders propagate independently.
Client view: Eventually consistent. Clients poll for updates; local view converges within seconds under normal conditions.
Clients may see their own writes immediately via optimistic UI updates, confirmed when the server commit succeeds.
Scalability and Operations
Sharding: Partition by namespace_id. Hot namespaces (large shared folders with many collaborators) require additional strategies:
- Partition large folders into subnamespaces
- Cache heavily-accessed metadata
- Rate-limit per-user operations within shared spaces
Monitoring: Track commit latency, sync lag (time from commit to propagation), chunk upload/download throughput, metadata query latency, push notification delivery rates, and client retry/conflict rates.
Disaster recovery: Metadata requires cross-region replication with sub-minute RPO. Blob storage uses multi-region erasure coding or replication.
Schema evolution: Online migrations require dual-writing during transition. Example: changing chunk size requires background reprocessing with old chunks remaining readable during migration.
Common failure modes:
- Split-brain during network partitions → mitigated by strongly-consistent metadata store with proper quorum
- Thundering herd on popular files → CDN, rate limiting, and staggered retries
- Cascading failures from hot namespaces → isolation via separate request queues per namespace shard
- Metadata-blob inconsistency → metadata commits only after blob durability is confirmed; reconciliation jobs detect and repair orphaned blobs
This architecture scales to hundreds of millions of users by treating metadata and content as separate problems, using immutable content-addressed chunks for efficiency, and maintaining simple, strongly-consistent ordering within each namespace.