Skip to content

Lesson 33 of 38Case studies

Design Dropbox (File Sync)

Design a file sync service with chunking, deduplication, a metadata journal per device, change notifications, and conflicted copies.

22 min read0/4 questions

You save a 2 GB video project on your laptop, and a minute later it is on your phone and your colleague's desktop. Then you change one title card, and only a few megabytes cross the network, not 2 GB. File sync looks like "upload a file, download a file", but the interesting parts are everything that makes it cheap and correct: splitting files into chunks, never uploading the same bytes twice, telling every device what changed, and deciding what happens when two people edit the same file on a plane. This design shows up in interviews as "Design Dropbox" or "Design Google Drive", and the same ideas power backup tools, package registries, and container image layers.

Requirements

Functional

  • Upload and download files of any type, up to 50 GB each.
  • Sync automatically across all of a user's devices.
  • Share folders with other users, with view or edit access.
  • Keep version history, so you can restore a file from last week.
  • Work offline, then sync edits when the device reconnects.

Non-functional

  • Never lose data. A file confirmed as saved must survive disk, server, and data center failures.
  • Strongly consistent metadata: two devices must agree on which version of a file is current.
  • Changes reach other online devices within seconds.
  • Use as little bandwidth as possible. Users notice when sync eats their connection or phone data plan.

Out of scope: real-time co-editing of documents (that is Google Docs, built on operational transforms or CRDTs inside the app), full-text search of file contents, and previews.

Back-of-the-envelope numbers

QuantityMathResult
Usersgiven500M total, 100M daily active
Logical storage500M × 5 GB average usedabout 2.5 EB before dedupe
File changes100M DAU × 20 changes a day / 86,400about 23,000 commits/s
Upload bandwidth2B changes × about 1 MB of new chunksabout 2 PB a day, roughly 185 Gbps
Metadata rows500M users × 2,000 filesabout 1 trillion file entries
Chunks per 50 GB file50 GB / 4 MBabout 12,800 chunk hashes, about 400 KB of metadata

Two things stand out. Bytes are huge, so they belong in object storage, and anything that avoids sending bytes is worth real money. Metadata is also big and must be strongly consistent, so it needs a sharded relational database, not a cache. These are the two halves of the design, the same split you saw in Storage and Blobs.

API

POST /v1/files/commit_check
{ "path": "/Projects/cut.mov", "chunks": ["9f86d0...", "3a7bd3...", "ef2d12..."] }
 
200 OK
{ "missing": ["ef2d12..."],
  "upload_urls": { "ef2d12...": "https://blobs.example.com/ef2d12...?X-Amz-Signature=..." } }
 
PUT <presigned url>                         -> raw chunk bytes, straight to object storage
 
POST /v1/files/commit
{ "path": "/Projects/cut.mov", "parent_rev": 41, "chunks": [ ... ], "size": 2147483648 }
200 OK  { "rev": 42 }
409 Conflict  { "current_rev": 43 }          -> someone else changed it first
 
GET  /v1/changes?cursor=ns7:1180            -> entries after journal position 1180
GET  /v1/changes/longpoll?cursor=ns7:1180   -> returns early when something changes
GET  /v1/files/chunks/{hash}                -> presigned download URL

The client never sends file bytes through the API servers. It sends hashes, and only uploads the chunks the server does not already have.

Data model

namespaces   (ns_id PK, owner_id, kind)          -- a user's root, or one shared folder
journal      (ns_id, seq, path, rev, op, PRIMARY KEY (ns_id, seq))  -- append-only change log
files        (ns_id, path, latest_rev, deleted, PRIMARY KEY (ns_id, path))
file_versions(ns_id, path, rev, chunk_hashes, size, author_device, created_at,
              PRIMARY KEY (ns_id, path, rev))
chunks       (hash PK, size, storage_key, ref_count, created_at)
device_cursors(device_id, ns_id, last_seq)        -- where each device has synced to

A namespace is a unit of sharing: your home folder is one, and every shared folder is another. Each namespace has its own journal, an append-only log with a sequence number that only goes up. Every commit appends one row. A device's sync state is simply "the last seq I have applied, per namespace". If this sounds like the chat app's per-conversation sequence numbers, it is the same idea.

Shard all of these tables by ns_id. One namespace's journal and files then live on one shard, so a commit is a single-shard transaction and the journal order is easy to keep strict.

High-level design

Saving an edited file
LaptopMetadata svcObject storeNotifierPhonechunk + SHA-256 each chunkcommit_check(hashes)missing: 1 chunk + presigned URLPUT chunk ef2d12commit(parent_rev=41)ns7 changedlong poll returns: changesGET /changes?cursor=ns7:1180

The client watches the file system. When cut.mov changes, it splits the file into chunks and hashes each one locally.

