Dev Skills

Design file sync like Dropbox: a full worked answer

Keep a folder in step across devices, with saves that work offline and multi-gigabyte files that upload and download in resumable chunks. The hard part is two devices editing the same file offline: the design has to detect the conflict and keep both versions, since silently dropping one is data loss.

hard

By devskills editorial team · Last updated

Common trap
Try it before reading. How the stages work: the five stages.

The question

Design a file sync service. A folder on several devices stays in step, edits made offline sync when the device reconnects, and history is recoverable. Files range from a few kilobytes to several gigabytes.

What kind of problem this is

“Design file sync like Dropbox” is a hard-level problem in the sync and offline family. The same data lives on several devices, all of which can be edited while disconnected.

Two people (or one person on two devices) changed the same thing offline. Everything hinges on whether you detect that or silently pick a winner, and on how little you can transfer to bring a device up to date.

Before anything: where is the slack?

What slack means

Local edits: zero. Propagation: seconds. Full sync of a new device: hours.

The local device must feel instant even with no network at all. Everything else (reaching other devices, agreeing with the server, resolving conflicts) has real slack. The design is built on that asymmetry.

A user saving a file has zero tolerance. The save writes to local disk and returns, even offline. Sync happens afterwards, in the background. If the product ever makes someone wait for the network to save a file, it has failed at its core job.

Propagation has seconds of slack. If a change reaches another device in three seconds rather than three hundred milliseconds, the user will not notice, because they are rarely watching two devices at once. So propagation can go through a queue and be batched, which matters a lot when someone drops in a folder of 10,000 files.

A new device syncing 200 GB has hours of slack, and the user knows it. What it must not do is block anything else, or start from the beginning if it is interrupted at 90%.

The place with no slack and no way to buy any: not losing an edit. If two devices both edited a file offline and one version silently disappears, that is not a sync delay. It is data loss, and the user will not know it happened.

So: The client is the source of truth for local state and works fully offline. Sync is asynchronous, resumable and chunked. Conflicts are detected and preserved as both versions rather than resolved by picking a timestamp.

1

Requirements

about 5 min
What a strong answer sounds like

Assumptions: desktop and mobile clients, folders can be shared between users, files from a few kilobytes to several gigabytes, and the client works fully offline with sync resuming on reconnect.

The question that changes a box: do we need to merge concurrent edits to the same file, or is preserving both acceptable? Real merging means understanding file formats. You can merge text; you cannot merge a video. So a general file sync product cannot merge. I will assume we detect the conflict and keep both versions, naming one "Alice's conflicted copy". It sounds like a cop-out, but it is the correct engineering answer, because the alternative is silently discarding somebody's work.

Second question: is deduplication across users acceptable? Storing one copy of a file that ten thousand users all have saves a lot of storage, but it leaks information: an attacker can learn whether a file already exists somewhere by watching whether its upload completes instantly. I will assume deduplication within a user's own account only, which is where most of the benefit is without the disclosure.

Scope I propose: syncing a folder across a user's devices, sharing with other users, offline edits with conflict detection, resumable upload and download of large files, and version history. Out of scope: real-time collaborative editing inside a document, which is a different system built on operational transforms or CRDTs rather than on file sync.

The costs named here
Preserve both versions rather than merge → costs: The user sees a conflicted copy and has to deal with it. In exchange, we never silently lose an edit, which is the one unrecoverable failure here.
Say this
"Shared folders, full offline operation, files up to several gigabytes. One question: do we merge concurrent edits? We cannot merge a video, so I would detect the conflict and keep both copies. The alternative is discarding somebody's work silently."
Common trap
Designing a diff algorithm. It was not asked for, it only works for some file types, and chunk-level sync gets you most of the benefit with none of the complexity.
Stage checklist
  • Established sharing between users, not just one user's devices
  • Asked about merging and chose conflict preservation, with the reason
  • Asked about cross-user deduplication and named the information leak
  • Excluded real-time collaborative editing as a different system
  • Committed to full offline operation as a requirement
