Cloud file storage like Dropbox, Google Drive or OneDrive looks like a folder that is magically the same on every device. Behind it, files are cut into chunks identified by their content hash, stored once in a durable block store, and described by a strongly consistent metadata database that records which chunks make up each version of each file. A sync protocol of change journals, cursors and long polling tells every device what changed, so editing one page of a 2 GB file uploads a few megabytes, not the whole file.
Think of it like
A LEGO model and its instruction booklet
Instead of shipping a finished LEGO castle to each friend, you ship the booklet: an ordered list of brick types. Every friend already owns most standard bricks, so you only mail the few unusual ones they lack. Changing a tower means a new page in the booklet and maybe two new bricks. The bricks are the block store (content-addressed, shared, never modified); the booklet is the metadata (small, versioned, and the only thing that has to be strictly consistent).
1. Requirements
Functional
- Upload, download, move, rename and delete files and folders
- Automatic sync across a user's devices, including edits made offline
- Version history and restore; deleted files recoverable for a period
- Share files and folders with people (view or edit) and by link
- Files up to tens of GB, with resumable uploads
Non-functional
- Durability first: never lose or corrupt a committed file (object-storage-grade, "eleven nines" class)
- Metadata must be strongly consistent: two devices must agree on what the latest version is
- Changes appear on other devices within seconds
- Bandwidth-efficient: transfer only what changed
- Scales to hundreds of millions of users and exabytes of data
| In scope | Out of scope |
|---|---|
| Chunking, dedup, block storage | Real-time co-editing inside a document (Google Docs style operational transforms) |
| Metadata, versions, sync protocol | Full-text search over file contents (see Search Systems) |
| Conflicts, sharing and permissions | Previews, thumbnails and media transcoding (mention as async workers) |
| Upload and download paths | Billing, quotas UI, admin consoles |
2. Back-of-the-envelope estimation
Assume 100 million users, 20 million daily actives, an average of 10 GB stored per user, and 10 file changes per active user per day. Chunks are 4 MB. See Back-of-the-Envelope Estimation.
Raw block storage
~1.1 EB
with dedup and erasure coding
Metadata commits
~7,000 /s
peak
Upload ingress
~37 Gbps
average, after dedup and delta
Idle connections
~40M
devices waiting for changes
3. API design
Uploads are a two-phase protocol: first make sure every chunk is in the block store, then atomically commit a new file version that references them. The commit is tiny and transactional; the chunk uploads are big, parallel and retryable.
POST /v1/blocks/check
{ "hashes": ["9f86d0...", "60303a...", "fd61a0...", "a4e624..."] }
-> 200 { "missing": ["fd61a0..."] }
PUT /v1/blocks/fd61a0... (raw bytes, 4 MB; server recomputes SHA-256 and rejects a mismatch)
-> 201 Created
POST /v1/files/commit
{
"path": "/Projects/report.docx",
"parentRev": 7,
"size": 14680064,
"blockList": ["9f86d0...", "60303a...", "fd61a0...", "a4e624..."]
}
-> 200 { "fileId": "f_9001", "rev": 8 }
-> 409 Conflict { "latestRev": 8, "reason": "parent_rev_mismatch" }GET /v1/changes/longpoll?cursor=ns42:1873&timeout=60
-> 200 { "changes": true } (or { "changes": false } after 60 s; reconnect)
GET /v1/changes?cursor=ns42:1873
-> 200 {
"entries": [
{ "path": "/Projects/report.docx", "rev": 8, "blockList": ["9f86d0...", "..."], "deleted": false }
],
"cursor": "ns42:1874",
"hasMore": false
}
GET /v1/blocks/fd61a0... (or a short-lived signed URL to object storage)- Hashes are identifiers, not permissions.
GET /v1/blocks/{hash}must check that the caller can read some file that references that block; otherwise anyone who learns a hash can download the content. parentRevmakes commits optimistic. The server accepts the commit only if the file's latest revision is still the one the client edited. See API Design: REST, GraphQL & gRPC.- Cursors are opaque positions in a change journal, so a device that was offline for a week asks for "everything after position 1873" and pages through it.
4. Data model
-- A namespace is a unit of sharing: a user's root folder or a shared folder.
CREATE TABLE namespaces (
namespace_id BIGINT PRIMARY KEY,
owner_id BIGINT NOT NULL,
kind VARCHAR(16) NOT NULL, -- 'root' or 'shared'
next_seq BIGINT NOT NULL DEFAULT 1 -- next position in this namespace's journal
);
CREATE TABLE file_entries (
namespace_id BIGINT NOT NULL,
file_id BIGINT NOT NULL,
parent_id BIGINT, -- containing folder; NULL at the namespace root
name VARCHAR(255) NOT NULL,
is_dir BOOLEAN NOT NULL,
latest_rev BIGINT NOT NULL,
deleted BOOLEAN NOT NULL DEFAULT FALSE,
PRIMARY KEY (namespace_id, file_id),
UNIQUE (namespace_id, parent_id, name)
);
CREATE TABLE revisions (
namespace_id BIGINT NOT NULL,
file_id BIGINT NOT NULL,
rev BIGINT NOT NULL,
size_bytes BIGINT NOT NULL,
block_list TEXT NOT NULL, -- ordered SHA-256 hashes (JSON array)
modified_by BIGINT NOT NULL,
created_at TIMESTAMP NOT NULL,
PRIMARY KEY (namespace_id, file_id, rev)
);
-- Append-only change log; (namespace_id, seq) is what a sync cursor points to.
CREATE TABLE journal (
namespace_id BIGINT NOT NULL,
seq BIGINT NOT NULL,
file_id BIGINT NOT NULL,
rev BIGINT NOT NULL,
PRIMARY KEY (namespace_id, seq)
);
CREATE TABLE memberships (
namespace_id BIGINT NOT NULL,
user_id BIGINT NOT NULL,
role VARCHAR(16) NOT NULL, -- 'owner' | 'editor' | 'viewer'
mount_path VARCHAR(1024), -- where the namespace appears in the user's tree
PRIMARY KEY (namespace_id, user_id)
);| Data | Store | Why |
|---|---|---|
| Namespaces, files, revisions, journal, memberships | Sharded relational DB (MySQL or Postgres), shard key namespace_id | Commits need transactions and unique constraints; everything a sync touches lives in one namespace, so one shard |
| Block index: hash → location, size | Distributed KV store, sharded by hash | Global dedup lookups by key, billions of rows, no joins |
| Block contents | Object storage with erasure coding | Immutable, content-addressed, cheap per byte; see Blob & Object Storage |
| Hot metadata (recent listings, memberships) | Cache | Listing a folder on every app open is read-heavy; see Caching |
5. High-level architecture
Clients talk to three stateless services: the metadata service (commits and listings), the block service (chunk upload and download) and the notification service (long polls). A committed change is published to a change stream that wakes up every device watching that namespace. Press play on a flow.
6. Deep dive: chunking and deduplication
Splitting files into chunks buys three things at once: resumable, parallel transfers (retry one 4 MB chunk, not a 20 GB file), delta sync (only changed chunks move) and deduplication (identical chunks are stored once). How you choose the chunk boundaries decides how well the last two work.
Fixed-size chunks
- Cut every 4 MB: trivial and fast
- In-place edits (databases, VM images, Office files rewriting a region) change only the touched chunks
- Inserting one byte near the start shifts every later boundary, so every chunk hash changes
- Used for simplicity in many sync products
Content-defined chunking (CDC)
- A rolling hash over a small window picks boundaries where the content matches a pattern
- An insertion changes only the chunks around it; boundaries after it resynchronize
- Variable sizes (enforce min and max), more CPU per byte
- Used by backup tools such as restic and Borg, and in LBFS-style sync research
Original: [AAAA][BBBB][CCCC][DDDD]
Fixed-size: [xxxA][AAAB][BBBC][CCCD][DDD] <- every chunk hash changes: re-upload everything
CDC: [xxxAAAA][BBBB][CCCC][DDDD] <- boundaries follow the content: 1 new chunk| Chunk size | Metadata per 1 GB file | Dedup and delta granularity | Transfer overhead |
|---|---|---|---|
| 256 KB | 4,096 hashes (~128 KB) | Excellent | Many small requests |
| 4 MB | 256 hashes (~8 KB) | Good | Balanced; a common choice (Dropbox has described 4 MB blocks) |
| 64 MB | 16 hashes | Poor: a small edit re-uploads 64 MB | Few large requests |
- Strong hashes only: SHA-256 makes accidental collisions practically impossible, so the hash can safely serve as the block's identity. A weak hash (CRC, MD5) would let two different chunks share an id.
- Verify on upload: the server recomputes the hash of every received chunk. A client must never be able to claim that arbitrary bytes belong to someone else's hash.
- Dedup scope is a privacy decision: global, cross-user dedup saves the most space, but an upload that completes instantly reveals that someone already stored that exact file. Per-user or per-team dedup avoids that side channel at some storage cost.
- Encryption interacts with dedup: encrypting each user's chunks with their own key defeats cross-user dedup. Convergent encryption (key derived from content) restores it but inherits the same confirmation-of-file risk.
7. Deep dive: the upload and download paths
At ~37 Gbps of ingress, pushing every byte through application servers is expensive. A common optimization is to let clients upload chunks directly to object storage with short-lived signed URLs, while the service keeps control of what gets committed.
- 1
Downloads mirror uploads
Fetch the block list from metadata, skip blocks already present locally (another file, an older version, a LAN peer), download the rest in parallel, verify hashes, reassemble into a temp file, then rename atomically.
- 2
Popular shared files
A file shared by link to thousands of people can be served through a Content Delivery Networks with signed, expiring URLs, because content-addressed blocks never change.
- 3
Garbage collection
Blocks are shared across files and versions, so deleting a file cannot delete its blocks. A periodic mark-and-sweep (or reference counts reconciled by a sweep) removes blocks no live revision references, after versions expire.
8. Deep dive: the sync protocol
Sync is a loop on every device: detect local changes and upload them, learn about remote changes and download them, and never confuse the two. The server side is simple because the journal gives every namespace a gap-free, ordered sequence of changes.
BEGIN;
-- Succeeds only if nobody committed since the revision the client edited (7).
UPDATE file_entries
SET latest_rev = 8
WHERE namespace_id = 42 AND file_id = 9001 AND latest_rev = 7;
-- 0 rows updated -> ROLLBACK and return 409 Conflict
INSERT INTO revisions (namespace_id, file_id, rev, size_bytes, block_list, modified_by, created_at)
VALUES (42, 9001, 8, 14680064, '["9f86d0...","60303a...","fd61a0...","a4e624..."]', 7, now());
-- Take the next journal position; the row lock orders commits within the namespace.
UPDATE namespaces SET next_seq = next_seq + 1 WHERE namespace_id = 42;
INSERT INTO journal (namespace_id, seq, file_id, rev)
SELECT 42, next_seq - 1, 9001, 8 FROM namespaces WHERE namespace_id = 42;
COMMIT;Short polling
- Ask "anything new?" every 30 s
- 40M devices → ~1.3M mostly empty requests per second
- Changes arrive up to 30 s late
Long polling
- Request stays open until a change or a timeout (~60 s)
- Plain HTTP: works through proxies and firewalls, easy to load balance
- Near-instant notification; Dropbox's public API offers a long-poll endpoint for exactly this
WebSocket or push
- Persistent bidirectional connection
- Lowest latency, but stateful servers and reconnection logic
- Mobile apps often rely on OS push (APNs, FCM) instead to save battery
Either way the notification carries no file data: it only says "your cursor is behind". The device then pulls the changes from the metadata service. Lost or duplicate notifications are harmless, because the cursor, not the notification, defines what the device has seen. See Real-time Communication.
9. Deep dive: conflicts and versions
- Optimistic concurrency, not locks: devices are often offline, so locking a file for editing would block other devices for hours. The
parentRevcheck detects conflicts at commit time instead. - Never auto-merge binaries: keep both versions and name the loser a conflicted copy. Text-aware merging belongs to collaborative editors, which are a different product.
- Every change is a revision: edits, renames and deletes append rows; nothing is overwritten. Restoring version 5 creates revision 9 that points at version 5's block list, which costs no bytes because the blocks still exist.
- Retention bounds cost: keep revisions for a plan-dependent window (for example 30 or 180 days), after which garbage collection can reclaim blocks only those revisions referenced.
- Tree conflicts are the tricky ones: one device renames a folder while another adds a file inside it, or deletes it. Using stable
file_ids withparent_id(instead of paths as keys) makes renames cheap and turns most of these into non-conflicts.
10. Deep dive: sharing and permissions
A shared folder is its own namespace with a membership list. Each member's tree mounts it at some path, so it appears like a normal folder. Because the journal is per namespace, a commit in a shared folder wakes every member's devices through one event.
| Concern | Design |
|---|---|
| Who can do what | memberships(namespace_id, user_id, role) with owner, editor and viewer roles checked on every metadata call |
| Block downloads | Allowed only if the caller can read a revision that references the block; signed URLs are issued after that check |
| Shared links | Random unguessable token mapped to (file or folder, permissions, expiry, optional password); revocable |
| Large company folders | A namespace with 100k members and millions of files becomes a hot shard; split it into sub-namespaces or give it a dedicated shard |
| Audit | Append-only access log for compliance and "who viewed this?" |
11. Delta sync beyond chunks
Chunk-level dedup is the main delta mechanism: an edit re-uploads only the chunks it touched. For large files with small edits, clients can go further with an rsync-style binary diff inside a chunk: the receiver sends cheap rolling checksums of fixed windows of its old copy, the sender finds matching windows in the new file and transmits only literal bytes plus references. Combined with compression and LAN sync (fetching blocks from a nearby device that already has them), most edits move kilobytes.
12. Scaling, bottlenecks and failure handling
- Metadata shards by namespace: keeps a commit and its journal in one transaction. Rebalance by moving whole namespaces. See Sharding & Partitioning.
- Notification fan-out: ~40M idle long polls need event-driven servers (epoll, async I/O) holding ~100k connections each, plus a routing layer that knows which server holds which namespace's waiters.
- Block store: erasure-coded across failure domains, with background scrubbing that rereads data and repairs bit rot before a second failure makes it unrecoverable.
- Upload storms: a new device's first sync can request millions of blocks; throttle per device and prioritize recently used files. See Rate Limiting.
- Async enrichment: thumbnails, previews, virus scanning and search indexing consume the change stream, so they never slow down a commit. See Message Queues & Pub/Sub.
| Failure | Effect | Handling |
|---|---|---|
| Upload interrupted at 60% | Some chunks stored, no commit | Resume: the dedup check reports only the missing chunks; orphans are garbage collected |
| Commit succeeds, response lost | Client unsure | Retry is idempotent: same block list and parentRev against rev 8 is recognized as already applied (or the client reads the latest rev first) |
| Notification server dies | Its long polls drop | Clients reconnect with their cursor; nothing is missed because the journal is the source of truth |
| Metadata shard failover | Brief write unavailability for its namespaces | Synchronous replica promotion; clients retry commits with backoff |
| Corrupted chunk on disk | Bad bytes on download | Hash check fails on the client; refetch from another fragment set; scrubbing repairs it |
Implementation
Streams the file so memory stays bounded, and returns the ordered list of chunk hashes that a commit references.
import hashlib
from dataclasses import dataclass
CHUNK = 4 * 1024 * 1024 # 4 MB
@dataclass(frozen=True)
class Block:
hash: str
offset: int
size: int
def block_list(path: str) -> list[Block]:
blocks: list[Block] = []
offset = 0
with open(path, "rb") as f:
while chunk := f.read(CHUNK): # buffered read returns a full chunk except at EOF
blocks.append(Block(hashlib.sha256(chunk).hexdigest(), offset, len(chunk)))
offset += len(chunk)
return blocks
def missing(local: list[Block], server_has: set[str]) -> list[Block]:
return [b for b in local if b.hash not in server_has]Key takeaways
- Split bytes from metadata: an immutable, content-addressed block store plus a small, transactional metadata database.
- Chunk files and identify chunks by SHA-256: this gives resumable uploads, delta sync and dedup with one mechanism.
- Content-defined chunking survives insertions; fixed-size chunking is simpler and fine for in-place edits.
- Commit new versions with optimistic concurrency (
parentRev), and turn conflicts into conflicted copies rather than silent overwrites. - A per-namespace journal plus cursors makes sync reliable; long-poll notifications are only hints to pull.
- Content hashes are not capabilities: authorize every block download against file permissions.
Common pitfalls
- Uploading whole files on every change instead of chunking, which wastes bandwidth and makes large uploads fragile.
- Using fixed-size chunks and expecting dedup to survive insertions near the start of a file.
- Pushing file data through notifications instead of treating them as hints and pulling from a durable journal.
- Deleting blocks when a file is deleted, breaking other files and versions that share them.
- Serving blocks to anyone who knows the hash, turning dedup into a data-leak channel.
Interview tips
- Estimate storage and metadata separately; the numbers show why they need different systems.
- Walk through an edit to one paragraph of a large file and show exactly which bytes move.
- Explain the conflict path concretely: two commits with the same parentRev, one wins, the other becomes a conflicted copy.
- Mention privacy trade-offs of global dedup; it shows depth beyond the happy path.
Real-world applications
- Dropbox has described 4 MB blocks identified by SHA-256, a metadata layer on sharded MySQL, a move of most block storage from Amazon S3 to its own system (Magic Pocket) around 2016, and a rewritten sync engine (Nucleus).
- Google Drive and Microsoft OneDrive offer desktop sync clients with versioning and conflict copies; OneDrive has described differential sync for Office files.
- restic and BorgBackup use content-defined chunking and content-addressed storage for deduplicated backups.
- rsync introduced the rolling-checksum delta algorithm that many sync tools still build on.
- Git stores content-addressed objects, the same idea at the scale of source files.
Test yourself
Why does content-defined chunking dedup better than fixed-size chunking after inserting a few bytes at the start of a file?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.