1/8

The notification carries no data on purpose. If a notification is lost, the next poll or reconnect still pulls the delta from the cursor, so nothing is ever missed. The journal is the truth; notifications are just a hint to look.

Deep dive 1: chunking and deduplication

Splitting files into chunks gives you three things at once: resumable uploads (retry one chunk, not 50 GB), parallel transfers, and deduplication. Each chunk is named by its SHA-256 hash, so identical bytes always get the same name. If the server already stores a chunk with that hash, from an earlier version or from any other user, nobody uploads it again.

The simple scheme is fixed-size blocks, for example 4 MB. Dropbox has long used fixed 4 MB blocks. It works well for files that are edited in place: change a byte in the middle of a disk image and only one block changes.

It fails badly for insertions. Add one paragraph near the start of a file and every byte after it shifts. Every fixed block boundary now cuts the data in a different place, every block hash changes, and you upload the whole file again.

Content-defined chunking (CDC) fixes this by choosing boundaries from the content itself. A rolling hash runs over a small sliding window of bytes. Wherever the hash matches a pattern, for example its low 10 bits are all zero, you cut. An insertion only changes the windows near it, so boundaries further along stay at the same content, and those chunks keep their hashes. Minimum and maximum sizes stop chunks from getting tiny or huge. Restic, Borg, and many backup tools work this way, often with an algorithm called FastCDC.

Run this. It inserts 13 bytes near the start of a 64 KB file and counts how many chunks would have to be uploaded.

Pythonchunking.py
import hashlibimport random random.seed(7)GEAR = [random.getrandbits(32) for _ in range(256)] # one random number per byte value def fixed_chunks(data, size=1024): return [data[i:i + size] for i in range(0, len(data), size)] def cdc_chunks(data, mask=0x3FF, min_size=256, max_size=4096): # Gear rolling hash: each byte shifts the hash left, so only the last 32 bytes matter. chunks, start, h = [], 0, 0 for i, b in enumerate(data): h = ((h << 1) + GEAR[b]) & 0xFFFFFFFF size = i - start + 1 if (size >= min_size and (h & mask) == 0) or size >= max_size: chunks.append(data[start:i + 1]) start, h = i + 1, 0 if start < len(data): chunks.append(data[start:]) return chunks def hashes(chunks): return {hashlib.sha256(c).hexdigest() for c in chunks} original = bytes(random.getrandbits(8) for _ in range(64_000))edited = original[:100] + b"NEW PARAGRAPH" + original[100:] # insert near the start for name, split in [("fixed 1 KB", fixed_chunks), ("content-defined", cdc_chunks)]: before, after = hashes(split(original)), hashes(split(edited)) new = after - before print(f"{name:16} chunks={len(after):3} must upload={len(new):3}")
Output
Press Run (⌘ Enter) to see what happens.

Fixed chunks re-upload everything after the insert. Content-defined chunks re-upload one. The mask sets the average chunk size: 10 bits gives about 1 KB here; real systems use averages in the megabytes, because every chunk costs a metadata row and a hash in the version's chunk list.

Quick check
Why does content-defined chunking survive an insertion at the start of a file when fixed-size chunking does not?
Need a nudge? A hint rules out a wrong answer.
Predict the outputPython

What does this print?

import hashlib

files = {"a.txt": [b"x", b"y"], "b.txt": [b"y", b"z"], "c.txt": [b"x", b"y"]}
stored = set()
uploads = 0
for name, chunks in files.items():
  for c in chunks:
      h = hashlib.sha256(c).hexdigest()
      if h not in stored:
          stored.add(h)
          uploads += 1
print(uploads, len(files))
Need a nudge? Hints walk you through it.
Dedupe across users leaks information

Global deduplication means that if any user has a file, everyone else's upload of it is instant. That instant upload is a signal. An attacker who suspects you store a particular document can upload it and watch whether the server says "already have it". Worse, early systems let a client claim a hash and get the file back without ever proving it had the bytes, which turned the service into free file sharing for anyone who knew a hash.

Defenses: never grant access to a chunk just because a client knows its hash (the server must have seen this user upload it, or the client must prove it has the content), and consider deduplicating only within a user or an organization. End-to-end encryption with per-user keys rules out cross-user dedupe entirely, which is a product decision as much as a technical one.

Deep dive 2: the metadata service and the journal

The metadata service is where correctness lives. Chunks are immutable and named by content, so object storage never has update conflicts. All the hard questions, "what is the current version?", "what changed since I last looked?", "who can see this?", are metadata questions.

A commit is one transaction on the namespace's shard:

  1. Check the user has write access to the namespace.
  2. Check every chunk in the list exists in chunks.
  3. Check files.latest_rev still equals the client's parent_rev. If not, return 409.
  4. Insert the file_versions row, update files.latest_rev, and increment chunk reference counts.
  5. Append a journal row with the next seq for this namespace.

