Design a file sync service
Read first: Object storage, Replication, Partitioning and sharding
A synced file is a metadata row plus immutable chunks in object storage. Clients upload only the chunks the account does not already have, and a commit is a compare-and-swap on the file version. Two devices that edit the same version offline both keep their bytes, and one of them does not silently win.
A file the user cares about is two different objects that people keep trying to store as one. The small one says the name, the parent folder, and which version this is. The large one is the bytes. Sync is the protocol that moves other devices onto the new version. It is not a remote disk, and it does not become one because you miss POSIX.
Requirements
The user has two or more devices and wants the same folders on each. Sometimes they are offline. Sometimes they share a folder with another person.
It must:
- Upload a file, including one that is larger than a request should be, and resume after a dropped connection.
- Show that file on the other devices, including a device that was offline at the time.
- Keep every byte the user wrote when two devices edit during a disconnect. Losing one edit without a trace is the bug.
- Share a folder with another account, with the same conflict rule.
Non-goals:
- POSIX. No open file descriptor on the server, no byte-range lock, no partial-write visibility, no directory that is also a mount a kernel can mmap. Object storage is immutable blobs and a metadata service that maps a key to where the bytes are. Overwrite is a new object and a pointer swing.
- Real-time co-editing of a document. That is a different product. The server-ordered, per-property design in the Figma story fits a structured canvas with clients that are online. It is the wrong promise for two laptops that each saved a whole file while disconnected.
- Video delivery. Once a file is synced, downloading it to a device is a chunk fetch, not a CDN problem. You can put a cache in front later. It is not the hard part.
Assumption on the conflict product: for opaque bytes you do not merge. A photo, a zip, and a spreadsheet do not have a character-level merge you can stand behind. Both versions survive. The user picks.
Estimation
Assumptions:
- 10 million accounts.
- Two devices each, so 20 million clients.
- Each account stores 5 GB. Decimal units below: 1 GB is 1e9 bytes.
- Average file is 500 KB, so an account holds about 10,000 files. Metadata row is 200 bytes.
- Each account changes 50 MB on a typical day.
- 40 percent of those changed bytes are chunks the account does not already have. The rest dedup and are not rewritten. This 40 percent is an assumption.
- Chunk size is 4 MB, meaning 4e6 bytes, except the last chunk.
- A naive client polls every 30 seconds. You will throw that number out and replace it. Compute it first so you know why.
- Peak is 3 times average, inside the 2x to 5x band.
- Object replication factor is 3.
stored user bytes = 10e6 * 5e9 = 5e16 bytes = 50 PB
metadata = 10e6 * 10,000 * 200 = 2e13 bytes = 20 TB
daily changed bytes = 10e6 * 50e6 = 5e14 bytes = 500 TB per day
average change rate = 5e14 / 86,400 = 5.8e9 bytes/s = 5.8 GB/s
shortcut / 1e5 = 5.0 GB/s, low by about 14 percent
new object writes = 0.40 * 5.8 GB/s = 2.3 GB/s average
peak new writes, 3x = about 7 GB/s
mutations per day = 10e6 * 20 files = 200e6
commit QPS, average = 200e6 / 86,400 = about 2,300
peak commits, 3x = about 7,000
naive polls = 20e6 devices / 30 seconds = about 670,000 QPS
A million requests a day is about 12 per second. The naive poll is the thing that looks like a scale problem, and it is self-inflicted. The bytes are the storage bill: 50 PB before you take out cross-chunk duplicates inside an account, times 3 replicas if every chunk is stored three times. Dedup inside the account cuts the 50 PB by whatever fraction of chunks are identical. You do not get to claim a global dedup ratio you have not measured. Within one account, identical chunks are addressed by hash, so the 5 GB already counts unique chunks if the client is honest. The 50 PB is then the unique-within-account total, and cross-account duplication is extra copies you accepted on purpose.
Twenty terabytes of metadata, partitioned, is a database. Fifty petabytes of bytes are not. That split is the design.
Foreground connections, as the replacement for the poll. Assumption: 10 percent of devices are active and hold a long-lived connection, 2 million sockets. The rest sync when they open the app, from a stored cursor, and do not poll on a timer while asleep. Two million connections are a gateway fleet. The metadata commit does not fan out inside the database transaction.
High-level design
flowchart LR
laptop[Laptop]
phone[Phone]
meta[Metadata database]
chunks[Content addressed chunks]
clog[Change log]
gate[Connection gateways]
laptop --> chunks
phone --> chunks
laptop --> meta
phone --> meta
meta --> clog
clog --> gate
gate --> phone
gate --> laptop
The client splits a file into chunks, hashes each one, and asks the metadata service which hashes are already stored for this account. It uploads the missing chunks, then commits a new version: an ordered list of hashes, the size, the name, and the parent. The commit is a compare-and-swap on the file’s version.
Other devices learn about the commit from the change log, either pushed if they are connected or pulled the next time they open. They download the hashes they do not have. The notification is a hint. The cursor is the truth.
Deep dive
Chunks, hashes, and the pointer
A content hash is the address of a chunk. Uploading the same hash twice is the same PUT. That is what makes the upload idempotent. Checksums belong on the bytes. If the stored checksum disagrees, the PUT fails and the client sends the chunk again. A large file uses multipart upload because one PUT of a huge object is a good way to start over from byte zero.
Order of durability: the chunk is durable first, then the metadata commit points at it. If you commit the pointer first, another device syncs, fetches the hash, and gets nothing. That is the durability bug. Orphan chunks, from a client that uploaded and never committed, are harmless and collectable. A garbage pass deletes hashes no metadata row references. Run it lazily. A wrong garbage pass is data loss, so the pass only deletes hashes that have been unreferenced for a grace period. Assumption: 7 days.
Dedup follows the hash, inside an account and inside a shared folder that uses that account’s keys. Two strangers with the same photo do not share a chunk. Cross-account dedup fights per-user encryption: if each account encrypts with its own key, identical plaintext is different ciphertext and the hashes do not match. Convergent encryption would make them match and would also tell the server who shares which bytes. This design does not do that. Say the non-goal. Shared folders dedup because the participants read the same chunks.
A small edit of a large file is the payoff. A 20 GB file is 20e9 / 4e6 = 5,000 chunks. The user changes 8 MB, which touches two chunks. The client uploads two chunks and commits a new list where 4,998 hashes are unchanged. You did not rewrite 20 GB. You also did not implement a binary diff format. The chunk size is the diff. Smaller chunks dedup more and cost more metadata. Larger chunks do the reverse. Four megabytes is a choice, not a law. If the interviewer pushes, offer 8 MB and show that the 20 GB file becomes 2,500 chunks and an 8 MB edit might be one chunk or two depending on alignment.
The metadata row holds the ordered list of hashes, or it holds a pointer to a manifest object when the list itself is large. A 5,000-hash list at 32 bytes is 160 KB. That can live in the row for a while. A million-chunk object should not. Past a threshold you store the manifest as an object and the row stores the manifest hash. Same pointer swing.
The commit and the conflict
Each file version has an integer. The client read version 7, edited, and now wants version 8. The write is: update this file to version 8 and this hash list, only if the current version is still 7. One transaction. One winner.
The loser still has bytes, already uploaded, addressed by hash. Nothing is discarded. The server keeps the loser’s list as a second file version attached to the same parent, with a generated name the user can see, and records a conflict on the change log. Both devices pull both versions. The user deletes one, or keeps both. You do not pick a winner by timestamp. Clocks on two laptops are a bad judge of which edit the user wanted, and the clocks page is why a timestamp is not a substitute for an order someone defined.
If both devices are online, the second save sees version 8 already and can reload before the user does more work. The ugly case is offline. Laptop and phone both started from version 7, both commit later, one CAS wins, the other becomes the conflict copy. That is the whole story. Spell it as a timeline if the interviewer looks unconvinced. Empty “we use CRDTs” is a different system, and it is the aside at the bottom, not the answer.
Sharing does not change the rule. Two people in a folder are two clients of one namespace. The version is on the file, not on the device.
Sync, cursors, and the poll you will not build
The metadata primary assigns a monotonic change id when a commit lands. Each device stores the last change id it applied. Sync is “send everything after this id, up to a page.” The device applies the page, moves the cursor, and asks again if the page was full. A device that has been gone longer than the log’s retention does a snapshot compare: list the namespace, hash by hash, and repair. Assumption: the log is retained 30 days. State the number. A cursor without a retention bound is a promise you will regret.
Replication of that metadata: the client that just committed must see its write. Read-your-writes means that device reads the primary, or sends the version it was given and retries if a replica is behind. Other devices can lag by a second. Asynchronous replication loses the tail if the primary dies before the replica catches up. For an ack you already showed the user, that tail is a lost file. Ack the commit only after the metadata transaction is durable on a majority of replicas, and accept that a slow replica stalls the save. That is the synchronous-replication trade, and it is the right one for the pointer. The chunk store has its own durability, which you already waited for before the commit.
Push is best-effort through the gateways. A gateway holds the socket, so it is stateful, and the next event for that device wants the same gateway or a backplane. If the gateway dies, the client reconnects, presents the cursor, and catches up. You do not keep session state as the only copy of the change. The log is the copy.
Partitioning the metadata by account id keeps one user’s tree on one shard, so a listing is local. It also means one huge company is one hot partition. Adding shards does not move them if the key is still the account id. When a tenant is actually hot, partition that tenant’s files by folder, and pay for a scatter when you list the whole account. Do that when the measurement says so, not in the first diagram.
The 670,000 polls are why the cursor is cheap and why idle devices do not ask. An empty poll is still a request, still a connection, still a chance to stampede when the fleet restarts and every client polls at once. Jitter the reconnects. A queue without a bound, on the change log side, is how a gateway falls behind and then retries itself to death. Cap the push and let the cursor heal.
Tradeoffs
| Choice | What you gain | What you spend |
|---|---|---|
| Bytes in object storage, tree in a database | You can list and authorize without touching 50 PB, and you can PUT a chunk without a schema migration | Two systems, and a crash between them leaves an orphan or, if you reorder, a dangling pointer |
| Content-hash chunks, dedup inside the account | Retries are idempotent, and a small edit uploads a few chunks | Cross-account duplicates remain, by choice, and hash metadata grows with the file |
| Compare-and-swap on the version, keep both edits | An offline save is never silently dropped | The user sees a conflict copy, and you did not merge |
| Last write wins by device timestamp | No conflict UI | One edit disappears, and the clock is not an authority |
| Poll every 30 seconds | The protocol fits in a weekend | About 670,000 empty reads a second, and a thundering herd after a blip |
| Cursor plus push to connected devices | Idle clients cost nothing, and a missed push heals | Gateways are stateful, and a dead gateway depends on the cursor being real |
| Ack only after a metadata majority | Failover does not eat a save the user saw succeed | A slow replica stalls the commit |
Failure modes
- Chunk PUT succeeds, commit never arrives. Symptom: storage grows, no device sees the file. Orphans, collected after the grace period. The client retries the commit. The hash list is the same, so the retry is safe.
- Commit succeeds, chunk was never durable. Symptom: the other device syncs and downloads a hole. This is the order bug. Do not publish the pointer first.
- Two offline edits, and the second CAS fails. Symptom if you ignore the failure: the second device retries blindly and either errors forever or overwrites the first edit on a later attempt. Keep the loser’s hashes and emit a conflict. The retry of the loser must be idempotent too: the same client, the same hash list, the same base version, returns the same conflict record rather than a second copy.
- Primary metadata is lost with a tail of async replicas behind. Symptom: a save that was acked is gone. You either acked too early or you accept the loss in the requirements. This product should not accept it.
- Notification bus is down. Symptom: devices update when they next sync from the cursor, not instantly. If the only record of the change was the push, the change is gone. That is why the log is the record.
- One account is a hot partition. Symptom: that tenant’s saves are slow and everyone else on the shard is slow with them. More shards with the same account-id key do nothing. Split the tenant’s key.
- A client retries a chunk upload in a tight loop after a checksum failure. Symptom: it hammers object storage with the same bad bytes. Fail the file after a few attempts and show the error. A retry storm of identical PUTs is idempotent and still eats bandwidth. The estimate of 7 GB/s of peak new writes has no room for a multiplicative retry bug.
- Garbage collection deletes a hash that a racing commit is about to reference. Symptom: a brand-new file with a hole. The grace period and a check that the hash is still unreferenced at delete time are the fence. A GC bug is a durability bug.
In the interview
First five minutes: who is syncing, the split between the row and the chunks, the content hash, the version CAS, and the statement that this is not a POSIX filesystem. Put one number up: 50 PB of bytes against 20 TB of metadata, under the assumptions, and 2,300 commits a second average against the 670,000 polls you refuse to build.
Skip kernel semantics, block-level replication products, and a tour of encryption modes. If they ask about encryption, give the one-sentence consequence: per-user keys make cross-account dedup go away, and you already declined that dedup.
The question that follows is the two offline editors, or the crash between the PUT and the commit. Walk the CAS, say both versions survive, and say the chunk hits disk before the pointer.
Check yourself
A 20 GB file changes by 8 MB. With 4 MB chunks, how much do you upload, and what has to be true for that to work?
The file is 20e9 / 4e6 = 5,000 chunks. Eight megabytes touches two chunks, so you upload those two and commit a new ordered list. This works if the client hashes chunks and the server already has the other 4,998 from the previous version. It is not a byte-range patch inside an object.
Two laptops both edit version 7 while offline. What does the second commit do?
The first compare-and-swap moves the file to version 8. The second does not match version 7, so it does not overwrite. Its chunks are already stored by hash. The server records a conflict copy and both devices sync both versions. A timestamp does not choose a winner.
Why is a 30-second poll from every device a bad design even when each poll is cheap?
Twenty million devices over 30 seconds is about 670,000 requests a second, mostly empty, and they reconverge after an outage. The change log and a cursor let an idle device stay quiet. Push is an optimization for devices that are actually connected. The cursor remains correct when the push is dropped.
You ack the save, then the metadata primary dies before the replica applies the commit. The chunks are safe. What did the user lose, and when should you have acked?
They lost the pointer, which is the file as far as every other device is concerned. Asynchronous replication drops the tail on failover. Ack after the metadata commit is durable on a majority, and only after the chunks it names are durable. A slow replica is the cost.
Based on: Designing Data-Intensive Applications, Kleppmann and Riccomini; Alex Xu, ByteByteGo volumes; Figma multiplayer.