2

Actors and lifecycle

about 6 min
What you are being asked for: List the actors — including the system — then write a file's life as a chain of states, and add the failure branches.
What a strong answer sounds like

Actors: the user, each of their devices as a separate actor with its own local state, other users sharing the folder, and the system itself, which decides what counts as a change, which version is current, when two versions are in conflict, and what history to retain.

A file's life: created or modified locally → detected by the client watcher → hashed and split into chunks → chunks not already on the server are uploaded → a new version is committed on the server → other devices are notified → they download the missing chunks → they apply the change locally. Plus deletion, which is a version like any other, and restore from history.

Failure branches. There are many, because this system runs on devices and networks it does not control. At detect: the file is still being written (someone is saving a 2 GB video), so uploading now captures a corrupt half-file. The client has to wait for the file to settle rather than react to the first event. At upload: the connection drops at 90% of 5 GB, which must resume from the last completed chunk, not restart. At commit: two devices commit versions derived from the same parent, which is the conflict case and the heart of the product. At notify: a device is offline, so it must find out on reconnect by asking what changed since the last version it saw, rather than depending on a push it missed.

The branches the system owns. A device offline for a month reconnects: sending it every individual change since then could be a hundred thousand events, so it needs a compacted answer: the current state of everything that changed, not the full history of how it got there. A user drops in a folder of 50,000 small files: that must not become 50,000 separate round trips, so the client batches. And the local disk fills mid-sync, which has to fail gracefully and resumably rather than leaving a half-written file that looks complete.

Common trap
Assuming the client always has a network. This product is defined by what it does without one, and most of the interesting branches start with a device that was away.
Stage checklist
  • Each device modelled as its own actor with its own state
  • Waiting for a file to settle before uploading a partially written file
  • Resumable upload from the last completed chunk
  • Two versions from the same parent named as the conflict case
  • Reconnect is a pull of what changed since a version, not a replayed push
  • A long-absent device gets compacted current state, not full history

The lifecycle, drawn

Edited locallyuser deviceSettled + hashedclient watcherMissing chunks uploadedclientVersion committedserverCursor moved, devices notifiedsystemApplied on other devicesclientsFile still being writtenwait for it to settle, or you upload a corrupt half-fileConnection drops at 90% of 5 GBresume from the last completed chunk — never restartParent version no longer matchesconflict: keep both, as a named conflicted copy. Never pick by timestampDevice offline for a monthpull the delta from its cursor — compact current state, not replayed historyLocal disk full mid-syncfail resumably; never leave a partial file that looks complete50,000 files dropped in at oncebatch hashes, bound parallelism, one cursor advance for the whole batch
A file's life across devices. The failed conditional commit is not an error. It is the mechanism that turns a silent overwrite into a visible conflict.
3

Numbers

about 6 min
What you are being asked for: Estimate storage, upload volume and the saving from chunking. Then finish: "So the hard part here is ___."
What a strong answer sounds like

Assume 50 million users, 50 GB each on average, so 2.5 exabytes of raw data. It goes straight to object storage. The one decision it forces is a retention and tiering policy, because keeping every version of everything on hot storage is not affordable.

Chunking is where the arithmetic becomes interesting. Split files into fixed 4 MB chunks and store each by content hash. A user edits one paragraph in a 2 GB presentation: without chunking that is a 2 GB upload, with chunking it is one 4 MB chunk, because every other chunk hashes the same and is already on the server. That is a 500-fold reduction for a common case, and an interrupted upload can resume at chunk granularity. No other decision on the board does as much for the product.

