Skip to content

Design File Storage and Sync (Dropbox / Google Drive)

Advanced 93 min read Part 17 of 18

Design Dropbox or Google Drive: chunked presigned uploads, content-defined dedupe, a metadata journal, cursor sync with push, conflicts, versions and sharing.

The Problem#

Design a cloud file storage and sync service like Dropbox, Google Drive or OneDrive. A user drops a file into a folder on their laptop. Seconds later the same file appears on their phone and on their work desktop. They can open the web site from any computer and download it. They can share a folder with a colleague, and when the colleague edits a spreadsheet inside it, the change flows back to every device of both people. If the laptop is stolen, nothing is lost. If they delete a file by accident, they can get it back.

That sounds like "store files on a server". It is not. Four hard problems hide inside it:

  1. Big files over bad networks. A file can be 50 GB, a single video project or a disk image. Uploading it at home takes over an hour, and the Wi-Fi will drop at least once. The upload must survive that and resume, not start over.
  2. Sync is a distributed systems problem. Every device holds a full copy of the user's files and can change them while offline. The service must merge changes from many replicas into one consistent picture, tell every replica what changed, and do it for hundreds of millions of users.
  3. Efficiency at exabyte scale. Users save the same file again and again with tiny edits, and millions of users store the same popular files. Shipping and storing whole files every time would waste enormous bandwidth and disk. The system must send and store only what is new.
  4. Trust. People put their tax returns, medical records and company secrets here. Files must never be lost or silently corrupted, and must never be visible to the wrong person.

Analogy. Think of a shared photo album kept by a librarian. The pictures themselves sit in a huge vault in numbered sleeves, and nobody cares which album a sleeve belongs to. The librarian keeps a ledger: "Album 'Holiday', page 3 = sleeves 1182, 4471, 9020." When you change a page, you do not hand over the whole album. You hand over only the new sleeves and a new ledger line. Every friend who holds a copy of the album checks the ledger now and then ("anything new since line 5,000?") and fetches only the sleeves they do not already have. If two friends rewrite the same page at the same time, the librarian keeps both versions and asks a human to choose. That is the whole design. The vault is blob storage, sleeves are content-addressed chunks, the ledger is the metadata journal, "since line 5,000" is the sync cursor, and keeping both versions is conflict handling.

Dropbox and Google Drive started from different ends of this space. Dropbox began as a sync engine first: a desktop client that keeps a folder identical across machines, with the web as a secondary view. Google Drive began closer to a cloud document store: files live in the cloud, with rich collaborative editing for Google's own document formats and a desktop sync client added on. We will design for the Dropbox shape (a real folder on disk that must stay in sync) because it is the harder and more common interview question, and point out where Drive-style systems differ.

Clarifying Questions#

QuestionAssumed answerWhy it matters
Which features are core?Upload, download, share with other users and see files shared with you, automatic sync across devicesThese four drive the architecture
Is in-browser editing or preview in scope?No. Editing happens in local apps; collaborative document editing is a separate systemKeeps us out of real-time co-editing (OT and CRDTs)
How large can a file be?Up to 50 GBRules out single-request uploads; forces chunked, resumable transfer
Which clients?Desktop (Windows, macOS, Linux), mobile (iOS, Android), and webDesktop clients watch a folder; mobile is mostly on-demand; web cannot watch anything
How many users?About 500 million registered, 100 million daily activeSizes metadata, notification connections and storage
Is versioning in scope?Yes, at least 30 days of history and recovery of deleted filesChanges how we treat overwrites and deletes: nothing is destroyed in place
Consistency or availability?Availability. A file uploaded in Germany may take a few seconds to appear in the USLets us use asynchronous replication and eventual sync
How should conflicting edits be handled?Never lose data: keep both versions, let the user resolveRules out silent last-writer-wins on file content
Storage quotas, virus scanning, legal hold?Out of scope for the core design; mentioned at the endThey bolt on without changing the core
Do we design the blob store itself?No. We use an object store like S3; designing one is the Object Store case studyLets us focus on sync, metadata and transfer

Requirements#

Functional Requirements#

  • Upload a file of any size (up to 50 GB) from any device, with progress shown and the ability to pause and resume.
  • Download any file the user can access, from any device.
  • Share a file or folder with other users (by email) with a role such as viewer or editor, and list the files shared with you.
  • Sync automatically: a change made on one device (create, edit, rename, move, delete) appears on every other device of every user who can see that file.
  • Version history: list earlier versions of a file and restore one; recover deleted files within the retention window.

Below the line (out of scope): editing files in the browser, viewing without downloading (preview), per-user storage limits, virus and malware scanning, full-text search inside documents. We will touch on how each would plug in.

Non-Functional Requirements#

  • Highly available for reads and writes, preferring availability over strict consistency. A few seconds of staleness between devices is fine.
  • Durable and correct. Once the service says "uploaded", the bytes must never be lost or silently changed. We target eleven nines of annual durability for file data, inherited from the object store, and we verify every chunk by hash end to end.
  • Low latency sync. A small edit on one device should appear on other online devices within a few seconds (p99 under 10 seconds).
  • Fast transfer. Make full use of the user's bandwidth; never resend bytes the server already has.
  • Scales to hundreds of millions of users, hundreds of billions of files and exabytes of data.
  • Secure. Encryption in transit and at rest; strict per-file access control; links that leak do not stay useful for long.

A note on the availability choice, because candidates often get it backwards. You pick consistency over availability only when a stale read would break the product, as in a stock exchange where two buyers must not both get the last share. For file sync, a colleague in another country seeing your new file three seconds late is harmless. What we must not do is lose a write or corrupt a file. Those are durability and correctness properties, not CAP consistency, and we keep them even while choosing availability. The metadata for one folder still needs a single, ordered history (more on that later), but that ordering can be local to each folder rather than global.

Capacity Estimation#

We size five things: stored bytes, metadata, change rate, transfer bandwidth and open connections. The goal is not precision but knowing which part of the system is big. For the method, see Back-of-the-Envelope Estimation and Numbers Every Engineer Should Know.

Users. 500 million registered users, 100 million daily active. Each active user has on average two to three linked devices (a laptop, a phone, maybe a work desktop), so about 250 million devices are active on a typical day.

Stored bytes. Most users are on small free plans and store a few gigabytes; a minority of paying and business users store hundreds of gigabytes or terabytes. Take an average of 4 GB of logical data per registered user:

  • Logical data: 500 million x 4 GB = 2 EB (exabytes).
  • Version history adds maybe 10 to 20 percent (old versions are kept for 30 days or more, but most files are never edited, and old versions share most of their chunks with new ones).
  • Deduplication removes duplicates within a user's own files and, if we allow it, across users. Real savings depend heavily on the user base; assume 20 to 30 percent for planning, and treat any larger number as an upside, not something to bank on.
  • The object store adds redundancy: about 1.4 to 1.5 times with erasure coding, or 3 times with plain replication.

Net: on the order of 2 to 3 EB of raw disk. That is why storage cost per byte dominates the business and why Dropbox eventually built its own storage system rather than renting it (more on that in a deep dive). For our design we treat the blob store as given.

Files and metadata. Assume 1,000 files per registered user: 500 billion files. Each file has a metadata row (path or name, parent, size, hash, timestamps, owner, revision pointer) of roughly 300 bytes, plus a list of chunk hashes. With 4 MB chunks, the median file (well under 1 MB) has one chunk and a 1 GB file has 256 chunks; averaged over everything, the chunk list is a few hundred bytes. Keep two revisions per file on average for history. Then:

  • 500 billion files x 2 revisions x about 500 bytes = about 500 TB of metadata, before indexes and replication.

That cannot live on one database server. At 1 to 2 TB per shard, we need several hundred shards, and with three replicas each, over a thousand database machines. Metadata is a sharding problem from day one. See Partitioning and Sharding.

Change rate. Each daily active user changes about 20 files a day (saves, renames, new photos from a phone, a build tool rewriting files in a synced folder). That is:

  • 100 million x 20 = 2 billion file changes per day, about 23,000 per second on average and, with a daily peak around three times the mean, about 70,000 per second at peak.

Each change is one metadata transaction and one journal entry, plus a fan-out of notifications to the other devices that can see the file.

Upload bandwidth. Not every change uploads new bytes. Renames and moves upload nothing; edits upload only changed chunks; many new files are already known to the server. Assume an average of 500 KB of genuinely new bytes per change:

  • 2 billion x 500 KB = 1 PB of new data per day, about 11.6 GB/s, or roughly 93 Gbps average ingest and 250 to 300 Gbps at peak.

This all goes straight from clients to the object store. Our application servers never touch it, which is the single most important design choice in the whole system.

Download bandwidth. Each change is pulled by the other devices of the owner plus everyone the folder is shared with. With an average fan-out of three devices, sync egress is about 3 PB per day (around 280 Gbps average), plus web and mobile downloads. Some of that is served from a CDN for hot shared files; most sync downloads are cold, unique reads that go to the object store.

Notification connections. Desktop clients stay connected all day to hear about changes. If 150 million devices are online at peak, and each notification server holds about 200,000 mostly idle connections (a well-tuned epoll-based server can hold more, but we leave headroom for reconnect storms), we need about 750 notification servers.

The hidden cost of safety-net polling. If every online device also polls "anything new?" every 5 minutes as a safety net, that is 150 million / 300 seconds = 500,000 requests per second of mostly empty answers. That number is larger than the real change rate. It tells us the poll must be extremely cheap (compare a cursor with a cached folder head, no database query) or must be replaced by long polling. A surprising result like this is exactly what estimation is for.

A single large upload. A 50 GB file over a 100 Mbps uplink takes 50 x 8 / 0.1 = 4,000 seconds, about 1.1 hours. Over a typical 20 Mbps home uplink it takes about 5.5 hours. Hashing it on the client with SHA-256 runs at roughly 0.5 to 1.5 GB/s on a modern laptop with hardware SHA instructions, so 35 to 100 seconds of CPU before or during upload. Chunked into 8 MiB parts it is about 6,400 parts.

QuantityEstimateWhat it drives
Registered / daily active users500 M / 100 MAccount and session scale
Logical dataabout 2 EBObject store size and cost
Filesabout 500 billionMetadata sharding (hundreds of shards)
Metadataabout 500 TBSharded relational or KV metadata store
File changes23 K/s average, 70 K/s peakMetadata write path, journal, fan-out
New bytes ingestedabout 1 PB/day, 93 Gbps averageDirect-to-object-store upload
Sync egressabout 3 PB/dayObject store reads, CDN for hot files
Online devicesabout 150 M at peakAbout 750 notification servers
Safety-net polls at 5 minutesabout 500 K/sMust be a cache lookup, not a DB query
50 GB upload at 100 Mbpsabout 1.1 hoursChunked, resumable, parallel transfer

Core Entities#

Start with a short list and refine it as the design grows. These are the nouns the rest of the design talks about.

  • User: an account. Owns a root folder and is the subject of permission checks.
  • Device: one installed client (a laptop, a phone, a browser session). Each device keeps its own sync position, so the server can tell which changes each device has already seen.
  • File metadata (file entry): the name, parent folder, size, content hash, owner, timestamps and a pointer to the current revision. This is what users browse. It is small and lives in a database.
  • File content: the raw bytes. It is large and lives in blob storage, never in the database.
  • Chunk (block): a piece of file content, a few megabytes or less, identified by the hash of its bytes. A file's content is an ordered list of chunk hashes. Chunks make resumable upload, delta sync and deduplication possible.
  • Revision (version): an immutable snapshot of a file at one point in time: its chunk list, size, hash, who wrote it, from which device, and which revision it was based on. "Restore a version" means pointing the file at an older revision.
  • Namespace: a tree of files with its own ordered change history. Each user has a root namespace, and each shared folder is its own namespace mounted into the trees of everyone it is shared with. This one idea makes sharing and sync scale; we explain it in the high-level design.
  • Journal entry: one line in a namespace's ordered change log ("seq 5012: report.docx now at revision r9"). Devices sync by reading the journal from where they left off.
  • Share (access grant): who can see a namespace or file and with which role (viewer, editor, owner).
  • Upload session: the server-side record of an in-progress large upload: which chunks have arrived, which are missing.

In an interview you can start with just three (File, FileMetadata, User), as long as you say you will add chunks, revisions and namespaces as the design needs them. That is how we will build it.

API Design#

We start with a naive API and let it evolve. Say so out loud in an interview: "I will sketch simple endpoints and improve them as we go."

The first draft has one endpoint per functional requirement:

POST /files                       body: file bytes + metadata      -> FileMetadata
GET  /files/{fileId}                                               -> bytes + metadata
POST /files/{fileId}/share        body: { users: [email, ...] }    -> 200
GET  /files/changes?since={time}                                   -> ChangeEvent[]

