Store and sync files across devices: chunks, deduplication, sync and sharing.
βDesign Dropbox. Or Google Drive. Something that keeps my files in sync across my devices.β
It is short on purpose. Your first job is to make it specific.
| What they check | Why it matters |
|---|---|
| Seeing that files are not rows | A file can be 10 GB and edited by small amounts. A strong candidate splits the file into chunks and treats metadata and bytes as two separate systems. |
| Bandwidth and storage thinking | The numbers show bytes, not requests, are the load. The interviewer wants to see you keep file bytes off the API servers and save bytes with dedup and delta sync. |
| A sync protocol, not just an upload API | Many devices change the same files. You need a change journal, a cursor, and a notification, so each device pulls only what it missed. |
| Conflict and consistency judgement | Two devices edit offline. Never losing a user's work is the product promise, and you should say how you detect and keep both versions. |
| Storage lifecycle and deletion | Chunks are shared by many files and versions. Deleting one safely, without racing a new upload, is where careless designs lose data. |
Cut every file into chunks of about 4 MB and name each chunk by its hash. Keep two systems: a block store that holds chunks (in object storage) and a metadata service that holds the folder tree and, for each file version, the ordered list of chunk hashes. The client uploads only the chunks the server does not already have, then commits the new version in one atomic step.
| Step | Minutes | What to get done |
|---|---|---|
| 1. Clarify | 4 | File size, devices, sharing, versions, offline. Rule out real-time co-editing. |
| 2. Estimate | 3 | Storage, upload bandwidth, commit rate, connections for notifications. |
| 3. API and data | 5 | Upload session, chunk put, commit, changes feed. Metadata tables and the block store. |
| 4. High-level design | 8 | Client sync engine, metadata service, block store, notification service. |
| 5. Deep dives | 15 | Chunking and dedup, the sync protocol, conflicts, then storage lifecycle and deletion. |
| 6. Scale and failures | 7 | Hot shared folders, upload failures, orphaned chunks, security, monitoring. |
| 7. Wrap up | 3 | Recap, trade-offs, what you would add next. |
| Ask | Why you ask it | Typical answer | How it changes the design |
|---|---|---|---|
| What is the largest file, and what is the average? | It decides whether chunking and resumable upload are needed, and how much bandwidth to plan for. | Up to 10 GB. Most files are small (around 1 MB). | Chunk files, upload in parallel, and make uploads resumable. |
| Do users have several devices that must stay in sync? | Sync is the hard part. One device would just be file hosting. | Yes: laptop, phone and web. Changes should appear within a few seconds. | Change journal, notifications, and a per-device cursor. |
| Can people share files and folders? | Sharing adds permissions and means many users can change one file. | Yes: share a file or folder with view or edit rights. | A shared folder is its own namespace with an access list. Updates fan out to all members. |
| Do we keep version history? | It controls how long old chunks must be kept, so it drives storage cost. | Yes, 30 days of versions, and deleted files can be restored. | Versions point to chunk lists. Garbage collection needs a retention rule. |
| Does the app work offline? | Offline edits are what create conflicts. | Yes. Edits are saved locally and synced later. | Client keeps a local database. The server must detect and handle conflicts. |
| Is real-time co-editing of one document needed? | That is a different, much harder problem (Google Docs). | No. Whole-file sync only. | No OT or CRDT in scope. Say it exists, and move on. |
| How should two conflicting edits behave? | Tests whether you protect user data. | Never lose work. Keep both and let the user decide. | Optimistic concurrency with a base version, and conflicted copies. |
| How many users, and how much does each store? | Gives the storage and bandwidth numbers. | 500M registered, 100M daily active, about 1 GB stored per user on average, 10 GB quota. | Hundreds of petabytes: object storage with erasure coding, and dedup. |
| Any privacy or compliance needs, such as end-to-end encryption? | End-to-end encryption conflicts with server-side dedup. | Encrypted in transit and at rest. End-to-end encryption is out of scope. | Server can see chunk hashes, so dedup works. Mention the trade-off. |
| Assumption | Value |
|---|---|
| Registered users | 500 million |
| Daily active users | 100 million |
| File changes per active user per day | 2 (new files or edits) |
| New bytes per change | 1 MB on average (after delta sync) |
| Stored per registered user | 1 GB on average (quota 10 GB) |
| Savings from dedup and compression | 30% |
| Download to upload ratio | 2 to 1 |
| Open sync connections | 1 per active device, 2 devices per active user, half connected at once |
| What | Maths | Result |
|---|---|---|
| File changes per day | 100M users Γ 2 | 200M / day |
| Commit rate (average) | 200M Γ· 86,400 s | about 2,300 / s |
| Commit rate (peak, 3Γ average) | 2,300 Γ 3 | about 7,000 / s |
| New data per day | 200M Γ 1 MB | 200 TB / day |
| Upload bandwidth (average) | 200 TB Γ· 86,400 s = 2.3 GB/s Γ 8 | about 18.5 Gbps |
| Upload bandwidth (peak) | 18.5 Gbps Γ 3 | about 55 Gbps |
| Total stored, before savings | 500M users Γ 1 GB | 500 PB |
| Total stored, after 30% savings | 500 PB Γ 0.7 | 350 PB |
| With 3 full copies, or erasure coding (1.5Γ) | 350 PB Γ 3, or Γ 1.5 | 1,050 PB, or 525 PB |
| Number of chunks | 350 PB Γ· 2 MB average chunk | about 175 billion |
| Chunk index size | 175B Γ 50 bytes | about 9 TB |
| File metadata | 500B files Γ 2 KB | about 1 PB (under 0.3% of the data) |
| Download bandwidth (average) | 2 Γ upload = 400 TB/day Γ· 86,400 Γ 8 | about 37 Gbps |
| Sync connections | 100M users Γ 2 devices Γ 50% | 100M, about 1,000 servers at 100k each |
| Method | Path | Request | Response | Notes |
|---|---|---|---|---|
| POST | /v1/uploads | { path, size, chunks: [{ hash, size }] } | 201 { upload_id, missing: [hash], put_urls } | Server answers which chunk hashes it does not have. Known chunks are skipped. Idempotent for the same upload_id. |
| PUT | /chunks/{hash} | chunk bytes (checksum header) | 200 | Goes to the block store with a short-lived pre-signed URL. Server checks the bytes hash to {hash}. Safe to retry (same bytes, same name). |
| POST | /v1/uploads/{id}/commit | { base_version } | 200 { file_id, version } or 409 { conflict } | Atomic. Succeeds only if every chunk exists and base_version is still current. 409 triggers a conflicted copy. |
| GET | /v1/files/{id}/content?version= | none | 200 { chunks: [{ hash, url }] } | Returns pre-signed block URLs. The client fetches chunks in parallel and joins them. Range reads for resume. |
| GET | /v1/changes?cursor=&ns= | none | 200 { entries, next_cursor, has_more } | The sync feed. Returns changes after the cursor for a namespace, in order. Page size is capped. |
| POST | /v1/shares | { ns_or_file, user, role } | 201 | Adds a member with role viewer or editor. Revoking is a DELETE that also invalidates cached grants. |
| Table | Key columns | Notes |
|---|---|---|
| namespace | ns_id, owner, type (user | shared), journal_cursor | Unit of sharding and of sync. A shared folder is its own namespace. |
| file | file_id, ns_id, parent_id, name, is_folder, deleted, latest_version | The tree. Move and rename change only parent_id and name. |
| file_version | file_id, version, size, chunk_hashes (ordered list), author, created_at | A version is a list of hashes. Old versions are kept for 30 days. |
| journal | ns_id, cursor (increasing), file_id, op, version | Append-only change log per namespace. This is what devices read. |
| acl | ns_id, user_id, role | Who can view or edit a namespace. |
| device_state | device_id, ns_id, last_cursor | Where each device is up to (also kept on the client). |
| Block store | Key | Value |
|---|---|---|
| chunk | SHA-256 of the bytes | The bytes (kept in object storage) |
| chunk_index | hash | location, size, reference count, created_at |
POST /v1/uploads/u_91/commit { "base_version": 7 }
200 { "file_id": "f_55", "version": 8 }
journal for namespace ns_12:
cursor 1041 op=update file=f_55 version=8
cursor 1042 op=create file=f_60 version=1
device pulls: GET /v1/changes?cursor=1040&ns=ns_12
-> entries 1041, 1042, next_cursor=1042| Component | What it does |
|---|---|
| Client sync engine | Watches the folder, cuts changed files into chunks, hashes them, uploads missing chunks, and keeps a local database of what it has synced. |
| Metadata service and database | Stores the folder tree, the versions and the ACLs. Does commits in a transaction. Sharded by namespace id. |
| Journal | An ordered, append-only list of changes per namespace, each with a growing cursor. The source of truth for sync. |
| Block service | Tells the client which chunks are missing, and hands out short-lived pre-signed URLs to the block store. |
| Chunk index and object storage | The index maps hash to location and reference count. Object storage holds the chunk bytes with erasure coding. |
| Notification service | Holds a long-poll or WebSocket connection per device and sends a small βnamespace changedβ hint. It does not carry data. |
| Garbage collector | Finds chunks that no file version needs any more, and deletes them after a grace period. |
| Sharing and ACL service | Checks who may view or edit a namespace on every metadata request, and on every URL it signs. |
The problem: A 10 GB file edited by a few bytes must not be uploaded again in full. The same file owned by a million people should not be stored a million times.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Whole files | Hash the file. Upload it if the hash is new. | Simplest. Dedup of exact copies. | One changed byte re-uploads the whole file. No resume. A 10 GB upload that fails starts over. |
| Fixed-size chunks (for example 4 MB) | Cut at fixed offsets and hash each chunk. | Simple and fast. Resumable. Great for appends and in-place edits. | An insert near the start shifts every later chunk, so all of them hash differently and are re-uploaded. |
| Content-defined chunking | A rolling hash scans the bytes and cuts where the hash matches a pattern (with a minimum and maximum size). | Cut points follow the content, so an insert changes only the chunk it lands in. | More CPU on the client. Chunk sizes vary. More code to get right. |
| Delta sync (rsync style) | Compare the old and new versions with rolling checksums and send only the differences. | Smallest uploads, even inside a chunk. | Needs the old version on both sides, and is heavy. Used only in addition to chunking. |
Content-defined chunks keep an edit local. The visualizer below shows it: with a 160 MB file, inserting 1 MB at the start uploads 161 MB with fixed chunks (every boundary shifts) but only 4 MB with content-defined chunks. Appending to the end is the one case where fixed chunks win (1 MB against 4 MB), which is why fixed-size is fine for logs and media.
Naming each chunk by its hash gives us dedup for free. Before uploading, the client sends the hash list and the server says which ones it has. The same chunk is stored once, with a reference count of how many file versions use it. Systems like Dropbox have described using blocks of about 4 MB named by SHA-256. See Compression and Deduplication and Checksums.
| Edit to a 160 MB file | Fixed 4 MB chunks upload | Content-defined chunks upload |
|---|---|---|
| Add 1 MB at the end | 1 MB | 4 MB |
| Change 1 MB in the middle (in place) | 4 MB | 5 MB |
| Insert 1 MB in the middle | 85 MB | 6 MB |
| Insert 1 MB at the start | 161 MB | 4 MB |
The problem: Many devices change the same files at any time. Each device must find out what changed, in order, without missing anything and without re-reading the whole tree. And a commit must never point to chunks that are not there.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Poll the whole tree | Each device fetches the full folder tree every few seconds and diffs it. | Trivial to build. | Far too heavy at 100M devices. Slow to notice changes. |
| Per-file timestamps | Ask for files modified since a time. | Simple query. | Clocks differ between machines, and two changes in the same millisecond can be missed. |
| A change journal with a cursor | Every commit appends an entry with the next number. A device remembers its last number and asks for everything after it. | Ordered, exact, cheap, easy to resume. No clocks. | The journal must be ordered per namespace, and old entries need compaction. |
| Merkle tree of folders | Each folder has a hash of its children. Compare hashes down the tree to find what differs. | Good for repairing a device that is badly out of sync. | More work to keep up to date. Use it as a fallback, not the main path. |
Each namespace has an append-only journal. A commit adds an entry with the next cursor number, inside the same transaction that writes the version, so the journal never disagrees with the data. A device keeps its last cursor, calls GET /changes?cursor=N, applies the entries in order, and saves the new cursor. A device that was off for a week just asks from its old cursor. A device that lost its state does a full listing and starts again.
To avoid polling, the notification service keeps a long-poll or WebSocket connection per device (see Long Polling and WebSockets). When a commit lands, a queue event wakes the right connections. The message carries no data, only "namespace 12 changed", so it is tiny, and a lost message is harmless: the device also checks every few minutes. About 7,000 pings a second on average is easy.
1. Upload all chunks (they exist but nothing refers to them yet)
2. POST commit { base_version: 7 }
BEGIN TRANSACTION
check every chunk hash exists in the chunk index
check file.latest_version == 7 -- else 409 conflict
insert file_version 8 (ordered hash list)
increment refcount for each hash
update file.latest_version = 8
append journal entry (cursor 1041)
COMMIT
3. publish "ns_12 changed" (after commit, at least once)The problem: A laptop and a phone both change the same file while offline, both starting from version 3. When they come back, the server has two different version 4s.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Last writer wins | Accept whichever save arrives last and overwrite. | Simple. No conflicts ever shown. | Silently throws away one person's work. The worst thing a storage product can do. |
| Reject the second save | Return an error and make the user fetch, merge and retry. | Nothing is lost. | Users on a flaky connection are stuck. Bad experience for a background sync client. |
| Keep both (conflicted copy) | Compare base_version with the current version. If different, store the second as a separate file such as βplan (Anna's conflicted copy).txtβ. | Never loses work. No merging logic. Works for any file type. | The user has to merge by hand, and conflict files can pile up. |
| Automatic merge (OT or CRDT) | Merge the two edits inside the document model. | Smooth for text and shared docs. | Needs to understand the file format. Only for native documents. See CRDTs and Operational Transformation. |
Every commit says "I changed version 7". If the file is still at 7, it becomes 8. If it is already at 8, someone else got there first, so the server does not overwrite: it stores this save as a conflicted copy in the same folder and tells both devices. That is exactly the "keep both" policy in the visualizer: no edit is hidden. The user sees two files and merges.
Plain files have no merge rules the server can trust, so the safe choice is to keep both. Only for files we understand (such as our own documents) would we use OT or CRDTs. Both versions also stay in the 30-day history, so even last-writer-wins would be recoverable, but users should not have to know that.
| Case | What the server does |
|---|---|
| Edit vs edit (same base version) | First commit wins. The second becomes a conflicted copy. |
| Edit vs delete | Keep the edited file and cancel the delete (or restore it), so the edit survives. |
| Two renames or moves of one file | The first wins. The second is applied to the new location only if it still makes sense, otherwise it is dropped and reported. |
| Move folder A into B while B moves into A | Moves are checked for loops. The second is rejected, because a folder cannot be inside itself. |
| Two new files with the same name | The second is renamed (βreport (1).pdfβ). |
The problem: There are about 500 billion files, and chunks are shared by many versions and users. The metadata must scale, hot shared folders must not melt a shard, and deleting a chunk must never break a file or race with a new upload.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Shard metadata by user id | All of a user's files live on one shard. | Simple. Most queries stay on one shard. | A shared folder spans users, so shared data lives on several shards. Cross-shard transactions are painful. |
| Shard by namespace id | A namespace (a user root or a shared folder) is the unit. Everything inside it lives on one shard. | A commit and its journal are one local transaction. Sharing means sharing a namespace. | A very busy shared folder is one hot shard. Moving a file between namespaces is a cross-shard move. |
| Delete chunks immediately when the count reaches zero | Decrement on delete. At zero, remove at once. | Frees space fast. | Races with a concurrent upload or dedup hit that is about to use the chunk. A bug here loses user data. |
| Grace period plus periodic mark-and-sweep | At zero, mark the chunk as a candidate. Delete only after, say, 7 days, and double-check against real references. | Safe against races and counting bugs. Cheap to reason about. | Disk is freed later. Needs a background job. |
A namespace is the natural unit: a commit, its version rows, and its journal entry all sit on one shard, so the commit is a single-shard transaction. A shared folder is simply a namespace with several members. Very hot namespaces can get their own shard, and the placement table is kept in a small routing service. See Sharding and Shard Keys, Hot Shards and Resharding.
For chunks, reference counts are fast but can drift, and a dedup hit can arrive just as the count hits zero. So reaching zero only marks the chunk. It is deleted after a grace period, and only if a full mark-and-sweep (walk every live version and collect the hashes it uses) still finds no reference. A dedup hit or upload also "touches" the chunk, which resets its timer. Cost: some dead data lives a week longer. Benefit: we never delete a chunk a live file needs.
| Data | Where it lives | Lifecycle |
|---|---|---|
| Current version chunks | Hot object storage, erasure coded | Kept while the file exists |
| Old versions (up to 30 days) | Same, then colder storage after a few days | Dropped after retention, if no other version uses the chunk |
| Deleted files (undelete window) | Hidden in metadata, chunks kept | Purged after 30 days |
| Unreferenced chunks (failed uploads) | Object storage, refcount 0 | Deleted after the grace period |
Both devices start from version 3: βQ3 plan: ship v2β. Device A adds β+ budgetβ and device B adds β+ risksβ, both while offline. Then they come back online. Who saves first, and what the server does about the second save, decides what you keep.
A simulated model with hard-coded chunk sizes (a 160 MB file) and no real hashing. Real clients cut chunks with a rolling hash (for example Rabin or Gear fingerprints) and name each chunk by its SHA-256. The sizes, the 1 MB edit and the file names are illustrative.
| Bottleneck | Fix |
|---|---|
| A hot shared namespace (a company-wide folder) | Give it its own shard, batch journal writes, and send one hint per connection, not one per change. Page the changes feed. |
| Upload bandwidth through the API tier | Never carry file bytes there. Pre-signed URLs let clients write straight to the block store, which scales as object storage does. |
| Chunk index lookups (175 billion chunks) | Shard the index by hash prefix. Cache hot hashes. Use a Bloom filter to answer βdefinitely not storedβ without a lookup. |
| Many small files (thousands of 1 KB files) | Batch them into one commit and one upload request. Pack tiny files into a bundle chunk, so that overhead does not dominate. |
| Slow and mobile networks | Resumable chunk uploads, parallel streams on good links, throttling, and metered-data and battery rules on phones. |
| Notification fan-out for large shares | Fan out in a queue-driven worker pool. Coalesce several changes in a short window into one hint. |
| Download hot spots (a popular shared file) | Put a CDN in front of the block store for public links, with signed, expiring URLs. |
| Failure | How the design copes |
|---|---|
| A chunk upload fails halfway | Retry the chunk. Same bytes, same hash, so the put is idempotent. The upload session lets the client ask which chunks already arrived. |
| The client dies after uploading chunks but before commit | Nothing is visible. The chunks are unreferenced and are removed by the garbage collector. The client resumes from the session. |
| Commit succeeds but the response is lost | The client retries the commit with the same upload id. It is idempotent and returns the same version. |
| A metadata shard is down | Replicas take over (leader failover). Writes to that shard's namespaces pause briefly. Clients keep working offline and sync later. |
| A zone or storage node is lost | Erasure coding rebuilds missing pieces from the others across zones. Reads keep working from the surviving pieces. |
| Notification service is down | Devices fall back to polling the changes feed every minute or so. Sync is slower, but correct, because the journal is the truth. |
Files are cut into content-defined chunks named by SHA-256. The client uploads only missing chunks straight to object storage, then commits a version (an ordered list of hashes) in one transaction that also appends to a per-namespace journal. Other devices are pinged, and pull the journal from their cursor. Conflicts become conflicted copies. Metadata is sharded by namespace, and unreferenced chunks are removed after a grace period.
| Decision | What we gain | What it costs |
|---|---|---|
| Chunking with dedup | Small edits upload small amounts. Identical data is stored once. | Client CPU, more metadata, and a dedup side-channel to manage. |
| Content-defined over fixed chunks | Inserts change one chunk instead of all later ones. | More complex client code and variable chunk sizes. |
| Journal with a cursor, plus a push hint | Exact, ordered, resumable sync with little polling. | A journal per namespace to keep ordered and compact. |
| Conflicted copies instead of auto-merge | Work is never lost, and it works for any file type. | The user merges by hand, and copies pile up. |
| Shard metadata by namespace | A commit is a single-shard transaction. Sharing is simple. | Hot shared folders, and cross-namespace moves are heavier. |
| Grace period before deleting chunks | No deletion races, and no lost data. | Storage freed a week later. |
The core of the question. Be precise about why each piece exists.
What goes where, how big it gets, and how it is cleaned up.
Where interviewers test whether you protect user data.
The follow-ups that change the problem. Answer calmly, and say what changes.
A change in requirements is a test of whether you understand why your design looks the way it does.
| New requirement | What changes in the design |
|---|---|
| Real-time co-editing of documents | Add a collaboration service with WebSocket sessions and OT or a CRDT for our own document types. Periodically snapshot to a normal file version. |
| End-to-end encryption | Chunk and encrypt on the client with per-user keys. Cross-user dedup is lost, and server-side search and previews stop working. Key recovery becomes a product problem. |
| Full-text search inside files | An indexing pipeline reads new versions from the journal, extracts text, and writes an inverted index. Respect ACLs at query time. |
| Files up to 1 TB (video, backups) | Larger chunks, many parallel streams, and chunk-level resumable sessions. The hash list is large, so store it in pages. |
| Strict compliance (retention and legal hold) | Per-namespace retention rules that override garbage collection, write-once storage for held data, and audit logs for every access. |
| Mostly photos and videos | Add thumbnail and transcoding jobs, a CDN for viewing, and larger fixed chunks, since media rarely gets small in-place edits. |
| 10Γ more users, most inactive | Tier inactive accounts to cold storage, keep metadata hot, and make cold reads slower but still correct. |
| A small company needs on-premises storage | Same logical design with a local block store and metadata database, and replication to the cloud as a backup. |
| Area | Weak | Good | Great |
|---|---|---|---|
| Requirements | Starts drawing servers. Never asks about file size, devices or conflicts. | Asks about file size, devices, sharing, versions and offline. Rules out co-editing. | Also raises encryption and dedup, conflict policy and retention, and states the scope back. |
| Estimation | No numbers, or counts only requests. | Computes storage, commit rate and upload bandwidth. | Sees that bytes dominate, concludes that file data must bypass the API tier, and sizes the notification connections. |
| Core idea | Stores whole files in one database. | Chunks files, separates metadata from blocks, uses object storage. | Explains chunk hashing, dedup, delta sync, reference counting and why each exists. |
| Sync and conflicts | Says βpoll for changesβ and βlast write winsβ. | Uses a change journal with a cursor and a base version for conflicts. | Adds the atomic commit order, idempotent retries, move and delete conflicts, and conflicted copies. |
| Storage lifecycle | Never mentions deleting chunks. | Mentions reference counts and garbage collection. | Explains the deletion race, the grace period, mark-and-sweep, and tiering. |
| Communication | Lists components with no reason. | Follows the steps and explains choices. | States the trade-off for each choice, such as dedup privacy and manual merges. |
| Mistake | Do this instead |
|---|---|
| Sending file bytes through the API servers | Use pre-signed URLs so clients upload straight to the block store. The API tier only carries small metadata calls. |
| Storing whole files and re-uploading on any change | Chunk files, name chunks by hash, and upload only the missing ones. |
| Last-writer-wins for conflicts | Use a base version on every commit and keep both versions as a conflicted copy. |
| Writing the version before the chunks exist | Chunks first, then one atomic commit. A failed upload then leaves only orphan chunks. |
| Deleting a chunk the moment its count reaches zero | Mark it, wait a grace period, confirm with mark-and-sweep, and touch it on every dedup hit. |
| Using timestamps to find changes | Use a journal with an increasing cursor per namespace. Clocks differ and can tie. |
| Sharding metadata by user id | Shard by namespace id so a commit to a shared folder is one single-shard transaction. |
| Promising dedup with no mention of privacy or encryption | Say that βalready storedβ leaks existence, and that end-to-end encryption removes cross-user dedup. |
Where the chunks live, with erasure coding and tiers.
Why identical chunks are stored once.
A way to find which folders or chunks differ quickly.
Resumable, chunked, pre-signed uploads.
How a device waits for a change hint cheaply.
Durability at 1.5Γ instead of 3Γ.
Why we shard by namespace and what a hot shard looks like.
Moving old versions to cheaper storage.