That 500-fold figure quietly assumes the edit overwrote bytes in place. Insert 100 bytes at the 1 MB mark of the same 2 GB file and fixed-size chunking falls apart: every byte after the insert moves 100 positions, so all 512 chunks, from the one holding the insert onward, hash differently and the full 2 GB goes up again. Content-defined chunking fixes this by choosing boundaries from the data itself: slide a rolling hash (Rabin, or the faster Gear hash used by FastCDC) over a window of ~48 bytes and cut wherever the low bits of the hash are zero, tuned so chunks average 4 MB, with a minimum and maximum size. After the insert, the cut points beyond the edit sit on the same content they always did, so the edited chunk changes (and occasionally its neighbour) and the other ~510 match: about 4 to 8 MB uploaded instead of 2 GB. The cost is a hash computed over every byte on the client, and variable chunk sizes, so a chunk's offset in the file is no longer a multiplication; the client needs the full chunk list to seek. Fixed-size is fine, and simpler, when edits overwrite in place (VM images, database files); content-defined chunking wins wherever bytes get inserted or deleted, which is most documents.

Metadata is the part people underestimate. 50 million users times, say, 20,000 files each is a trillion file records. That does not fit on one machine and it is not object storage's job. It needs a partitioned database, and the partition key has to be the user or the account, so that "list my folder" is one partition and never a scatter across the cluster.

Change notifications: if 10 million devices are online and each sees a few changes an hour, that is roughly 10,000 notifications a second, which is small. The cost is holding 10 million open connections, not the messages. It is the same shape as chat.

So the hard part here is conflict handling and metadata at a trillion rows, not bandwidth. Chunking and object storage make the bytes a solved problem. The design is about knowing which version is current for every file on every device, and detecting when two devices disagree.

The costs named here
Content-addressed 4 MB chunks → costs: A chunk index per file and a garbage collection problem when versions are deleted: a chunk can only go when nothing references it. Worth it for a 500-fold saving on large-file edits.
Content-defined chunk boundaries over fixed offsets → costs: A rolling hash over every byte on the client and variable-size chunks, so seeking needs the chunk list. Without it, one inserted byte near the start of a file re-uploads the whole file.
Say this
"2.5 exabytes in object storage, but the number that matters is chunking: editing a paragraph in a 2 GB file becomes a 4 MB upload. Metadata is a trillion rows, partitioned by user so listing a folder is one partition. So the hard part here is conflicts and metadata, not bytes."
Common trap
Estimating total storage and stopping. The chunking saving is the number that changes the design, and it is the one worth showing.
Stage checklist
  • Separated bulk data (object storage) from metadata (partitioned database)
  • Quantified the chunking saving with a concrete example
  • Showed why an insertion breaks fixed-size chunks, and when content-defined chunking is worth its cost
  • Estimated the metadata row count and said it must be partitioned by user
  • Noted connections rather than message volume as the notification cost
  • Finished the sentence: conflicts and metadata, not bandwidth

The numbers, drawn

Edit a paragraph in a 2 GB file — no chunking2 GB uploaded
Same edit, 4 MB content-addressed chunks4 MB uploaded — 500x less
File metadata rows~1 trillion — a partitioned database

So the hard part is conflicts and metadata, not bandwidth. Chunking plus object storage makes the bytes a solved problem; knowing which version is current on every device is the design.

Chunking is the number that changes the design. Everything else follows from it.
4

High-level design

about 12 min
What a strong answer sounds like

The client is a full part of this system, not a thin caller. It holds a local database of every file, its version, its chunk hashes, and its sync state. That is what makes offline work possible, and it is why the client can answer "what changed" without asking anybody. A watcher observes the filesystem, waits for files to settle, hashes them, and compares against its local record.

The metadata service owns the truth about versions, partitioned by account. Each file has a monotonically increasing version, and each account has a cursor: a single number that advances with every change in that account. A device syncs by saying "I am at cursor 8,412, what has changed since?" and getting back a compact list. The cursor is the most useful element in the design. Reconnecting after a month costs about the same as reconnecting after a minute, because the server answers with current state rather than replayed history.

Chunk storage is object storage, keyed by content hash. The client asks "which of these 50 hashes do you already have", uploads only the missing ones over presigned URLs directly to storage, and then commits a new file version referencing the full list. The bytes never touch my servers. At exabyte scale that is a requirement, not an optimisation.

