Design a File Sync Service
A file sync service keeps a folder identical across a user's laptop, phone and the cloud, and across everyone the folder is shared with. This lesson designs one: files split into content-addressed blocks so only changes are uploaded, a strongly consistent metadata service with a per-user change journal, push notifications to tell devices to sync, and clear rules for conflicts.
What you will learn
- Separate file content (blocks in object storage) from file metadata (a consistent database).
- Split files into blocks named by their hash: dedupe and resumable uploads come for free.
- Upload only the blocks that changed; commit the new file version in one metadata transaction.
- Each user has an ordered change journal; devices sync by asking for changes after a cursor.
- Notify devices over a long-lived connection, then let them pull; never push the data itself.
- On conflicting edits, keep both copies and let the user decide.
In this lesson
- The question
- Step 1: Clarify the requirements
- Step 2: Back-of-the-envelope estimates
- Step 3: Splitting files into blocks
- Step 4: The API
- Step 5: The high-level design
- Step 6: Uploading a change
- Step 7: The metadata service and the journal
- Step 8: Telling devices to sync
- Step 9: Applying changes on a device
- Step 10: Conflicts
- Step 11: Versions, deletes and sharing
- Step 12: Scaling and failures
- Step 13: The follow-up questions
- Recap
The question
Welcome to lesson twelve of the InterviewDryRun system design course. Today we design a file sync service: a folder on your computer that is magically the same on your other computer, your phone, and on the web, and that you can share with other people.
It is a great interview question because it combines two very different kinds of data. File contents are big, mostly unchanging, and can be stored in cheap object storage. File metadata, the names, folders, versions and who can see what, is small but must be strictly correct, because a mistake there means lost files. Separating the two, and treating each properly, is the heart of the answer.
Max asks
“Design a service that keeps a folder in sync across a user's devices, like the popular cloud folder products.”
That is how Max, our AI interviewer, asks it. The key word is sync. Uploading and downloading files is easy. Keeping several copies identical, when any of them can change at any time, even offline, is the hard part. We will spend most of our time on how changes are detected, transferred and applied, and what happens when two devices change the same file.
The plan: requirements and numbers, then the key idea of splitting files into blocks, then the high-level design. Then deep dives on uploading changes, the metadata service and its change journal, notifying devices, downloading, conflicts, sharing and versions, and finally failures and the follow-up questions.
Step 1: Clarify the requirements
- 01Sync a folderAdd, edit, rename, move, delete on any device
- 02Many devicesDesktop clients, phones, the web
- 03Offline editsWork offline; sync when back online
- 04SharingShare a folder with other users
- 05Version historyRestore a file to an earlier version
Start with questions to pin down the scope.
Users sync a folder: any add, edit, rename, move or delete on one device shows up on the others. Devices include desktop clients that watch the file system, mobile apps that usually download files on demand, and a web interface.
Ask about offline use. The answer is always yes: a laptop on a plane edits files, and syncs when it lands. That single requirement guarantees we will have conflicts, so we will need rules for them.
Sharing a folder with other people, so their changes sync to us too, and version history, so a user can recover from a mistake or from ransomware encrypting their files. Ask about maximum file size. Say up to tens of gigabytes, which tells us we can never upload a whole file just because a few bytes changed.
- 01Never lose dataDurability above everything
- 02CorrectEvery device converges to the same state
- 03EfficientTransfer only what changed
- 04Fast enoughChanges appear on other devices within seconds
- 05ScalesHundreds of millions of users, exabytes
The qualities. First, never lose data. Users trust us with their only copy of important files. Second, correctness: after the dust settles, every device must show exactly the same folder. These two rule out shortcuts we might take elsewhere.
Efficiency: bandwidth on laptops and phones is precious, so transfer only what changed, and never upload the same content twice. A one-byte edit to a big file should not mean re-uploading it.
And speed: a change should appear on other devices within a few seconds when they are online. Not milliseconds, like chat; a few seconds is fine. And it must scale to hundreds of millions of users.
Step 2: Back-of-the-envelope estimates
Let us size it.
Say five hundred million users with ten gigabytes each on average. That is around five exabytes. Exabytes. Clearly, file content must go into a massive, cheap, highly durable object store, and deduplication will be worth real money.
Changes: a hundred million daily users making about ten changes a day is a billion file changes a day, about twelve thousand a second. Each change is a metadata update, so the metadata store must handle that write rate with strong correctness.
And metadata size: ten thousand files per user times five hundred million users is five trillion file entries. Each is small, a few hundred bytes, but that is still petabytes of metadata. So metadata must be sharded, and the natural shard key is the user, or more precisely the namespace, which we will define shortly.
The shape is clear. Content: enormous, write-once, cheap storage. Metadata: much smaller, but frequently changing and needing strict consistency. Two different stores, designed differently.
Deduplication changes these numbers a lot, and it is worth estimating. Many users store the same installers, the same popular documents and the same photos sent around by message, and every version of a file shares most of its blocks with the previous one. Real systems report that deduplication and delta uploads together cut stored bytes and upload traffic substantially. At exabyte scale, even a quarter saved is an enormous amount of money.
Step 3: Splitting files into blocks
report.pdf (18 MB) block 0: sha256 = 9f2c... 4 MB block 1: sha256 = 77ab... 4 MB block 2: sha256 = e013... 4 MB block 3: sha256 = 41d8... 4 MB block 4: sha256 = c5a0... 2 MB edit page 3 → only block 1 changes → upload one 4 MB block
Before the boxes, the single most important idea. Do not store files as files. Split each file into blocks, say four megabytes each, and compute a cryptographic hash of each block. A file then becomes simply an ordered list of block hashes.
Store each block in object storage under its hash. This is called content addressing, and it gives us three things almost for free. First, deduplication: two identical blocks have the same hash, so they are stored once, whether they are in the same file, two copies of a file, or files belonging to different users.
Second, efficient updates: when a user edits a file, only the changed blocks have new hashes, so only those blocks are uploaded. A small edit to a big file uploads one block instead of the whole thing. Third, resumable transfers: if the connection drops, every block already uploaded is safe, identified by its hash, and the client continues with the rest.
A refinement worth mentioning: with fixed block boundaries, inserting a single byte at the start of a file shifts every block, so every hash changes. Content-defined chunking fixes that by choosing block boundaries based on the content itself, using a rolling hash, so an insertion only changes the blocks around it. It is a nice detail for a strong candidate, but fixed blocks are fine as a first answer.
Step 4: The API
POST /v1/blocks/missing { hashes: [...] } → { need: [...] }
PUT /v1/blocks/{hash} body = block bytes
GET /v1/blocks/{hash}
POST /v1/files/commit
{ ns, path, blocks: [...], baseVersion: 41 }
→ { version: 42, seq: 99812 } | 409 conflict
GET /v1/changes?ns=ns_77&after=99810&limit=500
GET /v1/notify (long poll: returns when something changed)With the block idea in place, the API almost writes itself, and it is worth showing, because it makes the protocol between client and server concrete. There are two groups of calls: block calls and metadata calls.
Block calls: ask which of a list of hashes the server is missing, upload a block by its hash, and download a block by its hash. The server verifies that an uploaded block really hashes to the name it was given, so a buggy or malicious client cannot store wrong content under someone else's hash.
Metadata calls: commit a new version of a file, with its list of block hashes and the base version, which returns the new version or a conflict. List changes in a namespace after a cursor, in pages. And a long-poll notify call, which simply waits until something changes. Every operation a user can perform, from renaming a folder to restoring a deleted file, becomes a metadata call. No call ever mixes content and metadata, which is the separation we want.
Step 5: The high-level design
Now the boxes. On each computer, a desktop client watches the synced folder for changes, keeps a local database of what it believes each file looks like, and caches recent blocks.
The block service handles content. Clients upload and download blocks through it, or directly to object storage with signed URLs. The block store is keyed by hash, replicated across data centres for durability, and knows nothing about files or users.
The metadata service handles everything else: which files exist in which folders, which blocks make up each version of each file, who can see what, and an ordered journal of every change. It is backed by a strongly consistent, sharded database. This is the source of truth for what the folder looks like.
And a notification service keeps a long-lived connection open to each online client. When something changes, it tells the affected clients: something changed, come and sync. It never carries the data itself, just the nudge.
Say why the separation matters. Blocks are immutable and identified by hash, so they can be cached anywhere, replicated lazily and never need locking. Metadata is mutable and needs transactions. Keeping them apart lets each store do what it is good at, and means a huge upload never holds a database lock.
Step 6: Uploading a change
1. client: file changed → split, hash blocks
2. client → metadata: "which of these hashes do you need?"
← need [77ab..]
3. client → block store: PUT 77ab..
4. client → metadata: commit(path, blocks=[9f2c,77ab,...],
baseVersion=41)
← ok, version 42, journal seq 99812
← or conflict: current version is 43Let us trace a single edit. The client notices a file changed, through the operating system's file change notifications. It splits the file into blocks and hashes them.
It asks the metadata service: here is the list of block hashes for the new version; which ones do you not have? Because blocks are deduplicated globally, the answer is often very few, and sometimes none at all, for example when the user copied a file that already exists. The client uploads only the missing blocks.
Then it commits: in one transaction, the metadata service records the new version of the file as this list of hashes, and appends an entry to the change journal. The commit includes the version the client started from, the base version. If the file's current version is still that base, the commit succeeds. If someone else committed in between, it fails with a conflict, which we will handle shortly. This is optimistic concurrency, and it is what keeps metadata correct without locking files.
Note the order: blocks first, metadata second. A commit never refers to blocks that do not exist yet. If the client crashes between the two steps, we are left with some orphan blocks that nobody references, which a background garbage collector removes later. Orphans waste a little space; the opposite order would corrupt files. Say that trade-off explicitly.
Step 7: The metadata service and the journal
| Table | Key | Holds |
|---|---|---|
| namespaces | ns_id | a user's root or a shared folder |
| files | ns_id, file_id | path, current version, deleted flag |
| versions | file_id, version | block hashes, size, author, time |
| journal | ns_id, seq | ordered list of every change |
| blocks | hash | size, reference count |
Let us look at the metadata in more detail, because this is where correctness lives.
First, the namespace. Each user's root folder is a namespace, and each shared folder is its own namespace, mounted into the folder trees of everyone it is shared with. Namespaces are the unit of sharding and the unit of ordering. All of a namespace's metadata lives on one shard, so a commit is a transaction on a single shard, which is fast and simple.
Files have a current version, and versions record the list of block hashes, the size, who made the change and when. Old versions are kept for history.
The journal is the key structure for sync. Every change to a namespace is appended with an increasing sequence number: file added, file modified to version forty-two, file moved, file deleted. It is the namespace's history, in order.
And blocks have a reference count, or are tracked by a periodic scan, so that blocks no longer referenced by any version can eventually be deleted. Be careful here: with deduplication across users, deleting a block that another user still references would be catastrophic, so garbage collection must be conservative and delayed.
Why a relational, strongly consistent database for metadata, rather than an eventually consistent store? Because the operations are transactional by nature: moving a folder of a thousand files, or committing a version only if the base version matches. Getting those wrong loses or duplicates files. The scale is large but shardable by namespace, so we get transactions within a shard and scale across shards.
Step 8: Telling devices to sync
device keeps: cursor per namespace = last journal seq seen
notification: "ns_77 changed"
device → GET /changes?ns=ns_77&after=99810
← [99811: modified a.docx v42,
99812: deleted old.txt], cursor = 99812
device: download needed blocks, apply, save cursorHow does the laptop learn that the phone changed something? Each device keeps a cursor per namespace: the last journal sequence number it has applied. Syncing means asking: what changed after my cursor? The answer is the journal entries since then, in order.
To make that fast, the device keeps a long-lived connection to the notification service, as a long poll or a WebSocket. When a namespace's journal gets a new entry, the metadata service publishes an event, and the notification service sends a short message, namespace seventy-seven changed, to every connected device that has that namespace. The device then pulls the changes itself.
Why notify and then pull, rather than push the changes? Because pull is the one mechanism that always works. A device that was offline for a month, or that missed a notification, or just restarted, does exactly the same thing: ask for changes after its cursor. Notifications are just an optimisation that says do it now. If notifications fail entirely, devices still converge by polling every few minutes. Designing it this way means there is one sync path, which is tested constantly, instead of a fragile push path plus a rarely used recovery path.
Shared folders make this elegant. A folder shared with a hundred people is one namespace with one journal. Each of their devices holds a cursor in that journal. A change is written once, and every device catches up on its own. There is no per-recipient fan-out of data at all.
The notification service itself has to hold a connection for every online device, which at our scale is tens of millions of connections. Like the chat gateways in lesson eight, keep it thin: it maps namespaces to connected devices and forwards nudges. If one of its servers dies, its devices reconnect elsewhere and immediately ask for changes after their cursors, so nothing is missed.
Step 9: Applying changes on a device
- 01Fetch only missing blocksThe local block cache may already have most
- 02Write to a temp fileAssemble, verify hashes, then atomic rename
- 03Mobile: on demandDownload a file only when opened
- 04Smart placeholdersShow files that are only in the cloud
When a device applies a change, it compares the new version's block list with what it has locally, and downloads only missing blocks. If a file was renamed or copied, it may need nothing at all.
It assembles the file in a temporary location, verifies every block's hash, and then atomically renames it over the old file. A crash halfway leaves the old file intact, never a half-written one. This attention to atomicity on the client is easy to forget, and interviewers notice it.
Phones and small laptops cannot hold everything, so many clients show placeholders for files that exist only in the cloud, and download the content on demand when the user opens them. The metadata syncs fully; the content syncs selectively. Because metadata and content are separate in our design, this falls out naturally.
One more client detail: the client must tell the difference between changes it made itself and changes it downloaded, or it will see the downloaded file appear on disk, think the user changed it, and upload it again. The local database records the version each file came from, so the client can recognise its own writes and ignore them.
And clients should apply changes in journal order, but download content in parallel. Ordering the metadata changes keeps the folder structure correct, for example creating a folder before moving a file into it, while parallel block downloads keep large syncs fast. If a download fails, the client simply retries; the journal entry stays unapplied, and the cursor does not move past it until the file is in place.
Step 10: Conflicts
| Situation | Rule |
|---|---|
| Both edit the same file | first commit wins; second becomes a conflicted copy |
| Edit vs delete | keep the edited file |
| Both rename a folder | first wins; second is replayed on the new name |
| Same new file name in one folder | second is renamed with a suffix |
Offline edits make conflicts inevitable. A user edits a document on the plane, and a colleague edits the same shared document on the ground. Both try to commit a new version starting from version forty-one.
The first commit succeeds and becomes version forty-two. The second fails the base version check. What then? For arbitrary files, the service cannot merge contents, because it does not understand them. So the safest rule is: keep both. The second device saves its version as a new file next to the original, named something like report, conflicted copy, from the laptop, with the date. No one's work is lost, and the user decides.
Other conflicts get simple, predictable rules. An edit against a delete keeps the edited file, because losing work is worse than an unwanted file coming back. Two renames of the same folder: the first wins. Two new files with the same name: the second gets a suffix. The guiding principle to state is: when in doubt, never destroy data.
Some file types, like a shared document in an online editor, can do better with real-time collaborative editing, which merges individual operations. That is a different system, which we cover in a later lesson. For a general sync service, conflicted copies are the honest and safe answer.
Step 11: Versions, deletes and sharing
- 01Versions share blocksA new version stores only changed blocks
- 02Retention30 days, or longer on paid plans
- 03Deletes are softRecoverable until retention ends
- 04RansomwareRestore a whole folder to a point in time
Version history is cheap in this design, because versions share blocks. Version forty-two and version forty-one of a big file differ by one block, so keeping both costs one extra block, not a second copy of the file.
Keep versions for a retention period, say thirty days, and longer for paid plans. Deletes are soft: the file is marked deleted in metadata and can be restored until retention ends. Only then are its versions removed, and their blocks become candidates for garbage collection.
Because the journal records every change in order, we can also restore a whole folder to any point in time. That is the cure for ransomware: when malware encrypts every file on a laptop and the client dutifully syncs the encrypted versions, the user rolls the folder back to the hour before it happened. Mention this; it shows you have thought about what users really need from history.
Sharing ties back to namespaces. Sharing a folder creates a namespace with an access list, and each member mounts it somewhere in their own tree. Permission checks happen in the metadata service on every commit and every list of changes, and block downloads use short-lived signed URLs, issued only after the metadata service has checked that the user may read a file containing that block.
Step 12: Scaling and failures
- 01Huge shared namespaceHot shard: split very large namespaces
- 02Metadata shard downReplicas with automatic failover; clients retry
- 03Block store region downBlocks replicated across regions
- 04Client bugServer validates; version history undoes damage
A few failure cases. A namespace shared across a large company, with millions of files and constant edits, can become a hot shard. Watch for it, and give very large namespaces dedicated shards, or split them by subfolder.
Metadata shards are replicated with synchronous replication and automatic failover, because losing an acknowledged commit is not acceptable. During a failover, clients see errors and retry; their work is safe locally.
Blocks are replicated across regions, or stored with erasure coding, which splits each block into pieces plus parity so it survives several failures at a fraction of the cost of full copies. Durability targets for storage like this are many nines.
And a buggy client release, which, for example, deletes files it should not, is the scariest failure in sync systems, because the service faithfully syncs the damage everywhere. Defences: roll out client versions gradually, have the server reject obviously suspicious operations, like deleting a large share of a user's files at once without confirmation, and rely on version history to undo.
Step 13: The follow-up questions
Max asks
“Two users upload the same large file. Do you store it twice?”
No. The blocks have the same hashes, so the second upload asks which blocks are needed and is told none. The upload finishes instantly. Mention the privacy angle too: instant uploads can reveal that a file already exists in the service, so some designs only deduplicate within a user's own data, or require the client to prove it has the content.
Max asks
“How does a brand-new laptop get a user's twenty gigabytes?”
It starts with an empty cursor, lists the whole namespace from the metadata service, which is a paged snapshot rather than replaying years of journal, and then downloads blocks in parallel, most recently used files first. With placeholders, the folder appears immediately and content fills in behind it. If another device on the same local network already has the files, clients can even fetch blocks from each other, which is much faster than the internet.
Max asks
“Why not let clients talk directly to the database?”
Because the metadata service enforces permissions, validates operations, runs the version check, writes the journal and publishes notifications, all in one place. Clients are untrusted and come in many versions. Keeping that logic on the server means a bad client can only make requests the server accepts, and we can change storage without updating every client.
Max asks
“How would you keep a phone's battery and data usage low?”
Sync metadata fully but content lazily, as placeholders that download on open. Batch syncs instead of reacting to every notification, especially on mobile data. Respect the operating system's background limits, and upload photos only on Wi-Fi unless the user chooses otherwise. And use the same delta and deduplication logic as desktop clients, so an edited file sends only changed blocks.
Recap
- 010 to 5: requirementsSync, offline, sharing, history; never lose data
- 025 to 10: estimatesExabytes of content, trillions of metadata rows
- 0310 to 20: blocks and boxesContent-addressed blocks; block store vs metadata
- 0420 to 35: syncCommit with base version, journal, cursor, notify then pull
- 0535 to 45: the restConflicted copies, versions, sharing, failures
On the clock: five minutes of requirements, ending with: never lose data and converge everywhere. Five minutes of numbers, showing exabytes of content and trillions of metadata rows, two very different stores.
Ten minutes on blocks named by their hashes, which give deduplication, delta uploads and resumable transfers, and on the split between the block store and the metadata service.
Fifteen minutes on sync: upload missing blocks, commit with a base version, append to the namespace's journal, notify devices, and let them pull changes after their cursor. And the last ten on conflicts, versions, sharing and failures. If you can explain why notify-then-pull is more robust than pushing data, you have shown the kind of thinking this question is designed to find.
File sync answers often get stuck on storage and never reach conflicts and the journal. Practicing out loud helps you get to the interesting part in time. You can practice this exact question with Max, our AI interviewer, at interview dry run dot com. It is free to start, and you get a scored report with what to fix. The written lesson, with every diagram, is on the site too. See you in lesson thirteen.
Now say it out loud
Watching an answer is not the same as giving one. Max asks this exact question, pushes back when an answer is vague and keeps time, then scores you per skill.
Practice with MaxFree: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.