A ChangeEvent carries the file id, the kind of change (created, updated, moved, deleted) and the new metadata. Every one of these four endpoints will change by the end of the high-level design: uploads and downloads stop carrying bytes, sharing moves to folders, and since={time} becomes an opaque cursor because clocks cannot be trusted for ordering.

Here is where it ends up. Control-plane calls go to our API; data-plane bytes go straight to blob storage or the CDN.

# Transfer (content-addressed chunks)
POST /v1/blocks/check        { hashes: [h1, h2, ...] }
     -> { missing: [h2], uploadUrls: { h2: "https://blob.../h2?sig=..." } }
PUT  <presigned upload URL>  body: chunk bytes      (to blob storage, not to us)
 
# Commit a new revision of a file
POST /v1/files/commit
     { namespaceId, path, parentRevision, blocks: [h1, h2, h3],
       size, contentHash, clientModifiedAt, deviceId }
     Idempotency-Key: 7f3c...
     -> 200 { fileId, revision, journalSeq }
     -> 409 { conflict: true, currentRevision }
 
# Very large single-object uploads (multipart)
POST  /v1/uploads                      { fingerprint, size, name, parentId }
      -> { uploadId, partSize, partUrls: [ { partNumber, url } ] }
PATCH /v1/uploads/{uploadId}/parts     { partNumber, etag }
POST  /v1/uploads/{uploadId}/complete  -> FileMetadata
 
# Download
GET  /v1/files/{fileId}/content        -> { blocks: [ { hash, url } ] } or a signed CDN URL
 
# Sync
GET  /v1/changes?namespaceId=..&cursor=..   -> { entries: [...], cursor, hasMore }
GET  /v1/changes/longpoll?cursor=..         -> { changes: true|false, backoffSeconds }
 
# Sharing and history
POST /v1/shares                 { itemId, grants: [ { email, role } ] }
GET  /v1/shared-with-me?cursor=..
GET  /v1/files/{fileId}/revisions
POST /v1/files/{fileId}/restore { revision }

Four details in this API matter more than they look:

  • Identity comes from the token, never the body. The server learns who is calling from a validated session token or JWT, not from a userId field or header the client could forge. Every call then checks that this user may touch this file. See Authentication and Authorization.
  • Commits carry parentRevision. The client says "I edited revision r8". If the server's current revision is still r8, the commit succeeds; if someone else already committed r9, the server returns 409 and the client handles a conflict. This is optimistic concurrency control, and it is how we avoid silently losing edits.
  • Commits are idempotent. A laptop that commits, loses the response and retries must not create two revisions. The idempotency key (or the tuple of device, parent revision and content hash) lets the server return the first result again. See Idempotency and Safe Retries.
  • The cursor is opaque. Clients never parse it. The server can encode a namespace id and sequence number today and change the format tomorrow without breaking old clients. See API Design Best Practices.

High-Level Design#

We build the design one functional requirement at a time, then use the non-functional requirements to drive the deep dives.

1. Users can upload a file from any device#

Storing a file means answering two separate questions: where do the bytes go, and where does the metadata go?

Metadata is small, structured and queried constantly ("list this folder", "what changed since cursor X", "who can see this file"). It belongs in a database. In the simplest version, one document per file is enough:

{ "id": "f_123", "name": "report.docx", "size": 48213,
  "mimeType": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  "ownerId": "u_1", "parentId": "d_77", "status": "uploaded",
  "createdAt": "2026-03-02T10:15:00Z" }

A key-value or document store such as DynamoDB fits the "fetch files by owner and folder" access pattern well, and a relational database such as PostgreSQL or MySQL fits equally well, with the bonus of transactions across rows. Do not burn interview time on this choice early; both work at the start. It becomes interesting later, when we need an ordered change journal per folder and atomic moves, and we will revisit it in the metadata deep dive. See Choosing a Database: A Decision Guide.

Bytes are where the real choice is.

Bad: upload to a file server's local disk

The client POSTs the whole file to our File Service, which writes it to its own disk and saves the metadata row. This works for a hobby project and fails at once at scale. Disks fill up, so we must keep adding servers and somehow route each download to the server that holds the file. If that server dies, its files are unavailable, and if its disk dies, they are gone. We would be building a distributed storage system by accident.

Good: the File Service writes the bytes to blob storage

The client still sends the file to our service, but the service streams it into an object store such as Amazon S3, Google Cloud Storage or Azure Blob Storage, and writes the metadata row. The object store gives us practically unlimited capacity, very high durability (S3 is designed for eleven nines) and features we will use later: lifecycle rules, versioning and server-side encryption. See Object Storage and Blob Storage.

Two problems remain. First, the bytes travel twice: client to our server, our server to blob storage. That doubles bandwidth cost, adds latency and makes our stateless API servers hold long-lived, memory-hungry connections for hour-long uploads. Second, two stores must agree. If the blob write succeeds and the database write fails, we leak an orphan object. If the metadata is written first and the upload fails, users see a file that cannot be downloaded. We fix the second problem with a status field ("uploading", then "uploaded") and a cleanup job; we fix the first by removing ourselves from the data path.

Great: the client uploads directly to blob storage with a presigned URL

A presigned URL is an ordinary HTTPS URL for one specific object, with a cryptographic signature and an expiry time in its query string. Whoever holds it can perform exactly one kind of operation (here, a PUT of that object) until it expires, without having any cloud credentials of their own. Generating one is a purely local computation: the File Service signs the URL with its own credentials using HMAC (for S3, Signature Version 4). No network call to S3 is made, so issuing thousands per second is cheap.

The upload becomes three steps:

  1. The client asks our File Service for an upload URL, sending the metadata. The service checks permission, writes a metadata row with status uploading, and returns a presigned URL that expires in, say, 15 minutes.
  2. The client PUTs the bytes directly to blob storage using that URL. Our servers never see the bytes.
  3. Blob storage tells us the object exists. With S3 this is an event notification (to a queue such as SQS, or to a function) when the object is created; the File Service consumes it and flips the status to uploaded. As a belt-and-braces measure the client also calls "complete", and the service confirms with a HEAD request on the object before trusting either signal.

The metadata row in state uploading is also our defence against orphans in the other direction. A periodic sweeper finds rows stuck in uploading for more than a day, checks whether the object exists, and either completes or deletes them. Object-store lifecycle rules delete abandoned partial uploads. Together these give us eventual agreement between the two stores without a distributed transaction. For the general pattern, see Pattern: Handling Large Files and Blobs.

This simple single-PUT version does not yet handle a 50 GB file: a single PUT to S3 is capped at 5 GB, and an hour-long single request will not survive a flaky network. We fix that with chunking in the first deep dive.

2. Users can download a file from any device#

Bad: download through the File Service

The service reads the object from blob storage and streams it to the client. As with uploads, every byte crosses our servers twice, and a server busy streaming a 50 GB file is a server not answering API calls.

Good: presigned download URL to blob storage

The client calls GET /v1/files/{fileId}/content. The service checks that the caller can read the file and returns a presigned GET URL valid for a few minutes. The client downloads straight from blob storage. HTTP Range requests come for free, so a client can download a large file in several parallel byte ranges or resume an interrupted download from the last byte it received.

The remaining weakness is geography. The bucket lives in one region. A user in Sydney downloading from a bucket in Virginia pays roughly 200 ms of round-trip time on every TCP and TLS handshake and every congestion-window ramp-up, which caps throughput on long fat paths.

Great: download through a CDN with signed URLs

A content delivery network is a fleet of edge servers around the world that cache content close to users. The client gets a CDN signed URL instead of a bucket URL. The edge nearest to the user serves it; on a cache miss the edge fetches from the bucket (through a regional shield cache), stores it, and serves later requests locally. Even on a miss, the user benefits: their TCP connection terminates at a nearby edge, and the edge reuses warm, long-lived connections back to the origin.

Signed URLs work at the CDN the same way they work at the bucket. With CloudFront, for example, our service signs the URL path and expiry with a private key, the CDN holds the matching public key, and each edge verifies the signature and expiry before serving. See Content Delivery Networks (CDN).

CDNs cost money per gigabyte, and most files in a sync product are read only by their owner's other devices, once. Caching those at the edge wastes cache space. So we are selective: hot shared files (a file shared by link with thousands of people, a popular public download) get long cache lifetimes via Cache-Control, while ordinary private sync traffic goes straight to blob storage or through the CDN with a short or zero TTL. When a file is overwritten, the new revision has new content and therefore a new URL, so we rarely need to invalidate anything. Immutable, content-addressed objects are a gift to caches. See Cache Eviction and Invalidation.

3. Users can share files and see what is shared with them#

Sharing works like Google Drive: type a colleague's email, pick a role, and the file shows up in their "Shared with me" list. The interesting question is not how to record a share, but how to make the two common reads fast: "can this user open this file?" and "list everything shared with me".

Bad: a share list inside the file's metadata

Add an array of user ids to the file document: "sharedWith": ["u_2", "u_3"]. Checking access on download is easy, since the list is right there. But "show me everything shared with me" is now a scan: we would have to look inside the share list of every file in the system to find the ones that mention this user. With 500 billion files, that is not a query, it is a batch job.

Good: also keep the inverse mapping

Keep the share list on the file, and also store the inverse: a mapping from each user to the files shared with them, such as u_2 -> [f_123, f_456], in a cache or a second table. Now both reads are single lookups. The cost is that two copies of the same fact must stay in sync. If they live in the same database, update both in one transaction. If the inverse lives in a separate cache, it can drift, and we need a rebuild path.

Great: a separate, normalised shares table

Drop the embedded list entirely and store each grant as a row:

userId (partition key)itemId (sort key)rolegrantedBygrantedAt
u_2f_123editoru_12026-03-02
u_2d_456vieweru_92026-02-11
u_3f_123vieweru_12026-03-02

The composite key (userId, itemId) makes "everything shared with u_2" a single partition range read, and "can u_2 open f_123" a single point read. In DynamoDB that is a partition key plus sort key; in SQL it is a composite primary key. A secondary index on itemId answers "who has access to this file" for the sharing dialog. A range read is a hair slower than reading one cache entry, but there is only one source of truth, so nothing drifts.

From shared files to shared folders: namespaces

Real users mostly share folders, not files, and a shared folder brings a problem the table above does not solve. Suppose Alice shares a folder of 10,000 files with a team of 50 people. If grants are per file, sharing writes 500,000 rows, and every new file added to the folder needs 50 more. Worse, sync: when Bob adds a file to the folder, the change must appear in 50 people's change feeds.

The fix, used by Dropbox and by most serious sync systems in some form, is to make a shared folder its own namespace: a self-contained tree with its own change journal. Alice's root namespace contains a mount point that says "the namespace ns_team appears here as /Team". Every member's root namespace has a similar mount point, possibly under a different name or path. Then:

  • Sharing the folder writes one grant per member (member to ns_team), not one per file.
  • A change inside the folder is written once, to ns_team's journal. Each member's device follows the journals of every namespace it has mounted, so they all see it.
  • Access checks become "is this user a member of this namespace, with what role?", a small, highly cacheable fact.

We go deeper into roles, inheritance, link sharing and revocation in the sharing deep dive.

4. Files sync automatically across devices#

Every device keeps a full local copy of the files (or, on mobile and in "online-only" mode, placeholders it can fill on demand), and the server holds the authoritative copy. Sync runs in two directions.

Local to remote. A sync agent on the desktop watches the synced folder using the operating system's change notifications: inotify on Linux, FSEvents on macOS and ReadDirectoryChangesW on Windows (which .NET exposes as FileSystemWatcher). When a file changes, the agent waits for writes to settle (editors often write a temporary file and rename it over the original), queues the file, splits it into chunks, uploads only the chunks the server does not have, and commits a new revision with the parent revision it started from. Because the server is the source of truth, the agent tries to commit soon, so other devices can learn about the change quickly.

Remote to local. Each device must learn when something changes on the server. There are three ways to hear about it. For the background on each transport, see Polling, Long Polling, SSE, WebSockets and Webhooks.

  • Polling. Every N seconds the client asks "anything new since my cursor?". Simple and robust, but it detects changes late (on average after N/2 seconds) and, as the estimate showed, millions of devices polling generate enormous amounts of empty work.
  • Push over a persistent connection. The client holds one WebSocket or SSE connection per device (not per file) and the server pushes a notification when any namespace the user can see changes. Changes arrive within a second. But connections drop silently (laptops sleep, phones change networks, NAT boxes expire idle flows), and a notification sent into a dead connection is lost.
  • Hybrid: push for speed, pull for truth. Use push notifications as a hint ("namespace ns_team has new entries") and the change feed as the truth. On any hint, the client fetches GET /v1/changes?cursor=... to get the actual entries. The client also polls the change feed every few minutes as a safety net, and always on reconnect. A lost notification therefore delays a change by at most one polling interval; it never loses it.