Commit is where correctness lives. A new version is accepted only if its parent version matches what the server currently has: a conditional update, like the seat reservation. If the parent does not match, another device got there first, and this is a conflict rather than an overwrite. That one check is what prevents silent loss, and it takes about two lines of code.

Notification is a persistent connection per device, carrying only "the cursor moved" rather than the change itself. The device then pulls the delta over normal HTTP. That keeps the socket layer trivial and makes a missed notification harmless, since the next connection reveals the gap anyway.

Sharing adds a folder-level access record, and a change in a shared folder advances the cursor for every member. Permission checks happen at the metadata service on every access, not at the edge, because a chunk hash is effectively a capability and must never be servable without an ownership check.

The costs named here
Per-account cursor → costs: All changes in an account serialise through one counter, so a shared folder with very heavy write activity has a ceiling. In exchange, sync becomes easily correct and resumable.
Direct-to-storage chunk transfer → costs: The server does not see the bytes, so it cannot scan for malware inline and must do it asynchronously afterwards.
Say this
"Each account has a cursor, so a device says 'I am at 8,412, what changed?' and reconnecting after a month costs the same as after a minute. Commits are conditional on the parent version. That one check turns silent overwrites into detected conflicts. Chunks go straight to object storage over presigned URLs."
Common trap
Syncing by comparing modification times. Clocks on user devices can be wrong, sometimes by years, and users set them by hand. Use version numbers and content hashes instead; they do not depend on anyone's clock.
Stage checklist
  • Client holds a local database and can operate entirely offline
  • Per-account cursor so syncing is a delta, not a replay
  • Chunks in object storage by content hash, uploaded over presigned URLs
  • "Which of these hashes do you have" before uploading anything
  • Commit is conditional on the parent version — this is what prevents loss
  • Notifications carry only that the cursor moved; the client pulls the delta
  • Permission checked at metadata access, never inferred from knowing a hash

The architecture, drawn

have these hashes?presigned PUTconditional commitcursor movedDeviceslocal DB, offline-capableMetadata svcversions + cursorMetadata storepartition: accountChunk storagekeyed by content hashNotify svc"cursor moved"Chunk GCconservative sweepEvent queue
Bytes go straight to object storage by content hash. The metadata service owns versions and the per-account cursor, which is what makes sync a delta rather than a replay.
5

Deep dive and tradeoffs

about 14 min
What a strong answer sounds like

Hard part one: the offline conflict. Two devices both had version 7 and both edited while disconnected. Device A reconnects and commits version 8 successfully, because its parent matched. Device B reconnects and tries to commit with parent 7, but the server is now at 8, so the conditional commit fails. That failure is the correct outcome. B has not lost anything; it has been told it is behind. B then downloads version 8, and because it cannot merge arbitrary files, it writes its own edit as a new file named for the conflict and syncs that as a separate object. Both versions now exist and both are visible. The costs: the user sees a file they did not create and has to deal with it, and a folder synced across many devices after a long offline period can produce several conflicted copies, which feels messy. It is still the right trade. The alternative is choosing a winner by timestamp, and consumer device clocks are often wrong, so that choice would delete real work with no error and no way to notice.

Hard part two: 50,000 files at once. A naive client does 50,000 hash checks, 50,000 uploads and 50,000 commits, and the round trips alone take hours while the metadata service sees a burst of writes for one account: a self-inflicted hot partition. So: the client batches. Hash existence is asked in batches of hundreds. Uploads run with bounded parallelism, a few at a time, so one user cannot saturate their own connection or my ingest. Commits are batched into a single call that advances the cursor once for the whole batch rather than 50,000 times, which is what stops every other device receiving 50,000 notifications. Cost: the batch commit is more complex, and a partial failure has to be resumable at file granularity within the batch.

Chunk garbage collection. Chunks are shared between versions, between files, and in shared folders between users. Deleting a file cannot delete its chunks, because another version or another file may reference them. So chunks are reference counted, or swept periodically by finding unreferenced hashes. A sweep must be conservative and ignore anything recently created, because a chunk uploaded seconds ago may not yet have a version referencing it. Deleting a chunk that is still needed is unrecoverable data loss, so the job errs toward keeping too much. Cost: real money spent on storage that nothing references, and a job nobody should make more aggressive without careful review.

