Design a Distributed File Sync and Sharing Platform
System DesignModel answerLast updated
Build the architecture for a multi-client file storage system with hierarchical organization, collaborative sharing, chunked uploads, and cross-device synchronization.
Design the backend architecture for a file storage platform that supports multiple concurrent clients and collaborative workflows.
Your system should enable users to organize files in nested directories, grant access to collaborators with different permission levels, and maintain consistency across web browsers, desktop applications, and mobile devices. The platform needs to handle connection interruptions gracefully and preserve a history of changes.
Core Requirements
Your design must address:
- File operations: creating, retrieving, removing, relocating, and renaming both files and directories
- Hierarchical organization: nested directory structures owned by individuals or teams
- Collaborative access: granting permissions (owner, editor, commenter, viewer) that cascade through subdirectories
- Resilient uploads: breaking large files into segments that can resume after network failures
- Historical tracking: maintaining previous file states with restoration capability
- Multi-device consistency: propagating changes to all connected clients, including handling modifications made while offline
- Discovery: finding files by name, owner, type, and modification timestamp
- Reliability: ensuring high uptime, data durability, and protection against unauthorized access
Describe your end-to-end architecture including: component organization, API contracts, storage layer design, data schema, upload/download flows, client synchronization mechanism, consistency guarantees, horizontal scaling strategy, failure recovery, and key engineering trade-offs.
Scale & Performance Expectations
- User base: expect 10M+ registered accounts with several million actively syncing clients maintaining persistent connections
- Storage volume: petabyte-scale corpus with individual files ranging from kilobytes to multiple gigabytes
- Request patterns: predominantly read-oriented (downloads, listings, sync checks) outpacing writes roughly 10:1, though write volume remains substantial
- Durability goal: match industry-standard object storage (approximately 99.999999999% annual durability through geographic replication)
- Availability goal: keep core metadata and download operations available; search and thumbnail generation can tolerate brief degradation
- Security requirements: encrypted transport and storage, time-limited signed access tokens, audit logging for access and sharing events
- Out of scope: concurrent multi-user document editing with conflict-free merge (treat as separate real-time collaboration layer); simple last-write-wins or conflict-copy approach suffices
Recommended Clarifications
Consider asking:
- Does isolation occur at the individual user level, or do shared team/organization workspaces exist with independent permission trees?
- What file size distribution should we optimize for, and what's the maximum supported file size?
- Should we implement block-level differential sync (re-uploading only modified chunks), or is full-file replacement acceptable initially?
- How sophisticated are permission requirements—simple access lists, or nested groups, public links with expiration and passwords?
- Does search need to index file contents, or only metadata attributes?
- What retention policies apply to deleted items and version history (trash retention period, version count limits)?
- Do we need active-active multi-region writes for global low latency, or is single-write-region with read replicas sufficient?
Hints
Hint 1
Separate concerns: metadata operations (permissions, directory structure) have different consistency needs than blob storage (immutable file contents).
Hint 2
For resumable uploads, consider how clients can upload chunks independently before atomically committing the complete file manifest.
Hint 3
Synchronization requires tracking a sequence of changes—think about how clients efficiently discover what's new since their last sync without scanning the entire tree.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
High-Level Architecture
The system decomposes into three primary layers:
API Gateway & Application Tier: Stateless services handling authentication, request routing, and business logic. These servers validate permissions, coordinate metadata transactions, and orchestrate blob operations.
Metadata Store: A strongly consistent, partitioned database holding directory structures, file metadata, version chains, permission rules, and sync event logs. Partition by user ID or workspace ID for horizontal scaling.
Blob Storage: Object storage (S3, GCS, Azure Blob) for immutable file contents, fronted by a CDN for frequently accessed files. Each blob is content-addressed or version-addressed.
Supporting Services: Search indexer (Elasticsearch/Solr), notification service (push to connected clients), thumbnail generator, audit logger, and monitoring/metrics collection.
Data Model
Files and Directories: Each node (file or folder) has a stable UUID, a name, parent ID, owner, timestamps, and type. Files additionally reference blob storage keys and version chains. Folders are just nodes with children. This parent-pointer model supports efficient move operations (update one parent field) and prevents cycles through validation.
Versions: Each file edit creates a new version record with a version number, timestamp, blob key, size, and checksum. Retain the N most recent versions per retention policy.
Permissions: Store ACLs at the node level with user/group grants (owner, editor, commenter, viewer). For efficient evaluation, precompute effective permissions at query time or cache resolved permissions per user-node pair with TTL. Group memberships live in a separate service/table.
Change Log: Maintain an append-only log of events (create, modify, delete, share, move) with monotonic sequence numbers per workspace. Clients sync by requesting changes since their last-seen sequence number.
Upload Flow (Chunked & Resumable)
-
Initialization: Client requests an upload session from the API, specifying file name, parent directory, and total size. Server validates permissions, generates a session ID, and returns chunk parameters (chunk size ~4-16MB).
-
Chunk Upload: Client splits the file and uploads chunks directly to blob storage using presigned URLs or SAS tokens. Each chunk is stored with a session-scoped key (e.g.,
uploads/{session_id}/chunk_{n}). Client computes and includes per-chunk checksums. If a chunk fails, the client retries only that chunk. -
Commit: Once all chunks upload successfully, client calls a commit endpoint with the session ID and chunk checksums. Server validates chunk integrity, creates a manifest combining chunks into the final blob (or triggers a server-side concatenation job), generates a content-addressed blob key, creates metadata records (file node + version), appends to the change log, and returns success. This commit is an atomic transaction in the metadata store.
-
Idempotency: Use idempotency keys on the commit request. If the client retries after a network failure, the server recognizes the duplicate and returns the existing file ID without re-processing.
Download Flow
-
Authorization Check: Client requests a file via API. Server loads the file node, evaluates the requester's permissions (via ACL resolution, checking inherited permissions up the tree), and validates access.
-
Signed URL Generation: If authorized, server generates a short-lived signed URL (valid 1 hour) pointing directly to the immutable blob in object storage. The signature includes resource path, expiration, and requester identity.
-
Direct Download: Client fetches from object storage using the signed URL. Popular files are served from CDN edge caches, reducing origin load and latency. Audit log records the access event asynchronously.
Synchronization Protocol
Clients maintain a cursor (last-seen change log sequence number) and periodically poll or hold a long-lived connection to receive updates.
Initial Sync: Client downloads the full directory tree and file metadata for the workspace, storing it locally with the starting cursor.
Incremental Sync: Client requests changes since its cursor. Server returns a batch of change events (creates, updates, deletes, permission changes) with sequence numbers. Client applies these events to its local state and advances its cursor.
Offline Edits: When offline, clients queue local changes. On reconnect, they upload new/modified files and issue metadata operations. If a conflict occurs (another client modified the same file), apply last-write-wins based on server timestamps, or create a conflict copy if modification timestamps are close (within seconds).
Push Notifications: For online clients, use WebSockets or Server-Sent Events to push change notifications immediately, reducing sync latency from polling intervals to sub-second.
Consistency Model
Metadata Operations: Strong consistency within a partition (workspace/user). A move or permission change commits atomically and is immediately visible to all clients querying that partition. Use ACID transactions in the metadata database (Postgres, Spanner, DynamoDB with transactions).
Blob Storage: Immutable blobs are trivially consistent—once written, a version never changes. New versions get new keys.
Cross-Partition Operations: If supporting shared folders across workspaces, accept eventual consistency for cross-workspace permission updates (propagate asynchronously) or scope sharing to prevent cross-partition writes.
Derived Data: Search indexes, thumbnails, and activity feeds are eventually consistent. Changes appear within seconds to minutes depending on indexing lag. This trade-off is acceptable for non-critical features.
Permission Evaluation
For a read/write operation:
- Load the target node and walk up parent pointers until reaching a node with an explicit ACL or the root.
- Collect all grants applying to the requester (direct user grants + group memberships).
- Apply role hierarchy (owner > editor > commenter > viewer).
- Cache the result per (user, node, operation) tuple with a short TTL (5-10 minutes) in a distributed cache (Redis). Invalidate cache entries on permission changes.
For high-traffic shared folders, precompute a permission index asynchronously: when a folder's ACL changes, enqueue a job to recompute and store effective permissions for all descendants. Trade increased write complexity for faster reads.
Scaling Strategy
Metadata Database: Partition by workspace/user ID. Each partition is an independent shard with its own change log. Clients always interact with their home partition. Use consistent hashing or a routing table to map IDs to shards. Replicate each shard for availability (primary + replicas).
Blob Storage: Object stores scale horizontally by design. Use multiple buckets/containers if needed for namespace isolation or regional distribution. CDN caching handles read amplification.
API Tier: Stateless servers scale horizontally behind a load balancer. Add instances as request volume grows.
Search: Shard the search index by user/workspace ID. Stream change log events to a search indexer service that updates Elasticsearch clusters asynchronously.
Hotspots: Public shared files create read hotspots—mitigate with aggressive CDN caching and rate limiting. Large-scale permission changes (e.g., revoking access to a shared folder with 100k files) require async background jobs to avoid blocking.
Failure Handling & Durability
Blob Durability: Object storage providers replicate across availability zones or regions. Enable versioning and cross-region replication for critical data. Set lifecycle policies to transition old versions to cheaper archival storage.
Metadata Backups: Continuous backup with point-in-time recovery (e.g., 30-day window). Regularly test restore procedures.
Idempotency: All mutating API calls accept idempotency keys to safely retry without duplicating operations.
Circuit Breakers: Wrap external service calls (object storage, search) in circuit breakers to fail fast and avoid cascading failures.
Graceful Degradation: If search is unavailable, serve cached results or return errors while keeping core upload/download operational.
Security
- Transport: TLS 1.3 for all client-server and service-to-service communication.
- Storage: Server-side encryption at rest (AES-256) for blobs and metadata.
- Access Control: Signed URLs with short TTLs limit blast radius of leaked tokens. Tokens are scoped to specific resources and operations.
- Audit Logging: Record all access, sharing, and deletion events to an immutable log (append-only, tamper-evident).
- Rate Limiting: Per-user and per-IP limits prevent abuse and DoS attacks.
Key Trade-Offs
Strong vs. Eventual Consistency: Metadata operations use strong consistency within a partition for correctness, accepting slightly higher latency. Search and notifications use eventual consistency to decouple indexing from the critical path.
Direct Upload vs. Proxied: Direct-to-storage uploads with presigned URLs offload bandwidth from application servers and reduce latency, but require clients to handle multiple HTTP requests and retry logic.
Permission Inheritance vs. Precomputation: Inherited ACLs simplify management and reduce storage, but slow down read checks. Precomputed indexes speed reads at the cost of write amplification and eventual consistency for permission changes on large subtrees.
Block-Level vs. File-Level Sync: Block-level delta sync (hashing chunks, re-uploading only changes) saves bandwidth for large edited files but adds complexity. Start with file-level; add block sync if metrics show frequent large-file edits.
Single-Region vs. Multi-Region Writes: Single-region writes simplify consistency (no conflict resolution) but increase latency for distant users. Multi-region active-active enables global low latency but requires careful conflict resolution and increases operational complexity. Choose based on user distribution and latency requirements.