Design File Sync
How a file sync service uploads only changed chunks, keeps file lists consistent, resolves edit conflicts and notifies devices.
On this page
A file sync service keeps a folder identical on all of a user's devices and on the devices of the people the folder is shared with. When a file is saved on one device, the new version appears on the others, and files can be edited offline and synced later.
The question is hard because it combines two systems. One moves large amounts of file data and should never send the same bytes twice. The other stores small metadata records, such as the list of files and their versions, and has to be strictly correct, because a wrong file list can destroy a user's work. The steps below follow A Framework for Any Design.
Clarify the problem
Design a file sync service, like a shared folder that follows you across devices.
Each device has a local folder that is synced through the cloud. Do we need shared folders, version history and offline editing?
Shared folders yes, offline editing yes, and keep 30 days of versions.
How many users are there, how much data does each one store, and how often do files change?
10 million users with about 2 GB and 3 devices each. About 3 million change something on a given day.
Then my priorities are to never lose or silently overwrite a file, never upload bytes the server already has, show changes on other devices within seconds, and keep each folder's changes in one order. I will leave real-time co-editing out, because it is a different product.
- Functional requirements: users can upload, update, delete and move files, changes sync to their other devices, folders can be shared, 30 days of versions are kept, and devices can work offline.
- Non-functional requirements: no acknowledged change is ever lost. Every device sees the changes to a folder in the same order, which is strong consistency per folder. Online devices see changes within about 5 seconds, and only changed parts of a file are uploaded.
- Out of scope: real-time co-editing, search inside files and previews.
Estimate the scale
- Stored data: 10 million users × 2 GB = 2 × 1016 B, which is 20 PB before deduplication and redundancy.
- Changes: assume 3 million active users make 20 saves each, which is 60 million changes a day. Dividing by 86,400 seconds gives about 700 changes a second, and a 3x peak during working hours gives about 2,100 a second.
- Connected devices: 30 million devices, of which 30% online is 9 million waiting for changes.
The server keeps one index row (hash, location, reference count) for each 4 MB chunk. How big is that index?
- 20 PB of stored data
- 4 MB per chunk
- About 100 bytes per index row
Show the working
- 2 × 1016 B ÷ 4 × 106 B = 5 × 109 chunks
- 5 × 109 × 100 B = 5 × 1011 B = 500 GB
Estimate 500 GB (anything from 150 GB to 1.5 TB is a good answer)
The index fits in a sharded database. Smaller chunks find more duplicates but make the index grow in proportion.
Write the calls that save a changed file without re-uploading data the server already has, and describe how another device learns about the change.
Compare with a model answer
The client sends the hashes of the file's chunks, and the server replies with the ones it is missing. The client uploads those and then commits, naming the version it started from. Other devices hold a long poll that says which folder changed, and then ask for changes after their cursor.
Define the API Optional
Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.
POST /v1/commit
body { namespace_id, path, base_rev: 7, commit_id, size, chunks: [sha256, ...] }
200 { rev: 8, journal_seq: 1042 }
412 { missing: [sha256, ...] } upload these first, then retry
409 { current_rev: 8 } someone else changed it since rev 7
PUT /v1/chunks/{sha256} (raw bytes, at most 4 MB)
201 stored 200 already had it 400 hash does not match bytes
GET /v1/chunks/{sha256} -> bytes
GET /v1/changes?namespace_id=N&cursor=1041
200 { entries: [ { path, rev, chunks, deleted } ], cursor: 1042, has_more }
GET /v1/notify?cursors=N:1041,M:88 long poll, up to 60 s
200 { changed: ["N"] } or 204 nothing changed, poll againThe main API decision is that a client uploads chunks before it commits the metadata. A commit succeeds only if every chunk it names is already stored, so a file record never points at bytes that do not exist. If metadata were written first, other devices would be told about a version and would try to download chunks that had not arrived yet. The cost is one extra round trip when the server answers 412.
Both write calls are safe to retry. A chunk is named by its hash, so uploading it twice stores it once. The commit carries a client-chosen commit_id, so if a reply is lost, the retry returns the commit already applied instead of a 409 against the client's own edit.
Sketch the records for folders, files, versions and chunks. How does a device ask what has changed since it last looked?
Compare with a model answer
A version is a list of chunk hashes. Each namespace, meaning a shared folder or a user's root folder, has a numbered journal of changes. A device remembers a cursor, which is the number of the last journal entry it applied, and asks for the entries after it.
Model the data
namespaces: namespace_id PK, owner_id, next_seq BIGINT
files: (namespace_id, path) PK, file_id, latest_rev INT, deleted BOOL
revisions: (file_id, rev) PK, size, chunk_hashes BLOB, -- ordered list
device_id, created_at -- kept 30 days
journal: (namespace_id, seq) PK, file_id, rev, op -- the change log
members: (namespace_id, user_id) PK, role -- sharing
-- sharded by hash
chunks: sha256 PK, blob_key, size, ref_count
-- chunk bytes live in object storage under their sha256A commit has to check the base revision, write a new revision, update the file's latest revision and append a journal entry, and these four steps either all happen or none do. That requires a relational database sharded by namespace, so that every change to one folder lands on one shard and is applied in one order. Chunk bytes go to object storage, and the chunk index is a key-value lookup sharded by hash.
Draw how a save on one device reaches another device, with separate paths for file bytes and for metadata.
Compare with a model answer
Use three services: a block service for chunks, a metadata service for commits and the journal, and a notification service for long polls. A notification only says where to look for changes, so losing one loses no data.
High-level design
request and replyasynchronous message
- base rev
- 7
1The laptop saves the 200 MB
budget.xlsxand hashes its 50 chunks. Only one differs from revision 7.- base rev
- 7
2The laptop commits revision 8 with all 50 hashes. One is not in the chunk index, so the server answers
412.- base rev
- 7
- uploaded
- 4 MB
3The laptop uploads the missing chunk, which is 4 MB instead of 200 MB.
- rev
- 8
- journal seq
- 1042
4The laptop retries. The file is still at revision 7, so one transaction writes revision 8 and journal entry 1042.
- rev
- 8
- journal seq
- 1042
5A feed reads the journal and queues a change event. Events come from the journal, so a crash cannot skip one.
- phone cursor
- 1041
6The phone's long poll, which carries cursor 1041, is answered with a message that this folder changed, and no file data.
- phone cursor
- 1042
- downloaded
- 4 MB
7The phone asks for the changes after 1041, receives revision 8 with its 50 hashes, downloads the one chunk it lacks and rebuilds the file.
- rev
- 8
8Meanwhile the desktop edited the same file offline, starting from revision 7. Its commit names base revision 7, but the file is at revision 8, so the server answers
409.- phone cursor
- 1042
9If the notification service is down, devices fall back to asking for changes every minute. Changes arrive later, but none is missed.
Deep dives
Chunking and content hashing
Uploading a whole file every time it changes wastes bandwidth, so the client splits each file into chunks and names every chunk by a cryptographic hash of its bytes, such as SHA-256. Two chunks with the same hash have the same bytes for every practical purpose, so the server stores each distinct chunk once. This gives delta sync, because only chunks whose hash changed are uploaded. It gives deduplication, because a chunk shared by two files or two versions is stored once. It also makes retries safe, because uploading a chunk a second time changes nothing.
The remaining question is where to cut the file. With whole-file hashing there is one hash per file. A one-byte change to a 200 MB file uploads all 200 MB, so it is only acceptable for small files.
With fixed-size chunks, for example 4 MB, the file is cut at every 4 MB offset. An edit that changes bytes in place alters one chunk, so a small edit uploads only 4 MB of a 200 MB file. The weakness is an insertion. If a paragraph is inserted near the start of a document, every byte after it moves by the same amount, every later chunk boundary lands on different bytes, and every later chunk gets a new hash, so almost the whole file is uploaded again.
With content-defined chunking the client slides a small window, say 48 bytes, over the file and computes a rolling hash of the bytes in it. It cuts the file wherever the low 22 bits of that hash are zero, which happens on average once every 222 ≈ 4.2 million bytes, so chunks average about 4 MB. A cut depends only on nearby bytes, so an insertion changes only the chunks around it and later boundaries stay where they were. The cost is that chunk sizes vary, so it needs a minimum and a maximum size.
| Option | Good at | Bad at | Pick it when |
|---|---|---|---|
| Whole file | It is the simplest approach, with one hash per file. | A one-byte change uploads the entire 200 MB file again. | Use it only for files smaller than one chunk. |
| Fixed 4 MB chunks Usual default | It is easy to compute, and an edit in place changes only one chunk. | An insertion near the start shifts every later boundary, so every later chunk gets a new hash. | Use it for files that are edited in place, such as disk images. It is a good first answer. |
| Content-defined chunks | Boundaries follow the content, so an insertion changes only the chunks around it. | Chunk sizes vary, and it needs a rolling hash with a minimum and a maximum chunk size. | Use it for documents where text is inserted in the middle. It is the next step up from fixed chunks. |
The metadata service and consistency
Chunks can be eventually consistent, because a chunk either exists or does not and never changes. The file list cannot be. If a device applied "rename A to B" before "create A", it would end up with the wrong folder contents. For this reason each change receives the next journal sequence number in the same transaction that changes the file record, and every device applies the journal entries in sequence order.
Within one namespace, every device then sees the same changes in the same order, and never sees a revision whose chunks are not stored. Changes in different namespaces are not ordered relative to each other, so a normal save never needs a transaction across shards. A very large shared folder lives on a single shard, which then needs to be dedicated to it.
Failover needs care. If the metadata primary fails, promote only a replica that has every committed transaction, which means a synchronous replica or a database that uses consensus. An asynchronous replica that is behind could lose a commit a phone has already applied. See replication.
Conflicts
A conflict happens when two devices change the same file from the same starting revision, usually because one of them was offline. The server detects it with optimistic concurrency. Every commit names the base_rev it started from, and the server accepts the commit only if that is still the latest revision. The device that commits second receives 409, and the system then has to decide what to do with its version.
Last writer wins keeps whichever version arrived last and discards the other. It needs no user interaction, but it silently destroys someone's work, depending only on whose upload finished first. Conflicted copy keeps both. The losing device uploads its version under a new name, such as budget (Desktop's conflicted copy).xlsx, and both files appear on every device, so the user can merge them by hand. It is the usual default for files the server cannot parse. Automatic merge combines the two edits when they touch different parts of the file. It works only for formats the server can parse, such as plain text, and a faulty merge corrupts the file.
Deletes can conflict too. If one device deletes a file that another device edited from the same revision, the usual rule is to keep the edit and restore the file.
Notifying other devices
A device has to find out quickly that another device changed a folder. With plain polling, 9 million online devices asking every 5 seconds would send 9 million ÷ 5 = 1.8 million requests a second, almost all of them answered with nothing new.
Long polling avoids this cost. Each device keeps one request open that lists its namespaces and cursors, and the notification service answers it as soon as one of those namespaces changes, or after 60 seconds if nothing does. With 9 million devices that is about 9 million ÷ 60 = 150,000 empty answers a second, and changes still arrive within seconds. A WebSocket per device works similarly, as realtime communication explains.
The notification only says that namespace N changed. It never carries file data, because a dropped data message would be a missed change and an offline device would have nothing to replay. If a hint is lost, nothing is harmed, because the device's next poll sends its cursors and the service answers immediately if any of them is behind. For this reason the notification path can be fast and best-effort, while the journal stays strict.
Bottlenecks and failures
At 10x the scale there are 200 PB of data, about 21,000 commits a second at peak and 90 million online devices.
- The chunk store grows by adding object storage nodes, and the metadata database adds shards, with the busiest namespaces getting shards of their own.
- Storage is the largest cost. Use erasure coding instead of three full copies, and when a version is older than 30 days, delete it and decrement its chunks' reference counts so they can be collected.
| Component that fails | What happens | What you do |
|---|---|---|
| A block service server | Uploads and downloads that were using it fail. | Clients retry on another server, which is safe because uploads are identical when repeated with the same hash. |
| A metadata shard primary | Commits for the namespaces on that shard fail until failover finishes. | Fail over to a synchronous replica. Retried commits reuse their commit_id, so each one is applied once. |
| The notification service | Devices hear about changes late. | Devices fall back to polling every minute, and no change is lost because the journal is unaffected. |
| A device in the middle of an upload | Some chunks are stored but no file refers to them yet. | Garbage collection deletes unreferenced chunks after a grace period. The grace period stops it from deleting a chunk that a commit is about to use. |
What a strong answer sounds like
| Level | What the answer does |
|---|---|
| Junior | The answer uploads whole files and polls. |
| Mid-level | The answer uses hashed chunks for delta sync and keeps metadata separate from file bytes. |
| Senior | The answer commits metadata only after the chunks exist, keeps an ordered journal per namespace with a cursor on each device, resolves conflicts with base revisions and conflicted copies, treats notifications as hints, and explains why fixed-size chunks fail on insertions. |
Why not just keep whichever version arrived last?
That would silently destroy someone's work, and which edit survives would depend only on whose upload finished first. Instead every commit names its base revision. If that revision is no longer the latest, the server returns 409 and the client saves its version as a conflicted copy. Merging by hand is annoying, but nothing is lost.
Follow-up questions
How do you restore a file to last week's version?
The server commits a new revision whose chunk list is the one from last week. No file data moves, because those chunks are still stored, and other devices pick it up like any other change.
How do you sync a folder with 100,000 files to a new device?
The new device requests a snapshot of the file list with the journal cursor at which it was taken, instead of replaying every journal entry. It then downloads chunks in parallel, starting with the newest or smallest files. It then follows the journal from that cursor, so changes made during the download are not missed.
How does sharing work?
A shared folder is its own namespace with its own journal and a members table. The metadata service checks the caller's role on every commit, and each member's devices add the namespace to their long poll.
How do you handle renaming or moving a folder with thousands of files?
A rename or move is a metadata change and moves no file data, because chunks are named by content and not by path. The client commits the new paths in one transaction, so no chunk is uploaded again.
Can you encrypt files so the server cannot read them?
Yes, by encrypting the chunks on the device before upload. The cost is that identical files from different users no longer produce identical chunks, so cross-user deduplication stops working. Chunk names must also be keyed hashes, or anyone holding a file could confirm that it is stored.
After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".