History and restore. Versions are cheap because they share chunks, so keeping 30 days of history costs far less than 30 copies. Beyond that, thin them out. Restore is just committing an old version as a new one, which keeps history append-only and means restore is itself undoable.

The costs named here
Conflicted copies visible to the user → costs: A messy folder after a long offline period. Accepted, because the alternative silently deletes work.
Conservative chunk sweeping → costs: Paying to store orphaned chunks for a while. Worth it, because the failure in the other direction is unrecoverable.
Say this
"Device B's commit fails because its parent version no longer matches, and that failure is the feature: B learns it is behind instead of overwriting A. Since we cannot merge arbitrary files, B keeps both as a conflicted copy. Choosing a winner by timestamp would silently delete real work, based on clocks that are often wrong."
Common trap
Garbage collecting chunks aggressively. Deleting a chunk something still references is permanent data loss, and no retry or restore can undo it.
Stage checklist
  • Walked the conflict through both devices, not just the server
  • Explained why timestamps cannot decide it: consumer clocks are wrong
  • Batched hash checks, uploads and commits for a bulk import
  • One cursor advance per batch, so other devices are not flooded
  • Chunk garbage collection by reference, conservative on purpose
  • History cheap because versions share chunks; restore is a new version

The decision this turns on

A
Pick a winner by timestamp
  • —One version survives, so the folder stays tidy and the user is never confused.
  • —Depends on device clocks, which on consumer machines are routinely wrong.
  • —The loser is deleted with no error, no notification and no way to recover it.
  • —Feels clean right up until someone loses an afternoon of work.
B
Detect and keep both
  • —The conditional commit fails, so the second device knows it is behind.
  • —Both versions exist; nothing is ever silently discarded.
  • —The user sees a conflicted copy they did not create and must resolve it.
  • —A long offline period across several devices can produce several such copies.
Which one: Keep both. The messy folder is a visible, recoverable annoyance; a silently deleted edit is invisible and permanent. The version check that produces the conflict is two lines of logic, and the product's correctness depends on it.
What to do when two devices committed edits from the same parent version.

And then they push back

Your storage bill doubles every six months. What do you do?
A weak answer

"We would delete old data." Which data, and who agreed you could? Retention is usually a product and legal decision, not an engineering one.

A strong answer

"First, find out what is actually growing, because it is rarely uniform — usually one dataset, often logs or raw events or derived copies nobody remembers creating. Then, in order of cheapness: lifecycle policies moving cold data to colder tiers, which is cheap to implement and can cut the bill sharply when most data is rarely read after its first week; compression and columnar formats, which for event data is a 5-10x reduction; tiered granularity, keeping recent data fine-grained and rolling older data up; and only then deletion, which needs a retention policy agreed with the product and legal side rather than decided by me. I would also check for duplication — a derived index, a backup of a backup, an old migration copy — because a surprising share of storage growth is copies. The one thing I would not do is delete raw data that lets me reprocess when a job turns out to be wrong, because that is the safety net that makes everything else correctable."

You grow 10x every year for three years. What do you rebuild?
A weak answer

"The design already scales to any size." No design does, and claiming so means you have not identified where your assumptions run out.

A strong answer

"Year one, nothing. I sized the current design with headroom and it absorbs 10x. Year two, the single-primary database stops being enough and I have to partition, which is the expensive one: it means choosing a shard key, dual-writing, backfilling and cutting over, and it takes a quarter. That is why I chose the data model on day one so the natural shard key was already the primary access key. The migration is painful, but it is not a redesign. Year three, the thing I expect to hurt is not capacity but blast radius and operations: one global system serving 1,000x the original traffic needs regional isolation so one failure does not take everything down. So I rebuild the storage layer once, and I plan for it by picking the key correctly now."

The topics this answer used