The crucial point is that the notification carries no data the client depends on. It says "go look", and the cursor-based change feed is the only place the client learns what changed. That makes the system tolerant of duplicate, reordered and dropped notifications. Dropbox's public API has exactly this shape: a cursor-based list_folder/continue call, plus a list_folder/longpoll call that blocks until something changes and then returns changes: true with no details. See Pattern: Pushing Realtime Updates.

The full high-level design#

Putting the four requirements together gives the design below. It separates a control plane (metadata, permissions, journals, notifications) that our services own, from a data plane (chunk bytes) that flows directly between clients and blob storage. To keep the diagram readable we draw it in two halves.

The control plane:

The data plane and background work:

Components:

  • Clients. The desktop client is a full sync engine: file watcher, local metadata database, chunker, hasher, upload and download queues, conflict handling. Mobile clients are lighter and mostly fetch on demand. The web client lists, uploads and downloads but does not sync a folder. See Client, Mobile and Frontend Considerations.
  • LB and API gateway. TLS termination, authentication, rate limiting, request validation and routing. Note the payload limits of managed gateways (Amazon API Gateway caps requests at 10 MB), another reason bytes must never pass through here. See API Gateway and Backend-for-Frontend and Rate Limiting and Throttling.
  • Metadata Service. Stateless. Commits revisions with optimistic concurrency, appends journal entries, serves folder listings and the change feed, and answers permission checks. It is the heart of the system.
  • Block Service. Stateless. Given a list of chunk hashes, says which are missing, issues presigned upload and download URLs, verifies uploaded chunks, and maintains the chunk index. It never touches chunk bytes on the normal path.
  • Sharing Service. Manages namespace memberships, roles and shared links; writes into the metadata DB.
  • Metadata DB. Sharded by namespace. Holds file entries, revisions, journals, memberships and upload sessions. Strongly consistent within a shard, so each namespace has a single ordered history.
  • Chunk index. Maps chunk hash to storage location, size and reference count. Huge (one row per unique chunk) and read on every upload; a sharded key-value store.
  • Cache. Namespace head sequence numbers, membership lists and hot folder listings, so that the 500,000-per-second safety-net polls and permission checks rarely hit the database. See Caching Fundamentals.
  • Change bus. A log such as Kafka carrying "namespace X advanced to seq N" events from the Metadata Service to notification servers and background workers. See Apache Kafka in Practice.
  • Notification Service. Holds one long-lived connection per online device and pushes hints. Stateful only in the sense of holding sockets; a device can reconnect to any server.
  • Blob storage. Stores chunks as immutable objects keyed by hash. S3 or an in-house store. Encryption at rest, cross-region redundancy.
  • CDN. Caches hot shared content close to users; validates signed URLs at the edge.
  • Background workers. Garbage collection of unreferenced chunks, periodic re-verification of stored chunks, thumbnail and preview generation, search indexing, abandoned-upload cleanup.

Key Flows#

Flow 1: Saving an edited file (chunk, dedupe, upload, commit)#

Alice edits a 40 MB presentation on her laptop and presses save. Only one slide changed.