Step 3 is optimistic concurrency, a compare-and-set on the revision. It is what turns two offline edits into a detected conflict instead of a silent overwrite.

A device syncs by asking for journal entries after its cursor. A device that was off for a month just pulls a longer list. A brand-new device starts from cursor zero, or from a snapshot of files plus the current seq, which is faster for big namespaces.

For the push channel, you can use long polling or a WebSocket. Dropbox's public API uses long polling: the request hangs until something changes or a timeout passes, then the client calls the changes endpoint. Long polling is simple, passes through every proxy, and the server only needs to know which namespaces each connection cares about. A WebSocket, as in the chat app, saves the repeated request setup when changes are frequent. Either way the message is only "namespace changed", never the data.

Deep dive 3: conflicts and offline edits

Ada and Sam both open budget.xlsx at revision 41, then both go offline and edit it. Sam reconnects first and commits revision 42. Ada reconnects and commits with parent_rev = 41. The server sees latest_rev = 42 and refuses with 409.

The client now keeps both. It downloads revision 42 as budget.xlsx, and saves Ada's version beside it as budget (Ada's conflicted copy 2026-10-22).xlsx, then commits that as a new file. Nobody's work is lost, and a human decides what to merge.

Why not merge automatically? Most files are binary formats the sync engine does not understand. Merging two spreadsheets byte by byte, or even chunk by chunk, would produce a corrupt file or, worse, a valid-looking file with the wrong numbers. A silent wrong merge is far more harmful than an obvious duplicate. Apps that do merge, like Google Docs or Figma, do it inside the application with knowledge of the document structure, using operational transforms or CRDTs. That is a different product from file sync.

Put it in order5 steps

Order what happens when an offline device reconnects with a local edit.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Deep dive 4: saving bandwidth

Chunk-level dedupe is the biggest saving. Several smaller ones stack on top of it:

  • Delta sync inside a chunk. If a 4 MB chunk changed by a few bytes, an rsync-style binary diff against the old chunk can send kilobytes instead of megabytes.
  • Compression before upload for compressible types such as text and documents. Skip it for formats that are already compressed, like JPEG and MP4.
  • Resumable uploads. Each chunk is its own upload, so a dropped connection costs at most one chunk. For a 50 GB file this is the difference between a working product and an unusable one.
  • LAN sync. If your laptop and desktop are on the same network, the desktop can fetch chunks from the laptop directly. The server still decides which chunks are needed; only the transport changes.
  • Rate limiting and scheduling. Throttle background sync when the user is active, and wait for Wi-Fi on mobile for large files.

Bottlenecks, failures, and 10x scale

  • Hot shared folders. A company-wide folder with 50,000 members is one namespace on one shard. Every commit wakes 50,000 devices, which all pull the delta at once. Batch notifications for a short window, add jitter to the pulls, and serve the journal tail from a read replica or a cache, since recent entries are what everyone asks for.
  • Garbage collection. When versions expire from history, chunks lose references. You cannot delete a chunk the moment its ref_count hits zero: a client may be mid-commit with that exact hash after commit_check said it existed. Delete only chunks that have been unreferenced for a grace period, and make commit fail if a chunk vanished so the client re-uploads. Run a periodic mark-and-sweep audit as a safety net, because reference counts drift.
  • Durability. Object storage replicates or erasure-codes chunks across zones. Metadata uses synchronous replication within a region, because losing a committed revision means losing a user's file.
  • Encryption at rest. Encrypt each chunk with a data key that is itself encrypted by a key management service. Server-side encryption keeps dedupe working; client-side encryption with user-held keys does not.
  • 10x (25 EB of logical data): add metadata shards by namespace, which are independent; object storage scales by itself. At very large scale, storing billions of small objects gets expensive, so systems pack chunks into larger immutable files and keep an index of offsets.
Match the pairs0/5 matched

Match each problem to the mechanism that solves it.

Choose an item, then its match on the other side.
Key terms
content-defined chunking
Choosing chunk boundaries with a rolling hash over the data, so edits only change the chunks near them.
rolling hash
A hash over a sliding window of bytes that can be updated in constant time as the window moves one byte.
content addressing
Naming stored data by a hash of its contents, so identical data always has the same name and is stored once.
namespace
A unit of sharing and sharding, such as a user's home folder or one shared folder, with its own change journal.
journal cursor
The last journal sequence number a device has applied; syncing means fetching every entry after it.
conflicted copy
A second file the client creates when its edit lost a revision check, so neither edit is thrown away.
long polling
An HTTP request the server holds open until there is news or a timeout, used as a cheap push channel.