Design file sync (Dropbox-style)
Keep a folder identical on every device by splitting files into content-addressed blocks, committing changes to a strongly consistent metadata journal and sending only what changed.
The problem
Before file sync, people moved work between machines by emailing files to themselves or carrying a USB stick. Drew Houston has said he started Dropbox in 2007 after forgetting his USB stick on a bus journey. The product is a folder that is the same on every device you own.
The naive build is short: watch a folder, upload any file that changes, and have the other devices download it. It breaks quickly. A designer saves a 2 GB project file every few minutes, and each save uploads 2 GB. A laptop on hotel Wi-Fi drops its connection at 95% and starts again from zero. Two laptops edit the same document on a flight, and the second upload silently replaces the first. Every device polls the server every few seconds to ask whether anything changed.
Each failure points at one part of the real design. Split files into blocks so a small edit is a small upload. Name blocks by their hash so uploads are resumable and duplicates cost nothing. Keep the file tree in a strongly consistent store so conflicts are detected, not lost. Push a notification so devices do not poll.
Requirements
Functional
- A folder on each device mirrors the user’s files. Adds, edits, moves, renames and deletes all sync.
- A change on one device reaches the user’s other online devices within seconds.
- Devices work offline and sync when they reconnect.
- Folders can be shared between users.
- Version history: restore an earlier version or a deleted file for 30 days.
- Files up to tens of gigabytes, with resumable uploads.
Out of scope unless asked: several people typing in the same document at once (a different design, built on operational transforms or CRDTs), full-text search, previews and end-to-end encryption.
Non-functional
- Durability: losing a file is the worst possible failure. Stored blocks need the kind of durability object stores are designed for (Amazon S3 states a design target of eleven nines).
- Metadata consistency: strong. Every device must see the same order of changes within a folder, and a commit either happened or did not.
- Bandwidth efficiency: upload size should follow the size of the change, not the size of the file.
- Sync latency: other online devices learn of a change within about 5 seconds.
- Availability: 99.9% or better. Clients keep working offline, so a short outage is far more tolerable than a wrong answer.
- Scale: 100 million users, 10 million active each day.
Capacity estimates
| Quantity | Working | Result |
|---|---|---|
| Stored bytes | 100M users x 5 GB | 500 PB before deduplication and replication |
| File entries | 500 PB / 1 MB average file | about 500 billion |
| Metadata size | 500B entries x 200 bytes | about 100 TB |
| Commits | 10M active x 20 changes a day / 86,400 | about 2,300 per second, 7,000 at peak |
| Upload volume | 200M commits x 500 KB changed | 100 TB a day, about 1.2 GB per second |
| Open connections | 10M active x 1.5 devices | about 15 million long polls |
Two conclusions drive the design. First, the bytes and the metadata have opposite shapes. Blocks are enormous in total, immutable and fetched by exact name, which suits object storage. Metadata is 5,000 times smaller but mutable, ordered and transactional, which suits a sharded relational database. Second, 15 million mostly idle connections are a different workload from request handling, so notification gets its own service.
API
POST /v1/commits
Authorization: Bearer <token>
{ "namespace_id": 8812, "path": "/reports/q3.pptx", "parent_rev": 41,
"size": 41943040, "blocklist": ["a3f1...", "77c0...", "e9b2..."] }
200 OK { "rev": 42, "journal_id": 190233 }
200 OK { "need_blocks": ["e9b2..."] }
409 Conflict { "current_rev": 43 }
PUT /v1/blocks/{sha256} body: up to 4 MB
GET /v1/blocks/{sha256}
GET /v1/changes?cursor=... entries after the cursor, and a new cursor
GET /v1/changes/longpoll?cursor=... held open until something changes or it times out
A commit is a claim: “this path is now this list of blocks, and I based my edit on revision 41”. The server answers in one of three ways: accepted, upload these missing blocks first, or you are out of date. PUT of a block is naturally idempotent, because the name is the hash of the content and writing the same bytes twice changes nothing.
Data model
The unit of sharing and of sharding is the namespace: a user’s root folder, or a shared folder. Dropbox has described its own version of this table as the server file journal.
| Column | Type | Notes |
|---|---|---|
namespace_id |
integer, shard key | every row of one folder tree lives on one shard |
journal_id |
integer | increases by one per commit in the namespace |
path, file_id |
string, integer | the stable id survives renames |
blocklist |
list of hashes | empty for a delete marker |
Each row also carries rev, size, a modified time and a flag marking the latest version of the path. Old rows are the version history.
The block index maps hash to a storage location and size. A membership table maps namespaces to users and roles.
The client keeps a small local database, usually SQLite, with the last state it synced. That is how it tells “I changed this file” from “the server changed this file”, and it holds the cursor: the last journal_id applied in each namespace.
High-level architecture
Upload. A file watcher notices a save. The client splits the file into 4 MB blocks, hashes each one and sends a commit. The metadata service asks the block service which hashes it already holds and returns the missing ones. The client uploads those blocks, several in parallel, and commits again. This time the metadata service appends a journal row in a transaction and publishes a small “namespace changed” event.
Notify. Each online device holds a long poll open against the notification service, which keeps an in-memory map from namespace to waiting connections. When the change event arrives it answers those requests. The reply carries no file data, only “ask for changes”. Long polling, server-sent events and WebSockets all work here.
Download. The device calls GET /v1/changes with its cursor, receives the new journal rows, compares each block list with the blocks it already has, downloads the missing blocks and reassembles the file. It writes to a temporary file and renames it into place so a reader never sees a half-written file.
Garbage collection. Workers find blocks that no journal row inside the retention window refers to and delete them from the block store.
Deep dives
Chunking, content addressing and deduplication
The client cuts every file into blocks and names each block by a cryptographic hash of its bytes. Dropbox has described using 4 MB blocks hashed with SHA-256. A file is then an ordered list of hashes.
Three properties follow.
- Delta sync. Change one slide in a 40 MB deck and one hash in ten changes. The upload is 4 MB.
- Resumable uploads. Progress is the set of blocks the server holds. After a crash the client commits again and is told what is still missing. A 10 GB file is 2,560 blocks, and a dropped connection costs at most the few that were in flight.
- Deduplication. A copied or moved file, or the same installer in two folders, has hashes the server already holds, so nothing is uploaded.
Step 1 of 8
A 40 megabyte slide deck is already synced. It is stored as ten 4 megabyte blocks, and the metadata service holds the list of their ten hashes as revision 41.
Read the steps as text
- A 40 megabyte slide deck is already synced. It is stored as ten 4 megabyte blocks, and the metadata service holds the list of their ten hashes as revision 41.
- You change one slide on the laptop and save. The client hashes the file again, block by block. Nine hashes match the old list. Only block 7 has a new hash.
- The laptop asks to commit the new list of hashes on top of revision 41. The metadata service finds one hash it has never seen and asks for that block.
- The laptop uploads that one block, named by its hash. The block service hashes the bytes again to check them, then writes them to object storage. Four megabytes travel, not forty.
- The laptop sends the same commit again. Every block now exists and revision 41 is still the latest, so the metadata service records revision 42 in one transaction.
- The metadata service publishes a small event saying the folder changed. The notification service answers the long poll that the phone has been holding open.
- The phone asks for changes since its cursor and receives the new list of hashes. It already has nine of the blocks, so it downloads only block 7 and rebuilds the file.
- If the laptop had crashed halfway, it would commit again and be told which blocks are still missing. Naming blocks by their hash makes a small edit a small transfer and makes every upload resumable.
Fixed-size chunking has one weakness. Insert a byte at the start of a file and every later block boundary shifts, so every block gets a new hash. Content-defined chunking fixes this: slide a rolling hash over the bytes and cut wherever the hash matches a pattern, so boundaries move with the content. An insertion then changes only the chunk it lands in and perhaps a neighbour. Backup tools such as restic and Borg work this way. It costs more CPU and produces variable-size chunks. A middle path keeps fixed blocks and runs an rsync-style diff against the previous version of a changed block.
Cross-user deduplication saves the most storage and is the most dangerous. If an upload finishes instantly because another customer already stored the same file, you have told the uploader that someone has it. Worse, if a commit needs only hashes, anyone who learns a file’s hashes can add it to their account and download it. Researchers published both attacks around 2010 and 2011. The safe rule: a client may skip uploading a block only if that block is already referenced within its own account. The server can still store each distinct block once.
The server always re-hashes received bytes before storing them. That catches corruption in transit and clients that lie about a block’s name.
Commits and metadata consistency
A commit runs as one transaction on the shard that owns the namespace:
- Check the caller can write to the namespace.
- Check
parent_revis still the latest revision of the path. If not, return409. - Check every block in the list exists. If not, return
need_blocks. - Insert the journal row with the next
journal_idand clear the “latest” flag on the previous row.
Because the namespace is the shard key, all four steps touch one shard and need no distributed transaction. Step 2 is a compare-and-set, which is why this store needs ACID transactions and not eventual consistency. The awkward case is moving a file between two namespaces, for example from a private folder into a shared one. That spans shards and needs a two-phase commit or a carefully ordered pair of journal entries.
The order of operations across the two stores is the rule that keeps the system safe: blocks first, metadata second. A block with no metadata is an invisible orphan. Metadata with no block is a file nobody can open.
Reads must respect the cursor. If a device is told the namespace reached journal_id 190233 and then lists changes from a lagging replica, it sees nothing new and goes back to sleep. Either read change lists from the primary, or let the notification carry the journal id and serve the read only from a replica that has caught up to it.
Conflicts
A conflict exists when a commit’s parent_rev is stale: two devices started from revision 41 and both edited. The server cannot merge them, because it does not understand slide decks or spreadsheets, and picking a winner silently destroys someone’s work. So the losing client keeps its file under a new name, a “conflicted copy” with the device name and date, and syncs both. A person decides which to keep.
Edit against delete is settled the same way: the edit wins and the file comes back, because resurrecting a file is cheaper than losing changes. Renames are tracked by file_id, so a rename on one device and an edit on another combine cleanly instead of conflicting.
Bottlenecks and failure modes
- Client crashes mid-upload. Uploaded blocks stay on the server. On restart the client re-scans, commits and uploads only the remainder.
- Orphaned blocks. Uploads that are never committed, and blocks from versions older than the retention window, must be collected. The danger is a race: a collector decides a block is unreferenced at the same moment a new commit refers to it. Collect only blocks that have been unreferenced for longer than any commit could be in flight, for example a day.
- Lost notification or notification service down. Clients fall back to a slow periodic call to list changes. Sync becomes slower, not wrong.
- Metadata shard failover. Commits to those namespaces fail until a replica is promoted. Use synchronous replication for this store, because an acknowledged commit that vanishes means devices disagree about history.
- Huge shared folder. One commit to a namespace with 50,000 members wakes all their devices at once. Spread the wake-ups over a few seconds and let change lists be served from cache.
- Mass deletion or ransomware. Sync faithfully copies damage to every device. Version history and delete markers are the recovery path, which is why deletes are journal rows and not row removals.
Trade-offs
| Decision | Chosen | Alternative | Why |
|---|---|---|---|
| Chunking | Fixed 4 MB blocks | Content-defined chunks | Simple and cheap on the client; insertions near the start re-upload more |
| Metadata store | Sharded SQL, keyed by namespace | Wide-column or key-value store | Commits need transactions and ordering; costs cross-shard moves |
| Deduplication | Within an account | Across all users | No side channel; gives up some storage savings |
| Change delivery | Long poll hint, then pull by cursor | Push the change data | Lost hints are harmless; one extra round trip |
| Conflicts | Keep both files | Last writer wins | Never loses work; leaves clean-up to the user |
45-minute interview script
A pacing guide. Interviewers differ, so treat the timings as a default and follow their lead.
- 0:00 to 5:00
Requirements 5 min
Confirm the core loop (edit on one device, see it on the others), offline edits, shared folders, version history and maximum file size. State durability and metadata consistency as the two targets you will not trade away.
- 5:00 to 9:00
Capacity estimates 4 min
Derive total bytes, number of file entries, commits per second and open notification connections. Say the conclusion, which is that bytes and metadata have opposite shapes and belong in different stores.
- 9:00 to 13:00
API 4 min
Four calls. Commit a block list, put and get a block by hash, list changes since a cursor, long poll for changes. Point out that the commit carries the revision it was based on.
- 13:00 to 18:00
Data model 5 min
The per-namespace journal, the block index and the client's local database. Explain why the namespace is the shard key and why the journal id doubles as the sync cursor.
- 18:00 to 26:00
High-level design 8 min
Draw the client, the metadata service and database, the block service and object storage, then the notification path. Narrate one edit travelling from a laptop to a phone.
- 26:00 to 33:00
Deep dive: chunking and deduplication 7 min
Fixed-size against content-defined chunking, what a small edit costs in each, why resumable uploads fall out of content addressing, and the security limits of cross-user deduplication.
- 33:00 to 39:00
Deep dive: commits, consistency and conflicts 6 min
Blocks first then metadata, the single-shard commit transaction, detecting a conflict from the parent revision, and keeping both versions as a conflicted copy.
- 39:00 to 43:00
Failure modes and trade-offs 4 min
Client crash mid-upload, orphaned blocks and the garbage collection race, a lost notification, a metadata shard failover.
- 43:00 to 45:00
Wrap-up 2 min
Summarise in three sentences. Name what you would add next, such as rolling-hash deltas inside a block or LAN sync.
Key takeaways
- Split the system in two. Immutable blocks go to object storage, and the small mutable file tree goes to a strongly consistent, sharded relational store.
- A file is an ordered list of block hashes, so a small edit uploads one block and an interrupted upload resumes at the first missing block.
- Upload blocks first and commit metadata second, so metadata never points at bytes that do not exist.
- Every commit names the revision it was based on. A stale parent means a conflict, and the safe resolution is to keep both versions.
- A per-namespace journal id that only increases is both the ordering of changes and the cursor each device syncs from.
- Notifications are hints with no data in them. Losing one costs a delay, never correctness.
Check yourself
0 of 5 answered
Flashcards
These 6 cards are in your review deck. Tap a card to see the answer.
What is a content-addressed block?
A chunk of file data stored under the hash of its own bytes, for example SHA-256. Identical content always has the same name, which gives deduplication, integrity checking and idempotent uploads.
Fixed-size or content-defined chunking?
Fixed-size is simple and handles in-place edits well, but an insertion shifts every later boundary. Content-defined chunking picks boundaries with a rolling hash, so an insertion changes only nearby chunks, at the cost of more CPU and variable sizes.
How does a sync client resume a 10 GB upload after a crash?
It commits the block list again and the server replies with the hashes it does not have yet. The client uploads only those. Progress is lost for at most the blocks that were in flight.
How does the server detect a sync conflict?
Each commit carries the revision it was based on. If that is no longer the latest revision of the path, someone else committed in between, and the server rejects the commit.
Why is cross-user deduplication risky?
A fast "already have it" answer reveals that some other user holds the file, and if a hash alone were enough to claim a block, knowing a hash would let you download the content. Deduplicate within an account, or require proof of possession.
What does a device's sync cursor contain?
For each namespace it can see, the last journal id it has applied. Listing changes means asking for journal rows with a higher id.