Step by step:

  1. The agent receives a file-system event, waits briefly for the save to finish, and confirms the file actually changed (size, modification time, then hash).
  2. It splits the file into chunks and hashes each one. Ten of the eleven hashes match chunks of the previous revision, so the agent already knows they are on the server; it still sends all eleven to the Block Service, which answers with the one that is missing.
  3. The agent uploads only chunk h7, a few megabytes instead of 40 MB, straight to blob storage.
  4. It commits revision r9, naming r8 as the parent. The Metadata Service verifies that every chunk in the list exists (never trust the client's claim), then, in one database transaction on the namespace's shard, checks the current revision is still r8, writes r9 and appends the next journal sequence number.
  5. After commit, it publishes a small event: "namespace advanced to 5013". It does not wait for anybody to receive it.

If the response to the commit is lost, the agent retries with the same idempotency key and gets the same r9 back. If someone else committed in between, step 4 returns 409, and Flow 4 below takes over.

Flow 2: Another device learns about the change#

Alice's desktop at work and her colleague Bob's laptop both mount the namespace.

Notes:

  • The hint carries only the namespace id. If it is lost, Bob's next safety-net poll or reconnect finds the same entries.
  • Bob's client reconstructs the file from chunks it already has (from r8) plus the one new chunk. It writes to a temporary file and renames it over the old one, so an application that has the file open never sees a half-written file.
  • The client saves the new cursor only after the file is safely on disk. If it crashes in the middle, it replays from 5012 and the operation is idempotent.

Flow 3: Uploading a 50 GB file with pause and resume#

The session is found again by the content fingerprint, not by the file name, and the server rebuilds the truth about which parts exist from the object store's ListParts, not from the client's memory. We dissect this in the first deep dive.

Flow 4: Two devices edit the same file#

Alice (laptop, offline on a plane) and Bob (desktop) both edit budget.xlsx, revision r4.

Nothing is lost: Bob's version keeps the original name, Alice's version is saved next to it as a clearly labelled conflicted copy, and both people see both files on every device. The conflict deep dive explains why this is the right default and when you can do better.

Data Model#

The data splits into two worlds with very different shapes. The namespace side (users, namespaces, file entries, revisions, journals, memberships) is relational, transactional and accessed per namespace. The chunk side (the chunk index and upload sessions) is a giant key-value map accessed by hash. We draw them in three diagrams.

Users, devices and sharing:

Each user owns exactly one root namespace (root_ns_id); shared folders are further namespaces reached through membership rows.

Files, revisions and the journal inside a namespace:

The chunk side:

TableKeyStore and shardMain queries
user, deviceuser_id, device_idSmall relational table, sharded by user_idLogin, device list
namespacens_idMetadata DB, shard = hash of ns_idHead sequence for a namespace
membership(ns_id, user_id) plus index on user_idMetadata DB; copy by user for "my namespaces"Access check, list members, list my mounts
file_entry(ns_id, file_id), index (ns_id, parent_id, name)Metadata DB, same shard as its namespaceList folder, resolve path, rename and move
revision(file_id, rev_id)Same shard as the fileCurrent revision, version history, restore
revision_block(rev_id, position)Same shard, or packed as an array inside revisionBlock list of a revision
journal(ns_id, seq)Same shard as the namespaceChanges since cursor
chunkchunk_hashSharded KV store (hash is already uniformly random)Does it exist, where, refcount
upload_session, upload_partupload_id, (upload_id, part_number)KV store with TTL, index on (user_id, fingerprint)Resume an upload

Key decisions:

  • Shard the metadata by namespace, and keep everything for one namespace on one shard. File entries, revisions and the journal of a namespace live together, so committing a revision and appending to the journal is a single-shard transaction. No two-phase commit on the hot path. A root namespace is one user's private files; a shared namespace is one shared folder. Both are naturally bounded, which makes them good shard keys. The exceptions (one enormous company-wide shared folder) are handled by splitting the namespace, discussed in the metadata deep dive.
  • The journal is the sync protocol. (ns_id, seq) is a dense, gap-free, strictly increasing sequence per namespace, assigned inside the commit transaction. A device's cursor is simply "for each namespace I mount, the last seq I have applied". The change feed is a range scan WHERE ns_id = ? AND seq > ?.
  • Revisions are immutable. A save creates a new revision row; it never updates the old one. The file entry's current_rev pointer moves. Version history and restore fall out of this for free.
  • Chunks are content-addressed. The key is the SHA-256 of the chunk bytes. The same bytes always get the same key, so deduplication is a lookup, and any corruption is detectable by re-hashing.
  • Deletes are tombstones. deleted = true plus a journal entry, so other devices learn of the delete through the same feed. The rows are purged after the retention window.

A commit, in SQL against the namespace's shard, looks like this:

BEGIN;
-- optimistic concurrency: fail if someone else committed first
SELECT current_rev FROM file_entry
 WHERE ns_id = $ns AND file_id = $file FOR UPDATE;
-- application checks current_rev = $parent_rev, else ROLLBACK and return 409
 
INSERT INTO revision (file_id, rev_id, parent_rev, size, content_hash, device_id, server_time)
VALUES ($file, $new_rev, $parent_rev, $size, $hash, $device, now());
 
UPDATE file_entry SET current_rev = $new_rev WHERE ns_id = $ns AND file_id = $file;
 
UPDATE namespace SET head_seq = head_seq + 1 WHERE ns_id = $ns RETURNING head_seq;
INSERT INTO journal (ns_id, seq, file_id, op, rev_id)
VALUES ($ns, $head_seq, $file, 'update', $new_rev);
COMMIT;

Locking the namespace row to bump head_seq serialises commits within one namespace. That is intentional: it gives each namespace a total order. It also caps a single namespace at a few thousand commits per second on one primary, which is plenty for a folder and is the reason giant namespaces need splitting. For how to choose engines for each half, see Choosing a Database: A Decision Guide, Data Modeling and Database Indexing.

Deep Dives#

1. Large files: chunked, resumable, verified uploads#

Start from the user's experience, because it dictates the design. Uploading a 50 GB file takes an hour or more. The user needs two things: a progress indicator that is honest about how far along it is, and resumability, so that a dropped connection or a closed laptop at 49 GB does not mean starting again. This is the core of the problem, and in a real interview it is where the most time goes.

First, be precise about why one big request fails:

  • Timeouts. Clients, load balancers and servers all have idle and total timeouts. A single request that runs for 4,000 seconds at 100 Mbps (and several hours on a slower uplink) will hit one of them.
  • Size limits. Browsers and servers cap request bodies. Self-managed NGINX or Apache can be configured to accept huge bodies, but managed front doors often have hard limits; Amazon API Gateway is 10 MB. S3 itself accepts at most 5 GB in a single PUT.
  • Interruptions. Over an hour, a home or mobile connection will almost certainly blip. With one request, a blip means restarting from byte zero.
  • No progress signal. The user stares at a spinner with no idea whether anything is happening.

Chunking fixes all four: split the file into pieces and upload them independently, in parallel when bandwidth allows. The split must happen on the client. A very common mistake is to chunk on the server, which is pointless, because the whole file has already crossed the network in one piece to reach the server. Typical chunk sizes are 5 to 10 MB for multipart uploads, tuned by network conditions and file size. Progress becomes trivial: bytes in completed chunks divided by total bytes.

A sizing trap. S3 multipart uploads allow at most 10,000 parts, each between 5 MiB and 5 GiB (the last part may be smaller). A 50 GiB file in 5 MiB parts would need 10,240 parts: over the limit. So the part size must scale with the file: partSize = max(8 MiB, ceil(fileSize / 9,000)) leaves headroom. 8 MiB parts give 6,400 parts for 50 GiB; a 5 TiB object would need parts of at least about 525 MiB. Other providers have similar but different limits; check them rather than assuming.

To resume, someone must remember which chunks are done. We keep an upload session on the server, with a status per part:

{ "uploadId": "up_9f2", "fileId": "f_123", "fingerprint": "sha256:5be1...",
  "size": 53687091200, "partSize": 8388608, "status": "uploading",
  "parts": [ { "n": 1, "status": "uploaded", "etag": "a1b2..." },
             { "n": 2, "status": "uploading" },
             { "n": 3, "status": "pending" } ] }

The question is how that record stays truthful.

Good: the client reports each finished part

The client uploads a part directly to blob storage, gets 200 OK, then sends PATCH /v1/uploads/{id}/parts to mark it uploaded. Simple, and it gives instant progress. But it trusts the client. A buggy or malicious client can mark parts done that never arrived. The damage is mostly limited to that user's own file, which would be corrupt on download, but corrupt state is miserable to debug, and "upload complete" should mean something.

Great: trust, but verify on the server

S3 event notifications fire only when a whole multipart upload completes, not per part, so the server cannot simply listen for parts. Instead:

  • Each successful part upload returns an ETag, an identifier of the stored part. The client includes it in its PATCH. That keeps progress real time.
  • Before marking the file uploaded, and whenever a client resumes, the server calls ListParts for the upload id. The object store returns every part it actually holds, with ETags and sizes, in one call. The server reconciles its session record against that list.
  • Only then does the server call CompleteMultipartUpload with the ordered list of part numbers and ETags. The store assembles the parts into one object. Only after it confirms does the session become uploaded and the file revision get committed.

For integrity, rely on explicit checksums rather than ETag semantics. ETags of multipart objects are not simple MD5s of the content, and their format varies with encryption settings. S3 and other stores let the client send a checksum (such as CRC32C or SHA-256) with each part and verify it on arrival; use that, and keep your own SHA-256 fingerprint for the whole file.

Identifying a file to resume: fingerprints

When an upload restarts, two questions come first: have I tried to upload this file before, and if so, which chunks are already there? The file name cannot answer the first, because names collide and change. We use a fingerprint: a cryptographic hash (SHA-256) of the content. The same content always gives the same fingerprint, whatever the file is called.

Keep two identifiers apart:

  • The file id (a UUID or similar) identifies a file entry in a folder. Two users who upload the same PDF have two file ids.
  • The fingerprint identifies the content. Both uploads above have the same fingerprint. It is stored as a field and used for resumption and deduplication.

We also fingerprint each chunk, which lets us say exactly which parts were sent, detect corruption per part, and, as the next deep dive shows, skip chunks the server already has.

The full large-file flow is therefore:

  1. The client splits the file into parts (8 MiB here) and computes a fingerprint per part and for the whole file. For huge files, hashing can run in a streaming fashion, so the upload starts before the whole-file hash is known; in that case, resumption keys off a client-generated upload id persisted locally, plus the per-part hashes.
  2. It asks the server whether an upload session exists for this user and fingerprint. If one exists in state uploading, it fetches the list of parts the server has verified.
  3. If not, it starts a session. The server calls CreateMultipartUpload, stores the session as uploading, and returns the upload id and presigned URLs for the parts. Each part needs its own presigned URL that embeds the upload id and part number. Issue them in batches of a few hundred with short expiry rather than all 6,400 at once.
  4. The client uploads parts in parallel (four to eight at a time on a typical connection), retries failures with backoff, and reports ETags.
  5. When all parts are present, the server verifies with ListParts, calls CompleteMultipartUpload, then marks the file uploaded and commits the revision.
  6. Throughout, the client drives the progress bar from completed bytes.

Two cleanup rules complete the design. An abandoned multipart upload keeps its parts (and bills for them) forever unless aborted, so set a bucket lifecycle rule that aborts incomplete multipart uploads after a few days. And upload sessions themselves carry a TTL in the metadata store.

The multipart upload API is a ready-made implementation of all this, and SDKs (such as the AWS SDK's managed upload) will split, parallelise and retry for you. Saying "I would use multipart upload" shows hands-on experience. It does not replace being able to explain how it works, because that is what the interviewer wants to hear.

Do chunked uploads need chunked downloads? No. After CompleteMultipartUpload, the object is an ordinary single object. A client downloads it with one presigned or CDN URL, and for big files uses HTTP Range requests to fetch byte ranges in parallel or to resume an interrupted download. The client does not need to know where the upload part boundaries were.

An alternative that sync engines prefer: store chunks, not files

Multipart upload produces one object per file revision. That is ideal for the "upload a big file" requirement, but it wastes bandwidth and storage for sync: change one byte of a 2 GB file and you upload a new 2 GB object. Production sync systems therefore usually store each chunk as its own content-addressed object and describe a file revision as a list of chunk hashes, the design in our high-level diagram. Dropbox has publicly documented that its API's content hash is computed over 4 MB blocks: SHA-256 each block, concatenate the block hashes, SHA-256 the result, which reflects this block-based design.

With per-chunk objects:

  • Resumption is automatic. Each chunk is a tiny independent upload. "Resume" is just "ask which hashes are missing", with no session state to lose.
  • Delta sync is automatic. An edit uploads only new chunks.
  • Deduplication is automatic. A chunk that exists is never uploaded again.
  • Downloads assemble. Desktop and mobile clients fetch chunks and write them in order. A web browser cannot easily do that for a 50 GB file, so web downloads go through a stateless download proxy that streams the chunks in order as one HTTP response and maps Range requests onto chunk offsets. This is the one place our infrastructure carries bytes, and it scales horizontally like any stateless streaming service.

The cost is many more objects (a few hundred billion chunks), more per-request charges on a cloud object store, and a chunk index to maintain, with reference counting and garbage collection. Many teams use both: per-chunk storage for synced files, multipart single objects for huge one-off uploads such as backups and media archives.

2. Making upload, download and sync fast#

Bandwidth is a fixed pipe. We cannot widen it, but we can fill it well and send less through it. Each technique below is either "fill the pipe" or "send fewer bytes".

Fill the pipe: parallelism and adaptive chunks. One TCP connection rarely saturates a long, fast path, because its congestion window grows slowly and every loss halves it. Uploading four to eight chunks concurrently over separate connections (or multiplexed HTTP/2 streams with care) keeps the pipe full. Adapt the parallelism and chunk size to measured throughput: smaller chunks and fewer streams on a flaky mobile link, where a lost chunk is cheap to retry; larger chunks and more streams on a fast stable link, where per-request overhead dominates. See TCP vs UDP (and QUIC).

Send fewer bytes: delta sync. When a file changes, only changed chunks travel. A 40 MB presentation with one changed slide uploads one chunk. This works only if an edit changes few chunks, which leads to the most important subtlety in the whole design.

The boundary-shift problem. With fixed-size chunks (every 4 MB), inserting one byte near the start of a file shifts every later byte by one position. Every chunk boundary after the edit lands somewhere new, every later chunk's contents change, and every later chunk hash changes. A one-byte insert re-uploads the whole file. Delta sync collapses to full upload for any edit that is not an in-place overwrite.

Content-defined chunking (CDC) fixes this by choosing boundaries based on the content rather than on the offset. Slide a small window (say 48 bytes) across the file and compute a rolling hash of the window at every position. Declare a chunk boundary wherever the hash matches a pattern, for example when its lowest 13 bits are all zero. Because the decision depends only on the 48 bytes in the window, an insertion changes the boundaries only near the edit; a little further on, the window again sees the same bytes as before, finds the same boundaries, and produces the same chunks.

The rolling hash is what makes this cheap. A Rabin fingerprint treats the window as a polynomial over a finite field and can be updated in constant time per byte: remove the contribution of the byte leaving the window, add the byte entering it. Michael Rabin described polynomial fingerprinting in "Fingerprinting by Random Polynomials" (1981). The "Low-Bandwidth Network File System" (LBFS) by Muthitacharoen, Chen and Mazières (SOSP 2001) used Rabin fingerprints over a 48-byte window to cut files into content-defined chunks averaging about 8 KB, and showed large bandwidth savings for editing workloads. Newer hashes such as the Gear hash, used by FastCDC (Xia and colleagues, USENIX ATC 2016), are several times faster while giving similar boundaries.

The math of chunk sizes is simple and worth knowing. If a boundary fires when 13 bits of a well-mixed hash are zero, the chance at any byte is 1 in 2^13, so chunk lengths follow a geometric distribution with a mean of about 8 KB. Geometric distributions produce many tiny chunks and a long tail of huge ones, so implementations add a minimum size (do not even test for a boundary in the first 2 KB of a chunk) and a maximum size (force a boundary at 64 KB). For a sync product with multi-gigabyte files, the target is usually much larger, in the megabytes, to keep the chunk count and index size manageable: a 1 MB average means testing 20 bits instead of 13.

Whether Dropbox's production client uses fixed 4 MB blocks, content-defined boundaries, or a mix for different purposes is not something we can confirm from public sources. What is certain is the trade-off: fixed blocks are simpler and fine for files that are overwritten in place or replaced wholesale (photos, videos, most binary formats), while CDC wins for files with insertions (text, code, some document formats, uncompressed archives).

rsync's approach, for comparison. The rsync algorithm (Andrew Tridgell and Paul Mackerras, technical report, 1996) solves delta transfer differently. The receiver splits its old copy into fixed blocks and sends a weak rolling checksum and a strong hash for each block. The sender slides a window over the new file byte by byte, uses the weak checksum to find candidate matches at any offset, confirms with the strong hash, and sends only literal bytes plus references to matching blocks. This handles insertions without CDC, but needs an interactive exchange between two copies of the same file. A cloud store with millions of clients prefers CDC, because chunk hashes can be computed once and compared against a global index without the server reading the old file.

Send fewer bytes: compression. Compress on the client before upload; the compressed chunk is what blob storage holds, and the downloading client decompresses. Our servers stay out of the data path. Compression only pays when the time saved transmitting fewer bytes beats the CPU time spent compressing and decompressing:

  • Already-compressed media (JPEG, PNG, MP4, ZIP, most modern Office files, which are ZIP containers) shrink by a few percent at most. Skip them.
  • Text, logs, CSV, source code and uncompressed formats often shrink three to ten times. A 5 GB text log may become well under 1 GB.

A practical client decides per chunk: try a fast compressor on the first chunk, keep compressing only if the ratio is worth it. Among algorithms, gzip (DEFLATE) is universal and moderate; Brotli usually compresses text better than gzip and is supported in all modern browsers; Zstandard (zstd) compresses and decompresses much faster than gzip at similar or better ratios and has a wide range of levels, which makes it a strong default for client-side compression in a desktop sync agent. Two rules: always compress before encrypting (good ciphertext looks random and does not compress), and hash chunk identity over the uncompressed bytes, so that two clients with different compression settings still deduplicate.

Send fewer bytes: deduplication. If the server already holds a chunk, no client ever uploads it again. Within one user this catches copies, renames, moves and reverting a file. Across users it catches widely shared files (the same installer, the same viral video). Cross-user dedupe has a privacy cost, covered in the dedupe and garbage collection deep dive.

Other speed tricks used in practice:

  • LAN sync. If another device on the same local network already has the chunks, fetch them from it instead of from the internet. Dropbox offers a LAN sync feature of this kind; it needs local discovery and authenticated peer-to-peer transfer.
  • Pipelining and streaming sync. Do not wait to hash the whole file before starting uploads, and let other devices begin downloading chunks of a big file before its commit, then assemble when the commit lands.
  • Prioritisation. Sync small files and recently opened files first. A user waiting for a 10 KB document should not queue behind a 30 GB video.
  • Batching metadata. Commit hundreds of small files in one request when a user drops a folder in, instead of one round trip per file.

3. The metadata database: choosing and scaling it#

The metadata store is the system's brain. Every listing, commit, permission check and change feed request lands on it, and it holds about 500 TB. Its requirements are specific:

  • Per-namespace transactions: commit a revision, move the current pointer and append to the journal atomically.
  • A total order of changes within a namespace, so cursors make sense.
  • Uniqueness of names within a folder.
  • Very high read rates for listings and change feeds; tens of thousands of writes per second overall, a few per second per namespace.
  • Horizontal scale to hundreds of shards.

Basic: one relational database

A single PostgreSQL or MySQL primary with replicas handles millions of users and is the right answer for an early product. Transactions, unique constraints and ordered sequences are built in. It runs out at a few terabytes and tens of thousands of writes per second. See Relational Databases and SQL.

Better: shard by user

Hash the user id to pick a shard. Each user's private files live together. This breaks down at sharing: a shared folder belongs to many users, so either it lives on the owner's shard (and every member's sync requests cross shards) or it is duplicated (and must be kept consistent).

Best: shard by namespace, keep each namespace's world together

Make the namespace the shard key. A namespace's entries, revisions and journal share a shard, so the hot path (commit plus journal append) is a single-shard transaction. A user who mounts ten shared folders reads from up to eleven shards when syncing, but those reads are independent, parallel range scans, and they hit cache most of the time. A small directory service (itself cached) maps ns_id to shard. See Partitioning and Sharding and Pattern: Scaling Writes.

Dropbox has written publicly about Edgestore, a metadata store it built on top of sharded MySQL, which shows that a carefully sharded relational core can carry this load. Distributed SQL databases such as Spanner, CockroachDB or YugabyteDB are an alternative when you want cross-shard transactions without building them yourself. A key-value store such as DynamoDB can work too, using conditional writes for optimistic concurrency and transactions for the multi-item commit, but you lose free-form secondary indexes and must design every access path up front. See Amazon DynamoDB in Practice and SQL vs NoSQL: How to Choose.

Modelling the tree

Do not store full paths as the primary identity. Store each entry with a parent_id and a name. Then:

  • Renaming a folder changes one row, not one row per descendant. A folder with a million files can be renamed in a millisecond.
  • Moving within a namespace changes the parent_id of one row, plus a journal entry. Guard against cycles: moving /a into /a/b/c must be rejected, which requires walking up from the destination to the root.
  • Resolving a path walks from the root through each component. Cache resolved paths aggressively, or keep a denormalised path column (updated asynchronously on renames) for display and search only.

The unique index on (ns_id, parent_id, name) prevents two entries with the same name. But "same name" is subtle across platforms:

  • macOS and Windows file systems are usually case-insensitive (Report.docx and report.docx are the same file), while Linux is case-sensitive. If a Linux user creates both, a Windows device cannot represent both. The service must pick a rule (Dropbox treats names case-insensitively) and enforce it with a normalised unique key such as lower(name).
  • Unicode normalisation: macOS has historically stored names in a decomposed form (an accented "e" as "e" plus a combining accent), while other systems use the composed form. The same visible name can be two different byte strings. Normalise (for example to NFC) before comparing, but keep the original for display.
  • Illegal characters and names: Windows forbids characters like : and ? in names and reserves names like CON and NUL. A file legally created on Linux must be handled gracefully on Windows, usually by refusing to sync it there and warning the user.

These details sound small. They are the kind of thing that breaks real sync products, and mentioning them is a strong signal of practical depth.

Moves across namespaces and huge namespaces

Moving a file from a private folder into a shared one crosses namespaces, and so may cross shards. It is a delete in one journal and a create in another. Do it as a small saga: write the create in the destination (referencing the same chunks, so no bytes move), then the delete in the source, with an idempotent move id so a crash in the middle can be completed or rolled back by a repair job. Briefly, both files may be visible; that is acceptable under our availability-first requirement. See Distributed Transactions: 2PC, Sagas and Outbox.

A single namespace that grows enormous (a company-wide shared drive with tens of millions of files and thousands of writers) breaks the "one namespace, one shard, one sequence" assumption. Options: split it into child namespaces at natural folder boundaries (each with its own journal, mounted inside the parent), or move that tenant to a store that supports larger transactional partitions. Detect such namespaces early with metrics on size and commit rate.

4. The sync protocol: journals, cursors and the client's three trees#

Sync looks like "copy new files around". It is really replication: every device is a replica of a set of namespaces, and the protocol must bring every replica to the same state, in the face of crashes, offline periods, retries and concurrent writers. The design that works is a server-ordered log.

Basic: "what changed since time T?"

The first API sketch used GET /files/changes?since={timestamp}, with the server returning files whose updatedAt is after T. It fails in subtle ways:

  • Clock skew. Timestamps come from many servers whose clocks differ by milliseconds or more. A change stamped 10:00:00.010 on server X may commit after a change stamped 10:00:00.020 on server Y.
  • Commit order is not timestamp order. A transaction that starts at 10:00:00.000 and commits at 10:00:00.500 gets an early timestamp but becomes visible late. A client that read "everything up to 10:00:00.300" at 10:00:00.300 has already moved past it and will never see it.
  • Ties and pagination. Many changes share a timestamp; paging by time either repeats or skips them.

The result is silently missed changes, the worst kind of sync bug. See Time, Clocks and Ordering.

Better: a per-user change log

Assign every change a sequence number in a per-user log. Clients ask "changes after seq N". Ordering is now exact. But a shared folder with 50 members would need each change written to 50 logs, and the write amplification grows with membership.

Best: a per-namespace journal and a composite cursor

Each namespace has a dense, gap-free sequence, assigned inside the commit transaction (the head_seq bump we saw in the data model). Because the sequence is assigned in the same transaction that makes the change visible, a reader that sees seq 5013 has definitely seen every seq up to it. No change can appear "behind" the cursor later.

A device's sync position is then a vector of cursors, one per mounted namespace: {ns_alice: 88412, ns_team: 5013, ns_design: 120}. The opaque cursor string the API returns is just this vector, encoded and signed so clients cannot tamper with it. A list changes call:

  1. Decodes the cursor.
  2. For each namespace, reads journal WHERE ns_id = ? AND seq > ? ORDER BY seq LIMIT 1000 from that namespace's shard (in parallel).
  3. Maps each entry from namespace-relative paths into this user's view (a file at /Q3.xlsx in ns_team is /Work/Team/Q3.xlsx for Bob, because of his mount path).
  4. Returns the merged entries, a new cursor, and hasMore if any namespace had more than the page limit.

Journal entries carry the latest state (the new revision, name and parent) rather than a diff, so applying an entry is idempotent. Replaying a page after a crash produces the same result, which is what makes "save the cursor only after applying" safe.

Mounting and unmounting are themselves journal entries in the user's root namespace. When Bob joins ns_team, his root journal gets a "mount ns_team at /Work/Team" entry; his device sees it, adds ns_team: 0 to its cursor vector, and downloads the folder's contents. When Bob leaves, an "unmount" entry tells his devices to remove the folder locally.

New devices and expired cursors

A brand-new device does not replay years of journal. It asks for a snapshot: a paginated listing of the current state of each namespace, together with the head seq at which the snapshot was taken. It then follows the journal from that seq. To make the snapshot consistent, read it at a single database snapshot (a repeatable-read transaction or an MVCC timestamp), or tolerate a slightly torn snapshot by replaying the journal from the earliest seq at which the listing began, since replay is idempotent.

Journals cannot grow forever. Keep entries for some window (for example 90 days) and compact older ones. A device whose cursor is older than the retained window (a laptop that was in a drawer for a year) gets an error such as cursor_reset, and performs a full re-list followed by a local comparison. That comparison is expensive but correct, and it happens rarely.

The client side: three trees

The client is where most sync bugs live, because it must reconcile three views of the world:

  • Remote tree: what the server says, as of the device's cursor.
  • Local tree: what is actually on disk right now, as reported by the file watcher and periodic scans.
  • Synced tree: the last state on which local and remote agreed. This is the merge base.

Comparing each side with the synced tree tells the client who changed what. If only local differs from synced, upload. If only remote differs, download. If both differ for the same file, it is a conflict. Without the synced tree, a client cannot tell "I deleted this file" from "someone else created it", and that is how sync engines delete or resurrect files by mistake. Dropbox described this three-tree model publicly when it explained Nucleus, its rewrite of the desktop sync engine in Rust, around 2020; the model is also the classic three-way merge used by version control.

The planner must also order operations correctly. Create a parent folder before its children. Apply a move before writing into the moved folder. Delete children before the parent. Never delete a local file until the deletion is confirmed by the remote side, or by an explicit user action captured in the local tree. The local database holding these trees must itself be crash-safe (SQLite with write-ahead logging is a common choice), because a power cut mid-sync must not corrupt the client's memory of what was synced.

File watchers are lossy. Event buffers overflow under heavy churn, events coalesce, and some changes (a volume being unmounted and remounted, a backup tool restoring files) produce no events at all. So clients also scan periodically, comparing size, modification time and inode or file id with the local tree, and re-hash anything suspicious. Watchers give speed; scans give correctness. It is the same "push for speed, pull for truth" idea as in remote notifications.

5. Change notifications at scale#

The notification layer tells 150 million online devices, within seconds, that something they care about changed. It carries tiny hints, not data, but it has to hold an enormous number of mostly idle connections.

Basic: frequent polling

Every device calls list changes every 30 seconds. That is 5 million requests per second of mostly empty answers, each touching up to a dozen shards. Raising the interval to 5 minutes cuts load tenfold but makes sync feel broken.

Better: long polling

The device calls GET /v1/changes/longpoll?cursor=.... The server holds the request open for up to a minute or so. If any namespace in the cursor advances, it returns changes: true immediately; otherwise it returns changes: false at the timeout and the device calls again. Latency is near-instant and empty traffic drops to one request per device per minute. Long polling is plain HTTP, so it passes through every proxy and firewall, which is why it has been popular for sync clients. The server can also return a backoff value to slow clients down during incidents.

Best: persistent connections with a subscription index

Each device holds one WebSocket (or SSE or long-poll) connection to a notification server. Each server keeps an in-memory map from namespace id to the connections subscribed to it, built from each device's mounted namespaces when it connects.

When a namespace advances, the Metadata Service publishes {ns_id, seq} to the change bus. Fan-out works like this:

  • The bus is partitioned by namespace. A routing tier knows which notification servers have subscribers for which namespaces (each server registers its subscriptions in a shared index such as Redis, keyed by namespace).
  • Each event is delivered only to servers that have subscribers, and each of those pushes the hint down each subscribed connection.
  • Hints are coalesced. If a namespace advances 500 times in a second (someone dropped 500 files in), a device needs one hint, not 500. Servers debounce per connection, for example sending at most one hint per namespace per second.

Mobile apps cannot hold sockets in the background; the operating system suspends them. For mobile, use the platform push services (Apple Push Notification service and Firebase Cloud Messaging) to wake the app or show "Bob shared a folder with you", and let the app sync when it is foregrounded. Web clients use the same WebSocket path while the tab is open.

The thundering herd. A big shared namespace (a 20,000-person company folder) changes, and 40,000 devices all call list changes within the same second, each hitting the same shard. Mitigations: add random jitter of a few seconds before acting on hints for large namespaces; serve the journal tail for hot namespaces from a cache (the last few hundred entries of busy namespaces in Redis); and let the notification itself carry the new head seq, so clients that are already up to date skip the call. See Cache Failure Modes: Stampedes, Hot Keys and Penetration.

Reconnect storms. When a notification server restarts or a region fails over, hundreds of thousands of devices reconnect at once and each then calls list changes. Clients must reconnect with exponential backoff and jitter, and servers should accept connections faster than they process the follow-up sync calls (admission control on the change feed, not on the socket). See Resilience Patterns: Timeouts, Retries and Circuit Breakers.

The safety net, made cheap. Every client still polls (or reconnects) every few minutes, in case a hint was lost. That poll must not touch the database. Keep each namespace's head_seq in a cache, updated on commit. A poll compares the client's cursor vector with the cached heads and returns "nothing new" in microseconds. Only namespaces that actually advanced cause journal reads. That turns the 500,000-per-second safety-net load from the estimate into cheap cache lookups.

6. Conflict handling#

A conflict happens when two replicas change the same thing without seeing each other's change. With offline laptops, slow networks and shared folders, conflicts are a normal part of life, and the system's behaviour when they happen defines whether users trust it.

The kinds of conflict

  • Edit and edit: two devices change the same file from the same base revision.
  • Edit and delete: one device edits a file while another deletes it.
  • Create and create: two devices create different files with the same name in the same folder.
  • Rename and rename: one file renamed to two different names, or two files renamed to the same name.
  • Move and move into a cycle: device A moves folder x into y while device B moves y into x. Applying both makes a loop that is not a tree.
  • Write into a deleted folder: one device adds a file to folder f while another deletes f.

The server detects most of these with the same tool: every mutation names the revision or state it was based on, and the server rejects it if that base is no longer current. Conflicts are detected at commit time on the server, which sees a single ordered history per namespace.

Bad: last writer wins

Accept every commit; the latest one becomes current. Simple, and it is the default in many systems for small metadata fields. For file contents it is terrible: Alice's two hours of edits on the plane silently vanish when Bob's 10-second change lands first. "Latest" is also ill-defined when "latest" comes from client clocks, which can be hours wrong. Last-writer-wins is acceptable only if earlier versions are kept and easy to restore, and even then the user does not know they should look.

Good: detect and keep both

Use optimistic concurrency (the parentRevision check). The first commit wins the name; the second gets 409. The losing client saves its version as a conflicted copy next to the original, with a name that says what happened, such as budget (Alice's conflicted copy 2026-03-02).xlsx, the convention Dropbox uses. Both versions sync everywhere and a human decides. Nothing is lost.

Each conflict type gets a rule that never loses data:

  • Edit and delete: the edit wins; the file is resurrected with the edited content, because deleting someone's work is worse than leaving a file around.
  • Create and create: the second file is renamed with a suffix.
  • Move cycles: the server applies moves in its own order and rejects the second move that would create a cycle; that client undoes its local move.
  • Write into a deleted folder: either resurrect the folder (keeping the new file) or move the new file to a recoverable location. Never drop it.

Great: merge where the format allows, and keep a history

Some formats can be merged automatically. Plain text and code can use a three-way merge against the common base revision, the way version control does, and only create a conflicted copy if the same lines changed. Formats designed for collaboration (Google Docs, Office co-authoring) avoid file-level conflicts altogether by sending fine-grained operations to a server that orders them, using operational transformation or CRDTs. That is a separate system from file sync; see Conflict Resolution, OT and CRDTs.

Do we need version vectors?

Peer-to-peer systems with no central authority, such as Dynamo-style stores or the Coda file system, track causality with version vectors: a counter per replica, so that two versions can be compared as "A happened before B", "B happened before A" or "concurrent". The idea was introduced for detecting mutual inconsistency in replicated files by Parker and colleagues in 1983. Our design does not need them on the server, because each namespace has a single serialised history. The parent revision on each commit is enough to tell "based on the latest" from "based on something older". Version vectors become relevant if devices sync directly with each other (LAN sync with writes, or a fully offline peer-to-peer mode), or if a namespace is accepting writes in two regions at once. See Quorums and Leaderless Replication.

Disconnected operation, in which a client keeps working against its local copy while offline and reconciles on reconnect, was studied in depth in the Coda file system at Carnegie Mellon; Kistler and Satyanarayanan's paper "Disconnected Operation in the Coda File System" (SOSP 1991, later in ACM TOCS) remains a good read on exactly the conflict cases above.

7. Versioning and recovery#

Versioning was "nice to have" in the first sketch. Once we store files as immutable revisions built from immutable chunks, it becomes almost free, and it turns into one of the product's most valuable features: undo for accidental overwrites, recovery of deleted files, and recovery from ransomware that encrypts every file on a laptop and dutifully syncs the encrypted garbage to the cloud.

Basic: overwrite in place

Each upload replaces the stored object. There is no history. A bad save, a sync bug or ransomware destroys data permanently. Not acceptable for a product whose promise is "your files are safe".

Better: object-store versioning

Turn on bucket versioning so that overwritten and deleted objects are kept as non-current versions, with a lifecycle rule that expires non-current versions after 30 days. It protects against accidents at the storage layer, but the application cannot easily list "versions of budget.xlsx" (object keys do not map to user-visible files in a chunked design), and whole-file object versions waste space when only one chunk changed.

Best: revisions as first-class metadata

Every commit creates a new revision row that lists its chunk hashes; the file entry's current_rev moves forward; old revisions stay. Then:

  • Version history is SELECT * FROM revision WHERE file_id = ? ORDER BY server_time DESC.
  • Storage cost is only the delta. Revision r9 shares ten of its eleven chunks with r8, so keeping r8 costs one chunk, not 40 MB.
  • Restoring a version creates a new revision whose chunk list equals the old one (r10 = content of r6). It is not a rewind of the pointer. History stays linear, the restore syncs to every device as an ordinary change, and the restore itself can be undone.
  • Deleting a file writes a tombstone and a journal entry. The revisions and chunks remain until the retention window passes, so "recover deleted files" is a query over tombstones.
  • Point-in-time restore of a whole folder (rolling a namespace back to how it looked last Tuesday, the main tool against ransomware) replays the journal backwards to that point, computing for every file the revision that was current then, and commits those as new revisions in one batch.

Retention is a business policy expressed as data. Consumer products commonly keep 30 days of history, with longer windows on paid or business plans (the exact numbers are plan-dependent and change over time, so check current documentation rather than quoting them). A retention job walks revisions older than the window, deletes those that are not current, and decrements the reference counts of their chunks, which feeds garbage collection.

How much does history cost? If 10 percent of stored bytes are rewritten each month, and delta chunking means only a third of each rewritten file's chunks are actually new, a 30-day history costs about 3 percent extra storage. Without chunk sharing it would cost the full 10 percent. That arithmetic is why chunked revisions are the standard design. See Data Lifecycle, Tiering and Retention.

A ransomware detector is a natural extension: if one device suddenly rewrites thousands of files in minutes, all with high-entropy content and unfamiliar extensions, pause its sync, alert the user and offer a one-click folder restore. The data needed for detection (commit rate per device, content entropy of new chunks) is already flowing through the system.

8. Sharing and permissions in depth#

The high-level design gave us a shares table and namespaces. A real sharing model adds roles, folder inheritance, groups, links, and the hardest part: revocation that actually takes effect.

Roles. At minimum owner, editor and viewer; Drive-style products add commenter. Roles map to allowed actions: viewers can list and download; editors can also commit, rename, move and delete inside the folder; owners can also change membership and delete the folder. A shared folder's membership is the namespace's membership table. Permissions are checked on every control-plane call (list, commit, get a download URL), always against the caller's identity from their token.

Inheritance. Files inherit the permissions of the namespace that contains them. That is cheap and simple, and it is why making shared folders into namespaces is so effective: there are no per-file ACL rows to update when a folder is shared. Products that allow sharing a single file inside an unshared folder (Drive-style) add per-item grants on top, and an access check becomes "a grant on the item, or on any ancestor folder, or via any group the user belongs to". To keep that fast, precompute the effective set or cache the check results per user and item for a short time.

Groups and teams. Business customers share with groups ("Finance team") rather than individuals, and groups contain groups. Expanding nested groups on every check is expensive, so systems either materialise the expansion when membership changes or use a dedicated authorisation service. Google's paper "Zanzibar: Google's Consistent, Global Authorization System" (USENIX ATC 2019) describes such a service, which stores permissions as relation tuples ("user U is a member of group G", "group G is a viewer of folder F") and answers "can U view F" by walking those relations. Google reports that it serves authorisation for many of its products, including Drive. It also names the new enemy problem: if Alice removes Bob from a folder and then adds a secret file, a stale permission check must not let Bob see the new file. Zanzibar solves it with consistency tokens ("zookies") that make checks at least as fresh as the content they protect. Open-source systems inspired by it, such as OpenFGA and SpiceDB, are options if you need this model.

Link sharing. "Anyone with the link can view" creates a link token: a long random identifier (128 bits or more, so it cannot be guessed) that maps to an item, a role and optional constraints: an expiry date, a password, "only people in my organisation", download disabled. A link token is a capability, so anyone holding it gets access. Store only a hash of the token in the database, rate-limit link resolution to stop scanning, and let owners revoke a link instantly by deleting its row.

Listing what is shared with me. A query over the user's memberships (namespaces mounted or offered) and per-item grants, sorted by recency. It is served by the (user_id, item_id) index from the high-level design. New shares appear as journal entries in the recipient's root namespace (an offer to mount), so they arrive through the normal sync path, plus an email and a mobile push.

Revocation. Removing Bob from a folder:

  1. Deletes his membership row and writes an unmount entry to his root journal, so his devices remove the folder.
  2. Invalidates cached permission entries for Bob and that namespace, immediately, by explicit delete or by bumping a per-namespace permission version that is part of every cache key.
  3. Stops issuing new download URLs to Bob. URLs already issued are bearer tokens and remain valid until they expire, which is the main reason to keep their lifetime short (minutes).
  4. Cannot "un-download" files Bob already has on his laptop. That is a fundamental limit of sync, worth saying out loud. Managed enterprise devices can enforce remote wipe; consumer devices cannot.

See Authentication and Authorization for the models behind roles, groups and capability tokens.

9. Security: encryption, signed URLs and abuse#

Encryption in transit. All traffic uses HTTPS with TLS 1.2 or 1.3: API calls, chunk uploads to blob storage, CDN downloads and notification connections. Desktop clients can pin the service's certificate or public key to resist interception by rogue certificates.

Encryption at rest. Blob storage encrypts every object. Use envelope encryption: each object (or chunk) is encrypted with its own data key; data keys are themselves encrypted by a master key held in a key management service (AWS KMS, Google Cloud KMS, or an in-house HSM-backed service) and stored next to the data. Reading requires asking the KMS to decrypt the data key, which gives a central point for access policy, audit logs and key rotation. With S3, server-side encryption with KMS keys (SSE-KMS) does this for you. Metadata databases and backups are encrypted too; file names can be as sensitive as contents.

Signed URLs as bearer tokens. Every presigned blob URL and signed CDN URL embeds a path, an expiry and a signature. When the CDN gets a request, it verifies the signature with the public key we registered, checks the expiry and any extra conditions, and only then serves. Signed URLs are bearer tokens: anyone who has a valid, unexpired URL can use it, so a user who pastes one into a public forum has handed out access. Mitigations:

  • Short expiry (a few minutes for downloads; the client asks again when needed).
  • Bind the URL to conditions where the CDN supports it: an IP address range, or a signed cookie scoped to the user's session, so the URL alone is not enough.
  • Scope each upload URL to exactly one object key, method and maximum size, so it cannot be used to write elsewhere or upload a 1 TB file.
  • Key rotation for signing keys, with overlap so in-flight URLs survive the rotation.

Integrity. Every chunk is identified by its SHA-256 hash, and every reader re-hashes what it downloads. A flipped bit in storage, a buggy proxy or a malicious middlebox is detected rather than silently written into a user's file. On the server, background verification jobs periodically read and re-hash stored chunks, a process sometimes called scrubbing.

End-to-end encryption, and what it costs. If clients encrypt files with keys the service never sees, a breach of the service cannot reveal contents. But the server can then no longer deduplicate across users, generate previews and thumbnails, index for search, or scan for malware, and a user who loses their key loses their files. Some products offer it as an opt-in for specific folders, which is a reasonable trade-off to describe. A middle ground for deduplication, convergent encryption (deriving the key from the content's own hash, studied for Microsoft's Farsite system by Douceur and colleagues around 2002 and formalised as message-locked encryption by Bellare, Keelveedhi and Ristenpart in 2013), keeps dedupe working but leaks whether two users hold the same file, which brings us to the privacy problem of dedupe below.

Abuse. A free storage service attracts people hosting malware and illegal content and using shared links as a free CDN. Controls: per-user and per-link bandwidth limits, rate limits on link resolution and on uploads, hash-matching uploads against known-bad content lists, and a takedown workflow that can disable a chunk for everyone. See Security Fundamentals for System Design.

10. Deduplication, its privacy cost, and garbage collection#

Content addressing gives deduplication almost for free: before uploading a chunk, ask whether its hash exists. The harder parts are deciding how widely to dedupe and knowing when a chunk can be deleted.

Scope of deduplication

  • Within a file's history: unchanged chunks between revisions. Always worth it; it is what makes versioning cheap.
  • Within one user or one team: copies, moves, renames, re-uploads. Safe and valuable.
  • Across all users: one copy of the popular installer, meme video or textbook PDF, however many people store it. It saves the most storage at scale, but it has a privacy problem.

The side channel. If uploading a chunk the server already has completes instantly (because the client is told "no need to send it"), then the speed of an upload reveals whether someone else already stored that exact content. An attacker can test "does anyone store this specific document?" or, for a document with a small number of possible values (a template letter with a salary or a PIN in it), guess the values one by one. Harnik, Pinkas and Shulman-Peleg described this class of attack in "Side Channels in Cloud Services: Deduplication in Cloud Storage" (IEEE Security and Privacy magazine, 2010).

The "hash as a key" problem. If a client can claim a chunk just by sending its hash, the hash becomes a way to download content you never had. In 2011 a researcher published a tool (widely reported under the name Dropship) that used this to share files through Dropbox by exchanging hashes alone, and Dropbox changed its client protocol in response. Defences are proofs of ownership: the server asks the client to prove it holds the actual bytes, for example by hashing randomly chosen ranges of the content (Halevi, Harnik, Pinkas and Shulman-Peleg, "Proofs of Ownership in Remote Storage Systems", ACM CCS 2011).

The pragmatic design:

  • Deduplicate client-side (skip the upload) only within the user's own namespaces, where no one learns anything new.
  • Deduplicate across users only on the server side, after the full upload: the client always sends the bytes, and storage notices the chunk already exists and stores a reference instead of a second copy. That saves storage but not bandwidth, and it leaks nothing because timing is the same either way.
  • Never let a bare hash grant access. A chunk can be added to a user's file only if that user uploaded it or already has a revision referencing it.

Garbage collection: when can a chunk die?

A chunk may be referenced by many revisions in many namespaces. It can be deleted only when no retained revision references it. Two classic approaches:

  • Reference counting. Each revision commit increments the count of every chunk it lists; each revision expiry decrements. At zero, the chunk is a deletion candidate. Cheap and incremental, but counts drift if any increment or decrement is lost or doubled (a crash between steps, a retried job), and a drifted count either leaks storage forever or, far worse, deletes live data.
  • Mark and sweep. Periodically scan all retained revisions, mark every referenced chunk, and delete unmarked chunks. Self-correcting, but scanning hundreds of billions of references is a large batch job, run over days, so it cannot be the only mechanism.

Production systems combine them: reference counts (or per-chunk lists of referring namespaces) for routine reclamation, and a periodic mark-and-sweep or reconciliation pass that audits the counts and fixes drift before anything is deleted.

The resurrection race. The dangerous moment is this: the collector decides chunk h7 has zero references and is about to delete it; at the same instant, a client asks "do you have h7?", hears yes, skips the upload, and commits a revision referencing it. The collector deletes it. The new revision now points at nothing. Defences:

  • Grace periods. A chunk at zero references is not deleted immediately; it is marked "pending delete" with a timestamp and physically removed only after, say, 7 days. Any commit that references it in the meantime revives it.
  • Commit-time check. The commit path re-checks that each chunk exists and is not pending delete, and atomically increments its count. A "pending delete" chunk is either revived or the client is told to upload it again.
  • Two-phase delete. Soft-delete first (the object becomes unreadable but recoverable), hard-delete much later. A bug in GC then costs a restore, not a data loss incident.

The guiding rule: a GC that deletes too little costs money; a GC that deletes too much destroys trust. Every design choice should bias towards keeping data, with audits before deletion and delays between deciding and doing.

11. Offline use, mobile and on-demand files#

Offline is the normal case for a sync client. The client works against the local file system; sync is background replication. While offline, the watcher still records changes in the local tree. On reconnect, the planner diffs local, remote and synced trees, uploads local changes (with parent revisions from the synced tree, so conflicts are detected), and downloads remote ones. Because cursors and commits are idempotent, a reconnect in the middle of all this is harmless.

On-demand files (placeholders). Users with 2 TB in the cloud and a 256 GB laptop cannot sync everything. Modern clients show every file as a placeholder that looks like a normal file to applications but is fetched only when opened. Operating systems now provide official interfaces for this: Microsoft's Cloud Files API (used by OneDrive Files On-Demand) on Windows and Apple's File Provider framework on macOS and iOS. When an application opens a placeholder, the OS calls the sync client, which downloads the chunks and hydrates the file. Least-recently-used files can be dehydrated back to placeholders to free disk space. The design consequence on the server: metadata sync must be fast and complete even when content sync is partial.

Selective sync lets users choose which folders a device syncs. The device still receives journal entries for the whole namespace, but ignores (or records without downloading) entries outside its selection.

Mobile constraints. Mobile apps sync metadata on launch and on push, download files on demand, and run uploads such as camera backups in the background under the platform's rules (background transfer services on iOS, WorkManager on Android). They default to uploading over Wi-Fi only, respect battery-saver modes, and resume interrupted uploads from the last completed chunk. Mobile is where small chunks and aggressive resumption matter most.

Web clients do not sync. They list folders through the API, upload with chunked presigned uploads from JavaScript (the File API can slice a Blob into chunks and compute hashes with Web Crypto), and download through the CDN or the streaming download proxy.

12. Storage durability, consistency between stores, and repair#

Durability comes from the blob store, and is verified by us. Cloud object stores replicate or erasure-code each object across failure domains and advertise designs of eleven nines of durability per year. Erasure coding stores, for example, 6 data fragments plus 3 parity fragments for each piece of data, so any 6 of the 9 rebuild it: about 1.5 times overhead instead of 3 times for triple replication, which at exabyte scale is an enormous saving. How such a store places fragments, repairs failed disks and achieves those numbers is the subject of the Object Store case study.

Dropbox is a famous example of the economics. It stored file contents on Amazon S3 for years, then built its own exabyte-scale block storage system, Magic Pocket, and announced in 2016 that it had moved the large majority of user data onto it. The motive was cost and control at a scale where storage is the main expense. For an interview, "we use S3, and here is when we might build our own" is the right level.

Keeping metadata and blobs consistent. Two stores, no distributed transaction. The rules that keep them consistent:

  1. Bytes before metadata. Never commit a revision that references a chunk that is not durably stored and verified. The commit path checks existence.
  2. Metadata before deleting bytes. Never delete a chunk while any retained revision references it; delete only through the GC path with its grace periods.
  3. Immutability. A chunk key is a hash of its contents, so an object can never be "updated" into something else. Overwrites are new objects. There are no lost updates or torn writes at the blob layer.

With those rules, any failure leaves either an orphan (a stored chunk nobody references, which costs a little money and is collected later) or a pending operation (an upload session or a move saga) that a repair job can finish. It never leaves a revision pointing at missing bytes.

S3 has provided strong read-after-write consistency for all operations since December 2020, which simplifies these checks: a HEAD immediately after a successful PUT sees the object. On stores that are only eventually consistent for some operations, the commit-time existence check must tolerate a short delay or rely on the upload's own success response plus a later audit.

Reconciliation. Background jobs continually compare views that should agree:

  • The chunk index against a listing of the blob store (finds orphans and, critically, missing chunks).
  • Reference counts against a mark pass over revisions (finds count drift).
  • Each namespace's head_seq against the maximum journal seq (finds partial writes).
  • Random samples of stored chunks, re-read and re-hashed (finds silent corruption).

Every discrepancy is an alert and a ticket, not just an automatic fix, because a pattern of discrepancies usually points to a bug. See Observability: Logs, Metrics and Traces.

Backups beyond the primary store. Durability protects against hardware loss, not against our own bugs. A GC bug or a bad deploy can delete or corrupt data at the logical level, and replication faithfully replicates the damage. Keep the metadata database backed up with point-in-time recovery, keep soft-deleted chunks for a safety window, and consider a second copy of critical data in a separate account or provider with deletion protection. See Disaster Recovery and Backups.

Bottlenecks and Failure Modes#

Failure / hotspotImpactMitigation
Upload connection drops at 49 of 50 GBUser restarts a multi-hour uploadClient-side chunking, upload sessions found by fingerprint, ListParts verification, resume only missing parts
Bytes routed through API serversDoubled bandwidth, gateway payload limits, API servers starvedPresigned direct upload and download; servers stay on the control plane
One-byte insert re-uploads whole fileDelta sync useless for many file typesContent-defined chunking with a rolling hash, min and max chunk sizes
Missed change notificationA device silently stays out of dateHints carry no data; cursor-based change feed is the truth; safety-net poll and sync on reconnect
Timestamp-based change queriesChanges skipped because of clock skew and commit orderPer-namespace sequence assigned inside the commit transaction; opaque cursors
Concurrent edits to the same fileSilent loss of one person's workParent revision check on commit, 409 conflict, conflicted copy, never last-writer-wins on content
Huge shared namespace changesThousands of devices hit one shard at once (thundering herd)Coalesced hints, jitter, cached journal tail, head seq in the hint
Notification server restart or region failoverReconnect storm, sync request spikeExponential backoff with jitter, admission control on the change feed, spread connections across servers
Safety-net polling at scaleHundreds of thousands of empty requests per secondCompare cursors with cached namespace heads; no database reads unless a head advanced
GC deletes a chunk being re-referencedCommitted revision points at missing bytes: data lossGrace periods, commit-time existence and pending-delete check, soft delete before hard delete, audits
Leaked signed URLUnauthorised downloadMinutes-long expiry, scoped URLs, IP or cookie binding, link tokens revocable by deleting a row
Metadata shard hot or fullSlow commits and listings for many namespacesShard by namespace, split oversized namespaces, move hot tenants, cache listings and permissions

What Interviewers Expect#

Mid-level#

  • A clear API and data model covering upload, download, share and sync, with files and metadata stored separately (blob storage plus a database).
  • A working high-level design for all four functional requirements.
  • Not necessarily knowing presigned URLs or chunking up front, but reasoning to them under prompting: "You upload the file twice; how do you avoid that?" leads to direct upload; "How do you show progress and resume?" leads to chunks and tracked chunk status.
  • A sensible sync story: a client that watches the folder and uploads changes, and a way (polling at least) to learn about remote changes.

Senior#

  • Moves quickly through the basics to spend most of the time on large-file upload: client-side chunking, multipart upload with per-part presigned URLs, ETags and server-side verification, fingerprints for resumption, abort and cleanup rules.
  • Names the boundary-shift problem and content-defined chunking, explains delta sync and when compression helps.
  • Designs sync with a cursor-based change feed and push notifications as hints, plus a polling safety net, and explains why timestamps are not enough.
  • Handles conflicts with optimistic concurrency and conflicted copies; models sharing with a normalised shares table and ideally namespaces for shared folders.
  • Discusses trade-offs explicitly: DynamoDB vs relational metadata, CDN cost vs latency, cross-user dedupe vs privacy.

Staff+#

  • Treats the problem as replication: per-namespace serialised journals, single-shard commit transactions, cursor vectors, idempotent replay, snapshot plus journal for new devices, cursor expiry and reset.
  • Covers the client engine as a real distributed system: three trees and three-way reconciliation, lossy watchers plus scans, safe operation ordering, crash-safe local state, cross-platform naming hazards.
  • Designs the storage lifecycle end to end: content-addressed immutable chunks, reference counting with audits, the resurrection race and grace periods, rules for consistency between metadata and blobs, and reconciliation jobs.
  • Goes deep on permissions: inheritance through namespaces, groups, link capabilities, revocation and its limits, and the new enemy problem.
  • Quantifies: notification server counts, safety-poll load, metadata size and shard counts, history storage cost. Knows when building in-house storage (as Dropbox did) makes economic sense.
  • Drives the conversation, chooses which deep dives matter, and treats the interviewer as a peer.
Deep Dive: the numbers behind file sync, worked throughShow

How big is the chunk index? With 2 EB of logical data and an average chunk of a few megabytes for large files, but one chunk per small file, the number of unique chunks is dominated by small files: roughly the number of unique file contents, call it 300 to 600 billion. Each index row holds a 32-byte SHA-256 key, a location, a size, a reference count and timestamps, about 80 to 100 bytes with overhead. That is 30 to 60 TB, before replication. It is a sharded key-value store, and since the keys are cryptographic hashes, they spread perfectly evenly over shards with no hot spots by construction.

A Bloom filter in front of it. Most "do you have this chunk?" queries for brand-new content will answer "no". A Bloom filter over all chunk hashes answers most of those from memory. At about 10 bits per element for a 1 percent false-positive rate, 500 billion chunks need about 625 GB of filter, which is large but splittable by hash prefix across the Block Service fleet. A "maybe" goes to the index; a "no" is final. See Probabilistic Data Structures for Big Data.

Can two different chunks have the same SHA-256? In principle yes; in practice no. By the birthday bound, the chance of any collision among n random 256-bit hashes is about n squared divided by 2 to the power 257. For n = 10^12 chunks that is about 10^24 / 2.3 x 10^77, roughly 4 x 10^-54. Undetected disk and memory errors are many orders of magnitude more likely. That is why content addressing with a strong cryptographic hash is safe, and why weaker hashes (MD5, SHA-1, for which practical collision attacks exist) must not be used as identities: the danger there is not chance, it is an attacker crafting two different files with the same hash.

How much does CDC save? Take a 100 MB file with 1 MB average chunks (about 100 chunks) and insert one paragraph in the middle. With fixed chunks, every chunk after the insertion point changes: about 50 chunks, 50 MB, re-uploaded. With CDC, the chunk containing the edit changes, and occasionally its neighbour if the edit destroys or creates a boundary: 1 to 2 chunks, 1 to 2 MB. A 25 to 50 times saving for that edit. For in-place overwrites (a database file with fixed pages), fixed chunks do just as well.

Upload time with parallelism. A single TCP stream with 1 percent packet loss and 100 ms RTT is limited, by the well-known Mathis approximation (throughput roughly equals MSS divided by RTT, times 1.22 over the square root of the loss rate), to about 1,460 bytes / 0.1 s x 12.2, roughly 180 KB/s, about 1.4 Mbps. On such a lossy path, eight parallel streams get roughly eight times that, which is why parallel chunk upload matters far more on bad networks than on good ones. On a clean path (0.01 percent loss, 20 ms RTT), one stream can reach about 70 Mbps by the same formula, and two or three streams already fill a 100 Mbps uplink.

Notification server memory. An idle TLS WebSocket costs on the order of 10 to 30 KB of kernel and user-space buffers. At 200,000 connections per server, that is 2 to 6 GB, comfortable on a 32 GB machine. The binding limits are usually CPU for TLS handshakes during reconnect storms and file descriptor limits, not steady-state memory.

Journal volume. 2 billion changes a day at about 100 bytes per journal entry is 200 GB per day. With 90 days of retention, about 18 TB of journals, spread across the metadata shards, a few percent of the metadata total.

Commit rate per namespace. A namespace serialised through one row lock can commit perhaps 2,000 to 5,000 small transactions per second on a good primary. A person or even a 50-person team never comes close. A build system writing thousands of files per second into a synced folder can, which is a reason to batch commits (one transaction for many files) and to advise users not to sync build output.

Deep Dive: how real systems do itShow

Dropbox. Public engineering writing from Dropbox describes many of the pieces in this design. File contents are split into blocks of up to 4 MB, each identified by its SHA-256 hash, and the published API content hash is built from those block hashes. Metadata and block transfer are handled by separate services. Dropbox has described Edgestore, a metadata store built on sharded MySQL, and Magic Pocket, an exabyte-scale block storage system it built after years on Amazon S3, with the migration announced in 2016. Around 2020 it described Nucleus, a rewrite of the desktop sync engine in Rust, built around remote, local and synced trees and heavily tested with randomised testing that injects failures and reorderings. Its public developer API exposes the cursor model directly: list_folder returns entries and a cursor, list_folder/continue returns changes after a cursor, and list_folder/longpoll blocks until there are changes.

Google Drive. Drive's public API also uses an opaque change cursor: a client gets a start page token, then lists changes since that token and receives a new one. Drive's original strength was cloud-native documents edited collaboratively in the browser, where the sync unit is an operation rather than a file. Google's Zanzibar paper describes the authorisation system that serves Drive and many other Google products.

OneDrive and iCloud Drive. Both integrate deeply with their operating systems: OneDrive's Files On-Demand uses the Windows Cloud Files API to present placeholders, and iCloud Drive and third-party providers use Apple's File Provider framework. These OS frameworks have become the standard way to implement on-demand files, and Dropbox moved its macOS client onto File Provider in recent years.

Syncthing and peer-to-peer sync. Open-source tools such as Syncthing sync folders directly between a user's devices with no central server. Without a server to serialise history, they need causality tracking per file, and Syncthing's protocol documentation describes using version vectors for this. They show the alternative end of the design space: no storage cost for a provider, but no always-available copy, and every conflict detection decision made by peers.

The research lineage. The ideas are older than these products. rsync (Tridgell and Mackerras, 1996) made efficient delta transfer between two copies of a file practical. LBFS (Muthitacharoen, Chen and Mazières, SOSP 2001) introduced content-defined chunking with Rabin fingerprints to a network file system and showed that chunk-level deduplication across files saves a lot of bandwidth. Coda (Kistler and Satyanarayanan, SOSP 1991) worked out disconnected operation and conflict handling for a distributed file system. Venti (Quinlan and Dorward, FAST 2002) built archival storage on content-addressed blocks identified by their SHA-1 hash. Every modern sync product combines these ideas with cloud object storage and a central metadata service.

Deep Dive: failure walkthroughsShow

A client bug starts deleting files. A new client release misreads the local tree after an OS update and concludes that thousands of files were deleted locally. It begins committing deletes. Defences, in order: the client has a mass-delete guard (if more than some threshold of files, say 1,000 or 10 percent of a folder, would be deleted in one pass, pause and ask the user); the server rate-limits deletes per device and flags anomalous spikes; deletes are tombstones with retained revisions, so recovery is a bulk restore from the journal; staged rollout of client releases limits how many users run the bug. See CI/CD and Deployment Strategies.

A metadata shard primary fails. Commits for the namespaces on that shard fail for the 10 to 30 seconds it takes to promote a replica. Clients see errors, back off and retry; their changes stay queued locally, so nothing is lost. If replication was asynchronous, the last few committed transactions might not have reached the new primary. The clients that made them still hold the content and will see from the journal that their revision is not there, and re-commit. Synchronous replication to at least one replica (semi-synchronous in MySQL terms) avoids this window at the cost of commit latency. See Database Replication.

A chunk is corrupt in storage. A downloading client re-hashes a chunk and finds a mismatch. It reports the chunk, discards the data and retries. The server marks the stored copy bad, rebuilds the chunk from the blob store's redundancy (another replica or erasure-coded fragments), or, if the store cannot, asks any client that recently uploaded or downloaded a revision containing the chunk to re-upload it. Background scrubbing should find such cases before users do.

The notification tier goes down entirely. Every device loses its push connection. Sync does not stop: devices fall back to safety-net polling of the change feed and sync within the poll interval. Users notice that changes take a few minutes instead of a few seconds. Because notifications carry no data, recovering them needs no replay; devices simply reconnect.

A region fails. Covered in the multi-region deep dive below. In short: namespaces homed in the failed region become read-only (or unavailable for commits) until failover promotes their replicas elsewhere; chunk data is already replicated across regions; devices queue local changes and sync after failover.

The GC job misbehaves. A bug makes the reference audit think a large set of chunks are unreferenced. Because the pipeline is pending-delete, then a grace period, then soft-delete, then hard-delete after a safety window, and because a sudden spike in deletion candidates trips an alert that halts GC automatically, the bug is caught while the data is still recoverable. The lesson is to treat any automated deletion of user data as a dangerous operation with rate limits, circuit breakers and human review for anomalies.

Deep Dive: multi-region designShow

Users are global, but each namespace needs a single serialised history. The usual answer is home regions:

  • Each namespace is assigned a home region, typically where its owner or most of its members are. All commits for that namespace go to the metadata primary in that region. Reads (listings, change feeds) can be served from local replicas in other regions, slightly stale, which is acceptable under our availability-first requirement.
  • Chunk data is written to the uploader's nearest region and replicated asynchronously to other regions, so that downloads anywhere are fast and a region loss does not lose data. A commit waits only for the chunk to be durable in one region (plus that region's own redundancy); cross-region copies follow within seconds to minutes.
  • Notification servers run in every region; the change bus is replicated so that a commit in one region reaches devices connected elsewhere.
  • Failover: if a home region fails, its namespaces are promoted in a secondary region. Commits that were acknowledged but not yet replicated may be lost on the metadata side; the clients that made them still hold the data and re-commit after seeing the journal, as in the shard failover case. Chunks not yet replicated are recoverable from the original region when it returns, or re-uploaded by clients.
  • Moving a namespace's home when its members move (a team relocating) is a planned migration: replicate, briefly block commits, switch the primary, unblock.

A multi-primary design, accepting commits for the same namespace in two regions, would need version vectors or similar causality tracking and conflict handling at the server, much as peer-to-peer sync does. For a file sync product the gain (slightly faster commits for some users) rarely justifies the complexity, and the home-region design is the common choice. See Multi-Region and Global Data and Consistency Models.

Deep Dive: observability for a sync serviceShow

The single most important metric is sync latency: the time from a commit on one device to that change being applied on another online device. Measure it end to end: the committing device records the commit time, receiving devices report the time they applied the change, and the service computes percentiles per region and client version. Alert on p99 regressions. It captures problems in commits, the bus, notifications, change feeds and downloads, all at once.

Other signals worth having:

  • Upload and download success rate and throughput, by client platform, network type and region. A sudden drop for one platform usually means a client release bug.
  • Conflict rate per thousand commits. A spike signals a client bug creating false conflicts (or a server bug in the parent revision check).
  • Mass-delete events and restores, by client version.
  • Commit latency and abort rate per metadata shard; journal lag between primary and replicas.
  • Notification connections per server, reconnect rate, hint fan-out time.
  • Safety-net poll hit rate: the fraction of polls that found changes the push missed. Should be near zero; if it rises, notifications are being lost.
  • Reconciliation discrepancies: orphans, missing chunks, reference count drift, corrupt chunks found by scrubbing. Missing chunks are a page-the-on-call event.
  • Storage growth and dedupe ratio, for capacity planning. See Capacity Planning and Load Testing.

Client telemetry needs care: it must not include file names or contents, and it should be aggregated and sampled. Most of these metrics need only counts, durations and error codes.

Deep Dive: spending 45 minutes on this problem in an interviewShow

A plan that fits the clock:

  • Minutes 0 to 5: requirements. Upload, download, share, sync. Files up to 50 GB. Availability over consistency, but never lose data. Ask whether versioning and conflicts are in scope.
  • Minutes 5 to 8: entities and API. File, FileMetadata, User, then mention chunks, revisions and namespaces as coming later. Sketch the naive endpoints and say they will evolve.
  • Minutes 8 to 20: high-level design. Metadata in a database, bytes in blob storage, presigned direct upload, CDN download with signed URLs, a shares table, and sync with a watcher plus a change feed and push hints.
  • Minutes 20 to 35: the large-file deep dive. Why one request fails, client-side chunking, multipart upload, ETags and ListParts, fingerprints, resumption. This is the deep dive most interviewers want.
  • Minutes 35 to 42: second deep dive, chosen by the interviewer or by you. Delta sync with content-defined chunking, the cursor-based sync protocol, or conflicts.
  • Minutes 42 to 45: wrap-up. Security (encryption, short-lived signed URLs), what you would monitor, and what you would do next.

Phrases that signal depth: "the notification is a hint, the cursor is the truth", "sequence numbers assigned in the commit transaction, not timestamps", "chunk on the client, not the server", "content-defined boundaries so an insert does not shift every chunk", "conflicted copy rather than last-writer-wins", "a GC that deletes too much destroys trust".

Deep Dive: variants and how the design shiftsShow

Cloud-first document storage (Google Drive style). If most users work in the browser and on native cloud documents, sync becomes less central than collaborative editing, search and sharing. The metadata model is similar, but conflict handling for native documents moves into an operation-based editing service, and on-demand access (no local copy) is the default.

Photo and video backup (Google Photos or iCloud Photos style). Mostly one-way upload from phones, very high volume of medium-sized immutable files, heavy server-side processing (thumbnails, transcoding, face and object recognition), and a timeline-oriented metadata model. Dedupe by content hash prevents re-uploading the same photo from two devices. Background upload under mobile OS constraints and Wi-Fi-only policies dominate the client design.

Enterprise file sharing (Box style, or Dropbox and Google Workspace business tiers). Adds admin consoles, groups from corporate directories, data loss prevention, retention policies and legal hold (which suspend deletion and GC for specific users), audit logs of every access, regional data residency (a European customer's data must stay in the EU), and customer-managed encryption keys. Most of these are policy layers on the same core, but legal hold and residency reach deep into GC and placement.

Backup products. One-way, point-in-time snapshots of whole machines, rarely restored. Optimised for dedupe ratio and cheap cold storage tiers rather than sync latency. The chunk-and-manifest design is the same; there is no notification tier.

Version control systems. Git is a content-addressed store of blobs, trees and commits, with snapshots identified by hash, three-way merges against a common ancestor, and explicit user-driven conflict resolution. Many of the ideas in this case study appear there in a different form, which makes it a useful mental model.

Small scale. For a team of a few thousand users, a single PostgreSQL database, S3 with presigned multipart uploads, a cursor-based change feed and long polling are the whole system. Namespaces, Bloom filters, custom storage and home regions are scale-driven additions; say when you would add each.

Deep Dive: what the desktop client actually doesShow

Since the hardest bugs live on the client, it is worth sketching its internals.

  • File watcher and scanner. Subscribes to OS file events for the synced folder, debounces them (editors write temp files, rename and delete in quick bursts), and records candidate changes. A periodic scanner walks the tree comparing stat information (size, modification time, inode or file id) with the local database to catch missed events.
  • Hasher and chunker. For each changed file, reads it once, cuts it into chunks, and computes chunk hashes and the content hash. It must cope with files that change while being read: hash, then re-stat, and if the file changed meanwhile, start again later.
  • Local database. Stores the three trees, cursors, the upload and download queues and a cache of known chunk hashes. SQLite in WAL mode is a common choice. Every state change is a transaction, so a crash at any point resumes cleanly.
  • Planner. Diffs the trees, computes a safe ordered set of operations, and detects conflicts.
  • Transfer workers. Upload and download chunks in parallel with bandwidth limits the user can set, retries with backoff, and reports progress.
  • Applier. Writes downloaded files into a temporary location inside the synced folder, verifies their hash, then atomically renames them into place. It sets modification times and permissions, handles files open in other applications (on Windows, a locked file cannot be replaced, so the applier must retry later), and records the result in the synced tree.
  • Notification listener. Keeps the push connection, wakes the planner on hints, and runs the safety-net poll.

Testing such a client is famously hard. Dropbox has described running large numbers of randomised tests that generate file system operations, network failures and crashes, and then check invariants such as "after sync quiesces, all replicas match" and "no file is lost". Deterministic simulation of this kind is one of the best tools for finding the rare interleavings that cause data loss.

Key Takeaways#

  • Separate the control plane from the data plane. Metadata, permissions and journals go through your services; bytes go directly between clients and blob storage using presigned upload URLs and signed CDN URLs. See Pattern: Handling Large Files and Blobs and Object Storage and Blob Storage.
  • Chunk on the client. Chunks give progress, resumption, parallelism, delta sync and deduplication. For huge single objects, use multipart upload with per-part presigned URLs, ETags or checksums, ListParts verification and lifecycle cleanup. Find resumable sessions by content fingerprint, not by name.
  • Use content-defined chunking for delta sync. Fixed-size chunks turn a one-byte insert into a full re-upload; a rolling hash such as Rabin or Gear picks boundaries from the content. Compress before encrypting, and only when it pays.
  • Sync is replication over a server-ordered log. Each namespace has a journal with sequence numbers assigned in the commit transaction; devices hold opaque cursor vectors; replay is idempotent. Push notifications are hints, the change feed is the truth, and a cheap safety-net poll catches what push misses. See Polling, Long Polling, SSE, WebSockets and Webhooks and Pattern: Pushing Realtime Updates.
  • Shard metadata by namespace so that a commit and its journal append are a single-shard transaction; model trees with parent ids, and handle case-insensitivity and Unicode normalisation. See Partitioning and Sharding.
  • Never lose a write on conflict. Optimistic concurrency with parent revisions detects conflicts; conflicted copies preserve both versions; merging belongs to formats designed for it. See Conflict Resolution, OT and CRDTs.
  • Versioning is nearly free with immutable revisions and shared chunks; restore by creating a new revision, and keep tombstones and history for the retention window. See Data Lifecycle, Tiering and Retention.
  • Shared folders as namespaces make sharing and sync scale: one membership row per member, one journal per folder. Revocation needs cache invalidation and short-lived URLs, and cannot recall files already downloaded. See Authentication and Authorization.
  • Garbage collection must be biased towards keeping data: reference counts plus audits, grace periods against the resurrection race, soft delete before hard delete. Limit cross-user dedupe to the server side to avoid side channels. See Security Fundamentals for System Design.