Skip to content
Tech Intuition
Tech Intuition

Appearance

Theme

Signal · Dark with amber

Background

Slow stars and the odd comet

Connect

Case studies · Lesson 36 of 44

Case study: design a file sync service

A senior-level walkthrough of a file sync service such as Dropbox: blocks cut by content, one stored copy of each, a change journal with cursors, conflicts and garbage collection, in tested C# with an interactive story.

Case studyApplied50 min readUpdated

  • 1 architecture diagram
  • 1 sequence flow
  • 4 data models
  • 4 API designs
  • 11 code samples
  • 9 interviewer follow-ups
  • 4 self-checks

Read first: A framework for system design interviews, Replication and sharding, Consistency and availability

By the end you will be able to
  • A change must cost in proportion to the change, not the file. Cut by fixed size, an insert of 100 bytes near the front of a 1 MiB file re-sent 1,048,676 bytes, because every later block shifted. Cut by content, the same edit sent 10,064 bytes.
  • Name every block by a hash of its bytes, store each one once, and make a file a list of names. Twenty-one versions of one file kept 1.2 MB with content-defined chunks and 10.6 MB with fixed blocks. Write the blocks first and the commit second, and sweep unreferenced blocks only behind a lease, or a commit can name a block that is gone.
  • Keep an ordered journal per folder and let each device ask what changed after its cursor. Number entries when they become visible, or a reader's cursor can skip a change forever. A notification is only a hint; the journal is the truth.
  • Decide each path from three views, what the device holds, what both sides last agreed on and what the server holds, and never lose an edit silently. In 5,000 random offline sessions, last writer wins lost an edit in 2,061, and keeping both versions lost none.

9 code samples (388 lines), collapsed so the explanation stays in focus.

A file sync service looks like one folder that exists on several devices. It is really one copy per device, each of which can change while the others are away, plus a service that makes them identical again without losing anything anyone saved. Two facts shape everything. Files are big and edits are small, so the cost of a change must follow the size of the change and not the size of the file. And any device can edit at any time, including offline, so the service has to decide what a conflict is and what to do about one.

If you learn better by watching, the Story button in the corner of the screen opens this case study as a fourteen-minute scroll: one letter changes in a big file, and you watch the system find it, send it, store it once and show it on every device. This lesson is the full version, with measured code and the questions an interviewer asks. The numbers in the story and in this lesson come from the same experiments.

HLD

Clarify the file sync problem

Spend the first minutes on questions. Each answer changes the design.

AskWhy it matters
What is synced: documents, photos, large media, source code? What are the typical and the largest file sizes?Documents are small and edited in place. Media is large and rarely edited. Block size, chunking and upload strategy depend on which one dominates
How many devices does one person have, and how many people share a folder?Fan-out is per folder. A private folder has two or three devices; a team folder can have thousands
Must it work offline, and for how long?Two devices editing offline is where every conflict starts, and a day offline is a long queue to reconcile
What must never happen?A lost edit, a corrupted file, a deleted file coming back, a conflict settled silently the wrong way, a file you can open but not read
How fresh must other devices be?Seconds, not milliseconds. A change should show up within a few seconds, which allows batching and a lazy notification path
What else rides along?Sharing and permissions, links, version history, search, previews, selective sync, mobile, admin and audit controls

A good scope for 45 minutes: desktop and mobile clients, files up to tens of gigabytes, private and shared folders, offline edits with conflicts, version history, and durability first. Mention sharing links, search and end-to-end encryption as extensions.

HLD

Estimate: bytes are bulk, metadata is hot

State assumptions out loud. They are illustrative and the interviewer may change them.

Example · estimate
users:        500M registered, 100M active a day (assumed)
devices:      2.5 each = 250M, 40% online at peak = ~100M open sockets
changes:      20 saved files a user a day = 2B a day = ~23K a second
peak:         x4 = ~90K commits a second, nearly all small
if whole:     2B changes x 2 MB = ~4 PB a day sent as whole files
new blocks:   ~35% of those bytes are blocks the store has never seen
              = ~1.4 PB a day to store (the rest is already stored)
block count:  1.4 PB / ~1 MB average = ~1.4B new blocks a day
              x ~50 B a record (32 B hash, location) = ~70 GB a day
notify:       2B changes x 1.5 other devices = ~3B hints a day = ~35K/s
metadata:     100B files x ~5 revisions x ~300 B = ~150 TB, by folder
sockets:      100M / 50,000 per gateway = ~2,000 gateways

Five conclusions:

  1. Metadata is small and hot, bytes are huge and cold. A commit is a few hundred bytes that must be fast and strongly consistent. A block is megabytes that only needs to be durable. They deserve different services and different scaling.
  2. Chunking decides the bill. Four petabytes of changes a day become 1.4 petabytes of new blocks because most blocks already exist, and every ten points of dedupe moves roughly 400 terabytes a day.
  3. Open connections dominate the fleet. A hundred million sockets is a fleet of gateways before a byte moves, so the notification path carries a hint and never data.
  4. Order matters only inside one folder. Metadata partitions by folder, which makes the biggest shared folders the hot spots.
  5. Durability beats capacity. A lost file is not recoverable, so the dangerous operation here is deletion, and it gets most of the care.

LLD

The sync contract and data model

A client does four things: ask which blocks the server lacks, send those blocks, commit a file as a list of block names, and ask what changed since its cursor. Everything else is built from those.

POST/blocks/check
auth
device token, scoped to one namespace
body
{ namespace, hashes: [ up to 1,000 ] }
returns
{ missing: [ the hashes the server does not hold ] }
note
also leases the blocks it reports as present, so they survive until the commit
PUT/blocks/{hash}
body
the block's bytes, compressed, up to a few MB
note
idempotent, the same bytes under the same name any number of times are one block
  • 200stored and durable, and the bytes hash to the name
  • 400the bytes do not match the name
POST/commit
body
{ namespace, path, blocks: [ hashes in order ], size, baseRev, changeId }
note
changeId makes a retry change nothing
  • 200{ rev, seq }, written to the journal before this reply
  • 409{ currentRev }, the file moved on since baseRev
  • 410a named block is missing, upload it and commit again
GET/changes?namespace=N&cursor=C&wait=30
returns
{ entries: [ { seq, fileId, path, rev, blocks, op } ], cursor, hasMore }
note
holds the request open until there is news or 30 seconds pass
  • 410the cursor is older than the journal, list the tree and start again

Four tables carry the state. Files have stable ids, so a rename or a move is a change to the tree and never a change to the bytes.

file_entriesthe tree, partitioned by namespace
  • namespace_idbigint

    PKSHARD KEY
  • file_idbigint

    stable across renames and moves

    PK
  • parent_idbigint

    the folder it is in

    INDEX
  • nametext

    unique among live siblings, compared without case

  • is_folderboolean

  • head_revint

    newest revision, 0 for a folder

  • deletedboolean

revisionsimmutable, one per change to a file
  • namespace_idbigint

    PKSHARD KEY
  • file_idbigint

    PK
  • revint

    PK
  • blocksblob

    the ordered hashes, 32 bytes each

  • sizebigint

  • content_hashchar(64)

    one hash for the whole file, for quick equality

journalappend-only, one sequence per namespace
  • namespace_idbigint

    PKSHARD KEY
  • seqbigint

    1, 2, 3 ... one per change, no gaps

    PK
  • file_idbigint

  • revint

  • opsmallint

    add, edit, move or delete

  • change_iduuid

    a retry of the same commit finds this and changes nothing

    UNIQUE
  • created_attimestamptz

Numbered inside the commit, under the namespace's lock, so sequence order is visibility order.

blockscontent-addressed, shared by every file that contains them
  • hashchar(64)

    PKSHARD KEY
  • sizeint

  • refsint

    revisions that name it

  • locationtext

    container and offset in object storage

  • touched_attimestamptz

    last upload or check, for the sweeper's grace period

HLD

The high-level design of a file sync service

Fig. A file sync service: metadata apart from blocks
Fig. A file sync service: metadata apart from blocks
Fig. One saved file, from the laptop to the phone
Fig. One saved file, from the laptop to the phone

Read it as two planes. The block plane is a content-addressed store: a block's name is a hash of its bytes, blocks never change, and any number of files can share one. The metadata plane is a strongly consistent database sharded by folder (a namespace), where a file is a list of block names and every change is a revision and an entry in an ordered journal. The client sits in the middle with a local database and three views of each path, and a small notifier tells a device that something changed without saying what. The first three deep dives build the planes and the contract between them. The sync engine on the device comes after, because it needs both.

LLD

Deep dive: cutting a file into blocks

The cheapest byte to send is the one you do not send. A client cannot ask a server for a diff of a file the server has only ever seen as a whole, so it cuts the file into blocks, names each block by a hash of its bytes, and asks which names the server lacks. A file becomes a list of names, and a change to a file becomes a change to the list.

The simplest cut is a block every N bytes. Dropbox documents 4 MiB blocks hashed with SHA-256, and its API defines a file's content hash as the SHA-256 of the concatenated block hashes. Syncthing's protocol also uses fixed blocks, from 128 KiB to 16 MiB depending on the file's size. Fixed blocks are cheap and trivial to parallelise. They have one weakness: an edit that overwrites bytes in place changes one block, but an edit that inserts or deletes bytes moves every byte after it, so every later block holds different bytes and gets a different name.

The code below cuts a file both ways. The chunker for the second way is content-defined chunking: slide a rolling hash along the file, and cut after a byte whenever the hash of the bytes just before it has a rare property, here that its low 12 bits are zero. On random data that happens about once in every 4,096 bytes. Because the decision depends only on the bytes just before the cut, the same bytes make the same cut wherever they sit in the file, so insert something at the front and the boundaries after it come back where they were.

C# · Cutting a file into blocks110 lines
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;

sealed class Rng                                  // mulberry32: the same generator and seeds as the story
{
    uint a;
    public Rng(uint seed) { a = seed; }
    public uint NextUInt()
    {
        a += 0x6D2B79F5u;
        uint t = a;
        t = (t ^ (t >> 15)) * (t | 1u);
        t ^= t + (t ^ (t >> 7)) * (t | 61u);
        return t ^ (t >> 14);
    }
    public double Next() => NextUInt() / 4294967296.0;
}

record Chunk(int Start, int Length);

static class Chunker
{
    // A fixed lookup table, so every machine cuts the same bytes in the same places.
    public static uint[] GearTable(uint seed)
    {
        var r = new Rng(seed);
        var g = new uint[256];
        for (int i = 0; i < 256; i++) g[i] = r.NextUInt();
        return g;
    }

    public static List<Chunk> Fixed(byte[] d, int size)
    {
        var list = new List<Chunk>();
        for (int s = 0; s < d.Length; s += size) list.Add(new Chunk(s, Math.Min(size, d.Length - s)));
        return list;
    }

    // Cut after a byte when a rolling hash of the bytes just before it ends in `bits` zero bits. Never cut a chunk
    // shorter than `min`, and always cut at `max`. The hash only remembers about `bits` bytes, so it forgets what
    // came before an edit almost at once.
    public static List<Chunk> Cdc(byte[] d, int min, int bits, int max, uint[] gear)
    {
        var list = new List<Chunk>();
        uint mask = (1u << bits) - 1, h = 0;
        int start = 0;
        for (int i = 0; i < d.Length; i++)
        {
            h = (h << 1) + gear[d[i]];
            int len = i - start + 1;
            if ((len >= min && (h & mask) == 0) || len >= max) { list.Add(new Chunk(start, len)); start = i + 1; }
        }
        if (start < d.Length) list.Add(new Chunk(start, d.Length - start));
        return list;
    }

    public static string Id(byte[] d, Chunk c) =>
        Convert.ToHexString(SHA256.HashData(new ReadOnlySpan<byte>(d, c.Start, c.Length)))[..16];

    // How many chunks of `after` does the other side not have yet, and how many bytes is that?
    public static (int Count, long Bytes) Fresh(byte[] before, List<Chunk> had, byte[] after, List<Chunk> now)
    {
        var have = new HashSet<string>(had.Select(c => Id(before, c)));
        var fresh = now.Where(c => !have.Contains(Id(after, c))).ToList();
        return (fresh.Count, fresh.Sum(c => (long)c.Length));
    }

    // Dropbox documents its content hash like this: 4 MiB blocks, SHA-256 of each, then SHA-256 of the digests joined.
    public static string ContentHash(byte[] d)
    {
        var digests = new List<byte>();
        for (int s = 0; s < d.Length; s += 4 << 20)
            digests.AddRange(SHA256.HashData(new ReadOnlySpan<byte>(d, s, Math.Min(4 << 20, d.Length - s))));
        return Convert.ToHexString(SHA256.HashData(digests.ToArray())).ToLowerInvariant();
    }
}

static class Files
{
    public static byte[] Random(int n, uint seed)
    {
        var r = new Rng(seed);
        var d = new byte[n];
        for (int i = 0; i < n; i++) d[i] = (byte)(r.NextUInt() >> 24);
        return d;
    }
    public static byte[] Overwrite(byte[] d, int at, int n, uint seed)
    {
        var o = (byte[])d.Clone();
        Array.Copy(Random(n, seed), 0, o, at, n);
        return o;
    }
    public static byte[] Insert(byte[] d, int at, int n, uint seed)
    {
        var o = new byte[d.Length + n];
        Array.Copy(d, 0, o, 0, at);
        Array.Copy(Random(n, seed), 0, o, at, n);
        Array.Copy(d, at, o, at + n, d.Length - at);
        return o;
    }
    public static byte[] Delete(byte[] d, int at, int n)
    {
        var o = new byte[d.Length - n];
        Array.Copy(d, 0, o, 0, at);
        Array.Copy(d, at + n, o, at, d.Length - at - n);
        return o;
    }
}

The hash is a Gear hash, h = (h << 1) + table[byte], the rolling hash that FastCDC popularised: each step shifts older bytes up and out of the word, so the low bits depend only on the last few bytes. The older Rabin fingerprint does the same job with more arithmetic per byte. Two limits keep the chunks usable. A minimum stops a run of lucky bytes from producing slivers, and a maximum forces a cut through data with no cut points in it, such as a long run of zeros.

Now one file and four small edits. The file is 1 MiB of random bytes, which no compressor could shrink. It cuts into 256 fixed blocks of 4 KiB, or into 188 content-defined chunks that average 5,577 bytes, and every number below is printed by this program and asserted by the lesson's tests.

C# · A harness: one edit, two ways of cutting30 lines
using System.Diagnostics;

var gear = Chunker.GearTable(1);
var file = Files.Random(1 << 20, 42);                         // 1 MiB of bytes that no compressor could shrink
var oldFixed = Chunker.Fixed(file, 4096);
var oldCdc = Chunker.Cdc(file, 1024, 12, 16384, gear);
Console.WriteLine($"{oldFixed.Count} fixed blocks; {oldCdc.Count} content-defined chunks, {file.Length / oldCdc.Count} bytes on average");
Debug.Assert(oldFixed.Count == 256 && oldCdc.Count == 188);

var cases = new (string Name, byte[] After)[]
{
    ("overwrite 100 bytes in the middle", Files.Overwrite(file, 500_000, 100, 7)),
    ("insert 100 bytes at the front", Files.Insert(file, 100, 100, 7)),
    ("delete 100 bytes in the middle", Files.Delete(file, 500_000, 100)),
    ("append 100 bytes", Files.Insert(file, file.Length, 100, 7)),
};
var sent = new List<(long Fixed, long Cdc)>();
foreach (var (name, after) in cases)
{
    var f = Chunker.Fresh(file, oldFixed, after, Chunker.Fixed(after, 4096));
    var c = Chunker.Fresh(file, oldCdc, after, Chunker.Cdc(after, 1024, 12, 16384, gear));
    sent.Add((f.Bytes, c.Bytes));
    Console.WriteLine($"{name,-34} fixed: {f.Count,3} blocks {f.Bytes,9:N0} bytes | content-defined: {c.Count} chunk(s) {c.Bytes,6:N0} bytes");
}
Debug.Assert(sent[0].Fixed == 4_096 && sent[0].Cdc == 3_916);            // an overwrite touches one block either way
Debug.Assert(sent[1].Fixed == 1_048_676 && sent[1].Cdc == 10_064);       // an insert at the front shifts every fixed block
Debug.Assert(sent[2].Fixed == 548_764 && sent[2].Cdc == 3_816);          // a delete shifts everything after it
Debug.Assert(sent[3].Fixed == 100 && sent[3].Cdc == 1_123);              // an append touches only the last block
var small = Files.Random(1000, 3);
Debug.Assert(Chunker.ContentHash(small) == Convert.ToHexString(SHA256.HashData(SHA256.HashData(small))).ToLowerInvariant());
Edit to a 1 MiB fileFixed 4 KiB blocksContent-defined chunks (about 5.6 KiB)
Overwrite 100 bytes in the middle1 block, 4,096 bytes1 chunk, 3,916 bytes
Insert 100 bytes near the front257 blocks, 1,048,676 bytes1 chunk, 10,064 bytes
Delete 100 bytes in the middle134 blocks, 548,764 bytes1 chunk, 3,816 bytes
Append 100 bytes1 block, 100 bytes1 chunk, 1,123 bytes

An overwrite costs one block either way. An insert or a delete is where they part company: fixed blocks re-send everything after the edit, about a hundred times more than content-defined chunks. The append is fixed blocks' best case, since only the last block changes. The result is typical and not guaranteed: an edit usually changes one chunk, and an edit close to a cut can change two, because the hash window reaches a few bytes past it. In the story's toy example, about three edits in four change one chunk and the rest change two.

What size? The same program can answer how big a chunk should be. Cut 2 MiB by content at four target sizes, insert 100 bytes at thirty random places, and measure what each insert sends. Then work out what the chunk records cost at 48 bytes each (a 32-byte hash and about 16 bytes of location and bookkeeping) for a tebibyte of data.

C# · A harness: what size of chunk?20 lines
var sizes = new List<(int Target, int Chunks, long Mean, long Sent, long Gb)>();
foreach (int bits in new[] { 10, 12, 14, 16 })
{
    int target = 1 << bits;
    var big = Files.Random(2 << 20, 42);
    var before = Chunker.Cdc(big, target / 4, bits, target * 4, gear);
    var at = new Rng(9);
    long total = 0;
    for (int k = 0; k < 30; k++)
    {
        var after = Files.Insert(big, (int)(at.Next() * big.Length), 100, (uint)k);
        total += Chunker.Fresh(big, before, after, Chunker.Cdc(after, target / 4, bits, target * 4, gear)).Bytes;
    }
    long mean = big.Length / before.Count;
    long gb = (long)Math.Round((double)(1L << 40) / mean * 48 / 1e9);    // chunk records for 1 TiB
    sizes.Add((target, before.Count, mean, total / 30, gb));
    Console.WriteLine($"target {target,6:N0} B: {before.Count,5} chunks of {mean,6:N0} B on average; a 100-byte insert sends {total / 30,7:N0} B; 1 TiB is {gb} GB of records");
}
Debug.Assert(sizes.Select(s => s.Chunks).SequenceEqual(new[] { 1544, 372, 99, 23 }));
Debug.Assert(sizes.Select(s => s.Sent).SequenceEqual(new long[] { 2515, 10307, 33960, 126765 }));
Target sizeChunks in 2 MiBAverage sizeA 100-byte insert sendsChunk records per TiB
1 KiB1,5441,358 B2,515 Babout 39 GB
4 KiB3725,637 B10,307 Babout 9 GB
16 KiB9921,183 B33,960 Babout 2 GB
64 KiB2391,180 B126,765 Babout 1 GB

Smaller chunks send less per edit and cost more of everything else: more records to keep, more hashes to compute and compare, more requests. An edit lands in a chunk with probability proportional to its length, so the chunk it hits is longer than the average, and an insert sends one and a half to two times the average chunk. Real systems sit between tens of kilobytes and a few megabytes: the chunker library behind restic defaults to 512 KiB to 8 MiB with a 1 MiB average, and Dropbox's published block size is 4 MiB. With one mask, chunk sizes spread widely, which is why FastCDC adds normalized chunking, a stricter mask before the average size and a looser one after it. Production chunkers also spread the mask's bits across the word to lengthen the hash's memory, which this program keeps short for readability.

Four practical rules come with the cut.

  • Cut before you compress or encrypt. A block's name must be a function of its plaintext bytes, or the same bytes in two places get two names. Compress each block after naming it, then encrypt it.
  • Hash what you send. A file that changes while the client reads it can produce a block list that never existed. Read a block, hash those bytes, send those same bytes, and compare size and modification time at the end. If they moved, start the file again.
  • Know what the bytes are. A .docx is a zip with each part compressed on its own, so a small edit rewrites one part and the directory at the end, and a cut by content still finds the other parts. Compressing the whole archive would scramble everything after the first change.
  • rsync is a different tool. Its rolling checksum finds matching blocks at any offset, but it compares against the old file's block signatures, so both sides must hold the old version. A sync client wants to decide alone, with nothing but a list of names to ask the server about.

LLD

Deep dive: one copy of every block

Once a block's name depends on its content, the store can be dumb and strict: an immutable map from name to bytes. Putting a block that already exists changes nothing, so the first half of the upload protocol is a single question: here are the names I want to store, which of them do you lack?

C# · A block store and the upload protocol23 lines
sealed class BlockStore
{
    readonly Dictionary<string, int> sizes = new();
    public long Bytes => sizes.Values.Sum(s => (long)s);

    // First half of the protocol: here are the ids I want to store. Which ones do you not have?
    public List<string> Missing(IEnumerable<string> ids) => ids.Distinct().Where(id => !sizes.ContainsKey(id)).ToList();
    public void Put(string id, int size) => sizes[id] = size;
}

static class Client
{
    // Cut, offer the ids, send only what the server asked for, and report the bytes that travelled.
    public static long Upload(BlockStore store, byte[] data, List<Chunk> chunks)
    {
        var ids = chunks.Select(c => Chunker.Id(data, c)).ToList();
        var missing = new HashSet<string>(store.Missing(ids));
        long sent = 0;
        for (int i = 0; i < chunks.Count; i++)
            if (missing.Remove(ids[i])) { store.Put(ids[i], chunks[i].Length); sent += chunks[i].Length; }
        return sent;
    }
}
C# · A harness: twenty saves of one file18 lines
var fixedStore = new BlockStore();
var cdcStore = new BlockStore();
long first = Client.Upload(cdcStore, file, oldCdc);
long again = Client.Upload(cdcStore, file, oldCdc);              // someone else uploads the very same file
Debug.Assert(first == file.Length && again == 0);

long sentFixed = Client.Upload(fixedStore, file, oldFixed), sentCdc = first;
var current = file;
var pick = new Rng(5);
for (int v = 1; v <= 20; v++)                                      // each save inserts 100 bytes somewhere
{
    current = Files.Insert(current, (int)(pick.Next() * current.Length), 100, (uint)v);
    sentFixed += Client.Upload(fixedStore, current, Chunker.Fixed(current, 4096));
    sentCdc += Client.Upload(cdcStore, current, Chunker.Cdc(current, 1024, 12, 16384, gear));
}
Console.WriteLine($"21 versions. fixed: sent {sentFixed:N0}, stored {fixedStore.Bytes:N0}; content-defined: sent {sentCdc:N0}, stored {cdcStore.Bytes:N0}");
Debug.Assert(sentFixed == 10_625_544 && fixedStore.Bytes == 10_625_544);
Debug.Assert(sentCdc == 1_242_142 && cdcStore.Bytes == 1_242_142);

The first upload sends all 1,048,576 bytes. A second person uploading the very same file sends nothing at all, because every name is already on the shelf. Then twenty saves, each inserting 100 bytes at a random place. With fixed blocks, each save shifts roughly half the file, so the 21 versions sent and kept 10,625,544 bytes. With content-defined chunks they sent and kept 1,242,142, about a tenth, and that is for history too: version history costs only the chunks that changed, which is why a store with deduplication can keep thirty days of versions cheaply.

Blocks first, then the commit. A commit is a promise that the file can be read, so never make the promise before the data exists. There are two orders, and a crash at the wrong moment tells them apart.

  • Blocks, then commit. If the client dies after uploading and before committing, the server holds orphans: blocks that no file names. They are harmless, a little wasteful, and useful, because the retry finds them already there and commits without sending a byte.
  • Commit, then blocks. Optimistic, because the file appears sooner. If the client dies in between, the journal has an entry for a file whose blocks are missing. Every other device is told about it, asks for the blocks and gets an error: the file can be listed and cannot be opened, until the author comes back.

The server defends against the second order anyway. The commit checks that every block it names exists, in the same transaction that takes a reference on each, and answers 410 if one is gone.

Garbage. A block with no references is garbage, and deleting it is the most dangerous thing the store does. Unreferenced blocks come from orphans and from old revisions once their retention ends. Reference counts make deletion cheap and drift whenever a bug or a crash skips an update, so run a mark and sweep from the metadata now and then to make the counts honest. The danger is a race. A client asks which blocks the server lacks and is told it has them all, so it skips the upload. A moment later the sweeper finds one of those blocks unreferenced and old, and deletes it. Then the commit arrives, naming a block that no longer exists.

C# · A shelf of blocks and a sweeper35 lines
sealed class Shelf
{
    sealed class Entry { public int Refs; public long Touched; }
    readonly Dictionary<string, Entry> blocks = new();
    public bool Has(string id) => blocks.ContainsKey(id);

    public void Put(string id, long now) => blocks[id] = new Entry { Touched = now };

    // "Which of these do you lack?" An id we answer "have it" for must still be here when the commit arrives.
    public List<string> Missing(IEnumerable<string> ids, long now, bool pin)
    {
        var missing = new List<string>();
        foreach (var id in ids)
            if (blocks.TryGetValue(id, out var e)) { if (pin) e.Touched = now; }
            else missing.Add(id);
        return missing;
    }

    // A commit takes a reference on each block, and refuses if one has gone.
    public bool Commit(IEnumerable<string> ids, bool verify)
    {
        var list = ids.ToList();
        if (verify && !list.All(Has)) return false;
        foreach (var id in list) if (blocks.TryGetValue(id, out var e)) e.Refs++;
        return true;
    }

    // Delete blocks that nothing references and nobody has touched for `grace`.
    public int Sweep(long now, long grace)
    {
        var dead = blocks.Where(kv => kv.Value.Refs == 0 && now - kv.Value.Touched >= grace).Select(kv => kv.Key).ToList();
        foreach (var id in dead) blocks.Remove(id);
        return dead.Count;
    }
}
C# · A harness: a sweeper that races a commit
foreach (var (pin, verify) in new[] { (false, false), (false, true), (true, false) })
{
    var shelf = new Shelf();
    shelf.Put("d4", 0);                                              // left behind at time 0 by an upload that never committed
    var need = shelf.Missing(new[] { "d4" }, 99, pin);               // time 99: another client offers the same block
    Debug.Assert(need.Count == 0);                                   // "have it": it will skip the upload
    shelf.Sweep(100, 100);                                           // time 100: the sweeper finds it unreferenced and old
    bool ok = shelf.Commit(new[] { "d4" }, verify);                  // time 101: the commit arrives
    Console.WriteLine($"pin {pin,-5} verify {verify,-5}: commit {(ok ? "accepted" : "refused ")}, block {(shelf.Has("d4") ? "present" : "gone")}");
    Debug.Assert(ok == shelf.Has("d4") || !verify);                  // only the unchecked, unpinned run accepts a missing block
}
Pin on checkVerify at commitWhat happens at time 101
NoNoThe commit is accepted and the block is gone: a file that cannot be opened
NoYesThe commit is refused, and the client uploads the block and commits again: correct, and wasteful
YesNoThe commit is accepted and the block is present: the sweeper skipped it

The fix is to use both defences. Pin every block the server says it has: the check renews its last-touched time, so the grace period starts again, and a sweeper that only deletes blocks untouched for longer than the longest upload and its retries cannot take one that is about to be committed. Verify at commit as the last line of defence, in the transaction that takes the references. Run the mark phase against a snapshot of the metadata and never free a block younger than the snapshot. Deletion needs a delay, a log and an undo.

The privacy cost of sharing blocks. If the store deduplicates across users, "the server already has this block" is information. Harnik, Pinkas and Shulman-Peleg described the side channel in 2010: someone who guesses a file's hash can learn whether anyone stored it by watching whether the upload was skipped. Worse, a client trusted to say it holds a hash can claim content it never had. Mulazzani and colleagues showed that against Dropbox in 2011, where spoofing the hash of a chunk the server already held gave access to its content. The defences are to make the client prove it holds the bytes, for example with a challenge over random ranges (the proofs of ownership of Halevi and colleagues, 2011), to deduplicate only within an account or team, or to give up cross-user dedupe for private content. Convergent encryption, where the key comes from the content, deduplicates encrypted blocks and leaks equality.

LLD

Deep dive: the journal, cursors and notifications

A device that was offline for a day needs one question and one answer: what changed since I last looked? The answer is a journal: an append-only list of changes in each namespace, numbered 1, 2, 3 without gaps, where each entry names the file, its new revision and its block list. A device keeps a cursor, the number of the last entry it has applied, and asks for everything after it. That turns synchronisation into replaying a log from where you stopped, which is idempotent and resumable by construction. Dropbox's public API has the same shape: a cursor that list_folder/continue takes, and a longpoll call that holds the connection open until there is something new or a timeout.

The write side is a compare-and-swap. A commit carries the revision its author started from, the base revision, and the server accepts it only if the file is still at that revision. A commit written against a stale revision is the signal of a conflict, and it comes back as a 409 and not as a silent overwrite. A change id makes a retry harmless.

C# · A namespace: commit against a base revision, a journal, a cursor45 lines
enum Result { Ok, Conflict }

sealed class Namespace
{
    record Head(int Rev, string[] Blocks);
    readonly Dictionary<string, Head> head = new();
    readonly Dictionary<string, int> applied = new();             // change id -> revision, so a retry changes nothing
    public readonly List<(int Seq, string Path, int Rev)> Journal = new();

    public (Result Result, int Rev) Commit(string path, string[] blocks, int baseRev, string changeId)
    {
        if (applied.TryGetValue(changeId, out int done)) return (Result.Ok, done);
        int current = head.TryGetValue(path, out var h) ? h.Rev : 0;
        if (current != baseRev) return (Result.Conflict, current);
        head[path] = new Head(current + 1, blocks);
        Journal.Add((Journal.Count + 1, path, current + 1));      // numbered here, in the order changes become visible
        applied[changeId] = current + 1;
        return (Result.Ok, current + 1);
    }

    // Everything after the cursor, and the cursor to ask with next time.
    public (List<(int Seq, string Path, int Rev)> Entries, int Cursor) Changes(int cursor)
    {
        var entries = Journal.Where(e => e.Seq > cursor).ToList();
        return (entries, entries.Count == 0 ? cursor : entries[^1].Seq);
    }
}

// A journal that numbers entries when the work starts, or when it becomes visible.
sealed class SeqLog
{
    readonly bool atStart;
    int next, ticket;
    readonly Dictionary<int, (int Seq, string Path)> begun = new();
    readonly List<(int Seq, string Path)> visible = new();
    public SeqLog(bool atStart) { this.atStart = atStart; }

    public int Begin(string path) { int id = ++ticket; begun[id] = (atStart ? ++next : 0, path); return id; }
    public void Finish(int id) { var (seq, path) = begun[id]; visible.Add((atStart ? seq : ++next, path)); }
    public (List<string> Paths, int Cursor) Changes(int cursor)
    {
        var got = visible.Where(e => e.Seq > cursor).OrderBy(e => e.Seq).ToList();
        return (got.Select(e => e.Path).ToList(), got.Count == 0 ? cursor : got.Max(e => e.Seq));
    }
}
C# · A harness: conflicts, retries and a cursor that skips22 lines
var ns = new Namespace();
var c1 = ns.Commit("thesis.docx", new[] { "a1", "b2", "c3" }, 0, "laptop-1");
var c2 = ns.Commit("thesis.docx", new[] { "a1", "b2", "c9" }, 1, "laptop-2");
var c3 = ns.Commit("thesis.docx", new[] { "a1", "x7", "c3" }, 1, "phone-1");     // written against revision 1: too late
var c4 = ns.Commit("thesis.docx", new[] { "a1", "b2", "c9" }, 1, "laptop-2");    // the laptop retries after a lost reply
Debug.Assert(c1 == (Result.Ok, 1) && c2 == (Result.Ok, 2) && c3 == (Result.Conflict, 2) && c4 == (Result.Ok, 2));
Debug.Assert(ns.Journal.Count == 2);                                               // the retry added nothing
var (news, cursor) = ns.Changes(1);
Debug.Assert(news.Count == 1 && news[0].Rev == 2 && cursor == 2);

foreach (bool atStart in new[] { true, false })
{
    var log = new SeqLog(atStart);
    int slow = log.Begin("a.mov");          // a big upload begins first ...
    int quick = log.Begin("b.txt");         // ... a small one begins second and finishes first
    log.Finish(quick);
    var (seen, at) = log.Changes(0);        // the phone pulls now and keeps its cursor
    log.Finish(slow);
    seen.AddRange(log.Changes(at).Paths);   // it pulls again later
    Console.WriteLine($"numbered at {(atStart ? "start " : "commit")}: the phone saw {string.Join(", ", seen)}");
    Debug.Assert(seen.Contains("a.mov") == !atStart);
}

The first half is the contract. The laptop's second commit lands as revision 2. The phone's commit was written against revision 1 and arrives after revision 2 exists, so it gets a conflict and the current revision, 2. The laptop's retry, a repeat of a commit that did land, returns the same revision and adds no journal entry.

The sequence number trap. The second half is the one that goes wrong in production. Suppose the journal numbers an entry when the work begins, say with an auto-increment column, and not when it becomes visible. A slow upload starts first and gets number 13. A quick one starts second, gets 14, and commits first. A device that pulls in that gap sees entry 14 and moves its cursor to 14. When 13 commits a moment later, the device asks for everything after 14 and never sees it. The program numbers entries both ways and prints the result: numbered at start, the phone saw only b.txt; numbered at commit, it saw both. Nothing errors, and a file is missing on one device for good.

A cursor is only safe if entries become visible in the order of their numbers. The fix is to take the number inside the commit transaction, under a per-namespace lock, so that commit order and number order are the same thing. That serialises commits within one namespace, which is fine because they are small and a namespace is the unit of order anyway. When commits are too frequent for that, readers stop at the lowest sequence number still in flight, or read from the database's own commit log, which is ordered by commit.

Notifications are hints. A device does not poll every second, and the server does not push data. When a commit lands, the metadata service tells a notifier that the namespace changed, and the notifier sends each connected device one small message: something changed. The device then pulls from its cursor. Because the journal is the truth, a lost, late or duplicated hint is harmless, and a slow periodic poll is the safety net for a device that missed one. Hints for the same namespace to the same device coalesce, since a burst of a hundred commits needs one pull and not a hundred.

Cursors expire. Journals are trimmed, and a cursor older than the oldest entry cannot be answered, so the server says so (410, which Dropbox calls a reset) and the device rebuilds from a full listing. Take the cursor first, then list the tree, then replay from that cursor: a change that landed during the listing may be applied twice, which is harmless, and none is applied zero times. A move between two namespaces has no single journal to live in, so do it as an add in the destination and then a remove in the source: for a moment the file exists in both, never in neither.

LLD

Deep dive: the sync engine and conflicts

The server is the easy half. The device has to find what changed on a disk it does not own, decide what to do about each path, and apply the result safely while the user keeps working. Dropbox's engineers have described their desktop engine as three trees: Remote, what the server holds; Local, what is on the disk; and Synced, the last state both agreed on. The synced tree is the merge base, and from the three the correct operations can be derived and checked, instead of being stored as a queue of half-done tasks that can drift.

Events lie. Every operating system reports file changes, and every one can lose some. Linux's inotify drops events when its queue fills and sends an overflow event with no file attached. Windows's ReadDirectoryChangesW can overflow its buffer, return success and report zero bytes, with everything discarded. macOS's FSEvents coalesces events and sets a flag telling you to scan a directory tree again. So treat events as hints, always be able to rescan, and compare size and modification time first and a hash only when they differ. Wait for a file to settle before reading it, because editors save by writing a temporary file and renaming it over the target, so the stream shows a create and a rename and not a change. And recognise your own writes, or the client uploads the file it just downloaded and ping-pongs forever.

The decision for one path. The device holds a version, the synced tree holds the one both sides last agreed on, and the server holds a third. Each can be a content hash or nothing, and the rule is a three-way merge.

C# · Merging three views of one path85 lines
enum Step { Nothing, Upload, Download, DeleteRemote, DeleteLocal, Conflict }

static class Merge
{
    // What this device holds now, what both sides last agreed on, and what the server holds now. null means no such file.
    public static Step Decide(string local, string synced, string remote)
    {
        if (local == remote) return Step.Nothing;                                         // the same change on both sides, or none
        if (local == synced) return remote == null ? Step.DeleteLocal : Step.Download;     // only they changed it
        if (remote == synced) return local == null ? Step.DeleteRemote : Step.Upload;      // only we changed it
        if (local == null) return Step.Download;                                          // we deleted, they edited: the edit survives
        if (remote == null) return Step.Upload;                                           // they deleted, we edited: the edit survives
        return Step.Conflict;                                                             // both edited it, differently: keep both
    }

    // The policy that keeps no copy: whoever syncs last overwrites.
    public static Step LastWriterWins(string local, string synced, string remote)
    {
        if (local == remote) return Step.Nothing;
        if (local != synced) return local == null ? Step.DeleteRemote : Step.Upload;
        return remote == null ? Step.DeleteLocal : Step.Download;
    }
}

sealed class Device
{
    public readonly string Name;
    public Dictionary<string, string> Local = new(), Synced = new();
    public Device(string name, Dictionary<string, string> start) { Name = name; Local = new(start); Synced = new(start); }

    public void Sync(Dictionary<string, string> server, bool keepBoth)
    {
        foreach (var p in Local.Keys.Union(Synced.Keys).Union(server.Keys).ToList())
        {
            Local.TryGetValue(p, out var l); Synced.TryGetValue(p, out var s); server.TryGetValue(p, out var r);
            switch (keepBoth ? Merge.Decide(l, s, r) : Merge.LastWriterWins(l, s, r))
            {
                case Step.Upload: server[p] = l; Synced[p] = l; break;
                case Step.Download: Local[p] = r; Synced[p] = r; break;
                case Step.DeleteRemote: server.Remove(p); Synced.Remove(p); break;
                case Step.DeleteLocal: Local.Remove(p); Synced.Remove(p); break;
                case Step.Nothing: if (l == null) Synced.Remove(p); else Synced[p] = l; break;
                case Step.Conflict:
                    string copy = $"{p} ({Name}'s conflicted copy)";
                    Local[copy] = l; Synced[copy] = l; server[copy] = l;      // our version survives as a file of its own
                    Local[p] = r; Synced[p] = r;                              // and the path takes the server's version
                    break;
            }
        }
    }
}

static class Sessions
{
    // Two devices edit offline, then sync. Returns the sessions that lost an edit, and the ones that ended different.
    public static (int Lost, int Different) Run(bool keepBoth, int runs, uint seed)
    {
        var r = new Rng(seed);
        int lost = 0, different = 0;
        for (int run = 0; run < runs; run++)
        {
            var server = new Dictionary<string, string> { ["a"] = "a0", ["b"] = "b0", ["c"] = "c0" };
            var devices = new[] { new Device("laptop", server), new Device("phone", server) };
            var wanted = new List<string>();
            foreach (var d in devices)
            {
                int n = 1 + (int)(r.Next() * 3);
                for (int k = 0; k < n; k++)
                {
                    string p = "abcdef"[(int)(r.Next() * 6)].ToString();
                    if (d.Local.ContainsKey(p) && r.Next() >= 0.8) d.Local.Remove(p);
                    else d.Local[p] = $"{d.Name[0]}{k}.{run}";                 // an edit nobody else has ever written
                }
                wanted.AddRange(d.Local.Where(kv => !d.Synced.TryGetValue(kv.Key, out var s) || s != kv.Value).Select(kv => kv.Value));
            }
            if (r.Next() < 0.5) devices = new[] { devices[1], devices[0] };
            devices[0].Sync(server, keepBoth);
            devices[1].Sync(server, keepBoth);
            devices[0].Sync(server, keepBoth);
            if (wanted.Any(w => !server.ContainsValue(w))) lost++;
            if (devices.Any(d => !d.Local.OrderBy(k => k.Key).SequenceEqual(server.OrderBy(k => k.Key)))) different++;
        }
        return (lost, different);
    }
}
C# · A harness: five thousand offline sessions
Debug.Assert(Merge.Decide("v2", "v1", "v1") == Step.Upload && Merge.Decide("v1", "v1", "v2") == Step.Download);
Debug.Assert(Merge.Decide("v2", "v1", "v3") == Step.Conflict && Merge.Decide("v2", "v2", "v2") == Step.Nothing);
Debug.Assert(Merge.Decide(null, "v1", "v2") == Step.Download && Merge.Decide("v2", "v1", null) == Step.Upload);
var lww = Sessions.Run(false, 5000, 7);
var both = Sessions.Run(true, 5000, 7);
Console.WriteLine($"last writer wins: {lww.Lost} sessions lost an edit, {lww.Different} ended different");
Console.WriteLine($"keep both:        {both.Lost} sessions lost an edit, {both.Different} ended different");
Debug.Assert(lww.Lost == 2061 && lww.Different == 0);
Debug.Assert(both.Lost == 0 && both.Different == 0);
This deviceSyncedServerWhat the device does
v1v1v1Nothing: no one changed it
v2v1v1Upload: only this device changed it
v1v1v2Download: only the other side changed it
v2v1v2Nothing: both made the same change
v2v1v3Conflict: both changed it, differently. Keep both
deletedv1v2Download: it was edited elsewhere, so the edit survives the delete
v2v1deletedUpload: it was edited here, so the edit survives the delete

Last writer wins looks fine in a demo and loses data without telling anyone. The harness runs 5,000 sessions in which a laptop and a phone each make one to three offline edits among six paths, then sync in a random order. Under last writer wins, 2,061 sessions lost an edit, whose content appeared nowhere in the end. Under keep-both, none did, and under neither did a device end up different from the server. The sessions are deliberately cramped, so collisions are common. The point is not the rate: one policy can destroy work with no trace, and the other cannot.

Keeping both means the device whose commit lost renames its version to thesis (Phone's conflicted copy).docx and uploads it as a new file, then takes the server's version into the original path. Dropbox names its copies this way, and Syncthing keeps the winner under the original name and renames the loser to a .sync-conflict- file with a date, a time and the id of the device that changed it. A conflicted copy is itself a file, so it syncs everywhere, and a person can open both and decide.

Why not merge them? The two edits in the story touch different blocks, so it is tempting to combine them. A file sync service cannot, because blocks are cut by content and not by meaning. Two changed blocks in a spreadsheet's compressed XML can each be valid and the mixture can be corrupt. Only something that understands the format can merge: a text merge, or the collaborative editor from the previous lesson, which is why products that need real-time co-authoring build it into the editor and leave the file sync layer opaque.

The rest of the engine is a list of things that bite. Identity is not the path. Files have ids, so a rename on one device and an edit on another meet in the same file and nothing conflicts. Names collide in ways the server cannot see. Windows and macOS file systems are case-insensitive by default and keep the case you gave them, Linux file systems usually are not, so Report.txt and report.txt can be two files on one device and an impossible pair on another. Unicode normalisation, Windows's reserved names and its legacy path limit need the same treatment: a rule that renames and says so. Apply atomically. Download to a temporary file in the same folder, verify the hash, flush, and rename into place, and treat a local change made meanwhile as a conflict.

HLD

Deep dive: scaling folders, hot shares and storage

The namespace is the unit of order and of sharding. A person's root folder is a namespace. A shared folder is a namespace of its own that appears in each member's tree, so one journal serves everyone who shares it. Metadata lives in a relational store sharded by namespace id, with a directory that says which shard owns which namespace. Commits to one namespace serialise, which is correct and cheap: they are small, and nothing outside the namespace depends on their order.

The hot spot is the big shared folder. A company folder with 50,000 members turns one commit into 50,000 hints and, shortly after, 50,000 pulls for the same few entries. Three things keep that from becoming an outage. Coalesce hints, so a burst of commits sends each device one. Add jitter to the pulls, so the herd spreads over seconds. And serve the journal's tail from a cache, which is as cache-friendly as data gets: it is append-only, and every device asks for nearly the same range. Past a point, cap what a namespace can do (members, commits a second) the way the collaborative editor caps editors per document.

The notifier holds the connections. About a hundred million long-lived sockets sit behind a couple of thousand gateways, and a directory maps each device to the gateway that holds its socket. Because a hint carries no data, a notifier can drop one, send it twice, or lose a gateway without a correctness problem, which lets it be sloppy and cheap. The cost is only that a device may learn about a change a few seconds late, and the periodic poll bounds that.

The block plane is a different kind of system. A block service answers three calls, check, put and get, over an index from block name to location and an object store underneath. Packing small blocks into larger containers, indexed by container and offset, keeps the object count and request overhead down, because object stores are inefficient for tiny objects. For a very large file, upload blocks in parallel, resume from the last block the server confirms, and commit once at the end. Many small files ride in one request, as Drago and colleagues observed Dropbox's client bundling small chunks in 2012.

Durability is a property of the whole path. Acknowledge a block only after it is durable across failure domains, usually with erasure coding as in the erasure coding lesson and the object storage design. Because a block's name is a hash of its bytes, the store is self-verifying: any read can be checked against its name, and a scrubber can read and re-hash blocks all day to find bit rot long before a user does, then repair from the other fragments. Content-addressing also makes the worst failure visible, since a block that hashes to something else is simply wrong.

What dedupe buys. Content-defined chunks are the most aggressive deduplication, and not the only one. Meyer and Bolosky studied 857 desktop file systems at Microsoft and found that whole-file deduplication captured about three quarters of the savings of the most aggressive block-level scheme, for a fraction of the metadata. A product can use that: whole files for small ones, content-defined chunks for the large files where edits are small.

HLD

File sync failure modes and edge cases

What goes wrongWhat prevents or limits it
The client dies after uploading blocks and before committingBlocks first, commit second. The orphans are harmless, and the retry finds them and commits without sending data
A client commits first and dies before the blocks arriveThe server verifies every named block at commit and answers 410, so no journal entry ever names a missing block
The sweeper deletes a block a client was told the server already hasA lease on every block reported present, a grace period longer than the longest upload and retries, and a verified commit
A reply is lost and the client commits againA change id on every commit, remembered by the namespace, so the retry gets the original answer and adds nothing
A reader's cursor jumps past an entry that commits lateNumber entries at commit, under the namespace's lock, so sequence order is visibility order
A notification is lost or arrives twiceA hint carries no data and the journal is the truth. A periodic poll catches up, and a duplicate pulls nothing new
Two devices edit the same file offlineCommit against a base revision, answer a mismatch with a conflict, and keep both versions as a conflicted copy
One device deletes a file another editsThe edit survives. An edit is information that cannot be recreated, and a delete can be repeated
Names collide by case, normalisation, reserved names or lengthCompare names without case, normalise Unicode, and rename on the device that cannot hold the name
Ransomware encrypts a folder and the encrypted files syncVersion history keeps the old revisions, so a restore is a new revision that names the old blocks. Alert on a burst of rewrites
A shared folder with 50,000 members changesCoalesce hints, jitter the pulls, cache the journal's tail, cap what one namespace can do

Senior depth

What senior interviews ask about a file sync service

Interviewer follow-upL5Why split a file into blocks at all? Why not upload the whole file when it changes?How to answer

The cost of a change should follow the size of the change: a one-letter edit to a one-gigabyte file should not send a gigabyte. Cut the file into blocks, name each by a hash, and the client asks which names the server lacks and sends only those. The store keeps one copy of every block, so identical files, copies and old versions cost almost nothing. In the test, twenty-one versions of a 1 MiB file kept about 1.2 MB with content-defined chunks.

Interviewer follow-upL5What do you do about a device that was offline for a week?How to answer

Give it a cursor into a per-folder journal and let it ask for everything after the cursor, so catching up is replaying a log. If the journal has been trimmed past its cursor, the server says so, and the device takes the current cursor, lists the tree and replays from it, which is safe because applying a change twice is harmless. Its own offline edits commit against the revisions it started from, so any that collide with what happened meanwhile come back as conflicts and are kept.

Interviewer follow-upL6Inserting one byte at the front of a large file re-uploads the whole file with fixed-size blocks. How do you avoid it?How to answer

Fixed blocks are defined by position, and an insert moves every byte after it. Cut by content instead: a rolling hash over the last few bytes, cutting wherever it has a rare property such as low bits all zero, with a minimum and a maximum chunk size. The cuts then depend on the bytes and not their offsets, so the chunks after the edit come back unchanged. In the test, 100 bytes inserted near the front of a 1 MiB file sent 1,048,676 bytes in 4 KiB blocks and 10,064 bytes in content-defined chunks. The price is a pass over every byte and smaller, more numerous blocks to keep track of.

Interviewer follow-upL6Two devices edit the same file offline. What happens when they reconnect?How to answer

Every commit names the revision it was written against, and the server accepts it only if the file is still there. The second device to commit gets a conflict, saves its version as a separate conflicted copy, uploads that as a new file, and takes the server's version into the original path. No edit is lost, both versions reach every device, and a person decides. The alternative, last writer wins, converges and quietly loses work: in 5,000 random offline sessions it lost an edit in 2,061, and keeping both versions lost none.

Interviewer follow-upL6How do other devices learn about a change, and what if the notification is lost?How to answer

The metadata service tells a notifier that a namespace changed, and the notifier sends each connected device a small hint with no data in it. The device then pulls from its cursor. Because the journal is the truth, a lost hint costs only latency: a slow periodic poll catches up, and a duplicate hint pulls nothing new. Coalescing hints and jittering the pulls keeps a busy shared folder from stampeding the metadata service.

Interviewer follow-upL6How do you delete a block safely when many files and users share it?How to answer

Count references from revisions, and treat the count as a hint to be checked: run a mark and sweep from the metadata now and then, because counts drift. Never delete on the instant a count reaches zero. Delete only blocks that are unreferenced and untouched for longer than a grace period that exceeds the longest upload and its retries, renew a block's last-touched time whenever the server tells a client it already has it, and verify at commit that every named block exists. In the test, a sweeper that ran between "have it" and the commit deleted the block and left a file that could not be opened, unless the check pinned the block.

Interviewer follow-upL7Why can a reader's cursor silently skip a change, and how do you prevent it?How to answer

If entries are numbered when the work begins and not when they become visible, a slow commit can get number 13 and become visible after number 14. A device that pulls in between sees 14 and moves its cursor past 13, which it will never ask for. Number entries inside the commit transaction, under a per-namespace lock, so that commit order is number order. When commits are too frequent for that, let readers stop at the lowest sequence number still in flight, or read the database's own commit log. In the test, a phone saw both files when entries were numbered at commit and only one when they were numbered at the start.

Interviewer follow-upL7Deduplicating across users leaks information. How would you handle it?How to answer

The signal is that an upload was skipped because the server already has the block. Someone who guesses a file's hash can learn whether anyone stored it, and a client trusted to say it holds a hash can claim content it never had, which was shown against Dropbox in 2011. Make the client prove possession, for example with a challenge over random ranges of the file, deduplicate only within an account or a team, or turn cross-user dedupe off for private content. Convergent encryption keeps dedupe over encrypted blocks and still leaks equality.

Interviewer follow-upL7How would you sync a 50 GB file over a connection that drops every few minutes?How to answer

Upload in parallel blocks, ask the server which blocks it already holds when the connection returns, and resume from there. Blocks are idempotent, so a block sent twice is one block, and the client commits once at the end, naming the base revision and carrying a change id. On the download side, write blocks into a temporary file, track which are present, and rename into place only when every block hashes correctly.

HLD

How to present a file sync design in an interview

Start with what makes it hard: files are big and edits are small, so a change must cost in proportion to the change, and every device can edit offline, so conflicts are certain. Show the cost problem in one line, a one-letter insert that re-sends a gigabyte, then the repair: cut by content, name blocks by hash, store each once. Separate the two planes out loud, bytes in a content-addressed store and metadata in an ordered journal per folder, and name the order of writes that holds them together: blocks first, then the commit. Spend your time on the journal and cursors, the conflict rule, and the garbage collector that must never delete a block someone is about to name.

Summary

A file sync service has to make a change cost what the change weighs and never lose an edit. Cut files into blocks and name each one by a hash, so the client asks which names the server lacks and sends only those. Fixed blocks fail on an insert, because every later block shifts: 100 bytes near the front of a 1 MiB file sent 1,048,676 bytes, against 10,064 for content-defined chunks that cut where the bytes say. Store each block once, so twenty-one versions kept 1.2 MB instead of 10.6 MB, write blocks before the commit that names them, and sweep only behind a lease and a verified commit. Keep metadata in an ordered journal per folder, number entries when they become visible, let devices pull from a cursor and treat notifications as hints. Decide each path from three views and keep both versions on a conflict: last writer wins lost an edit in 2,061 of 5,000 offline sessions, and keeping both lost none. Scale by the folder, and let the block store verify itself.

Check yourself

Try answering out loud before you reveal each answer.

QuestionWhy does inserting one byte at the front of a file re-send the whole file with fixed-size blocks, and why does content-defined chunking not?Reveal answer

A fixed block is defined by its position, so an insert moves every byte after it, and every later block holds different bytes and gets a different name. Content-defined chunking cuts wherever a rolling hash of the last few bytes has a rare property, so a cut depends on the bytes and not their offset. After the edit the hash sees the same bytes and cuts in the same places, so only the chunk around the edit is new: 10,064 bytes sent, against 1,048,676 for 4 KiB blocks.

QuestionA client crashes between uploading its blocks and committing. What does the rest of the system see, and what if the order were reversed?Reveal answer

With blocks first, the server holds orphan blocks that no file names. No device sees anything, and the retry finds the blocks already there and commits without sending data. If the client committed first and then crashed, the journal would name blocks that were never uploaded, every other device would be told about the file, and none could open it. A commit is a promise that the file can be read, so the data must exist before the promise, and the server verifies it at commit.

QuestionWhy can a device's cursor skip a change, and how do you stop it?Reveal answer

If entries are numbered when work begins, a slow commit can be numbered 13 and become visible after 14. A device that pulls in between sees 14, moves its cursor there and never asks for 13. Take the number inside the commit transaction under a per-namespace lock, so visibility order is number order, or let readers stop at the lowest number still in flight.

QuestionTwo devices edit the same file offline. Why not let the last one to sync win?Reveal answer

Because it loses an edit without a trace: the first device's version is overwritten and nobody is told. In 5,000 random offline sessions, last writer wins lost an edit in 2,061 and keeping both versions lost none. Commit against a base revision, answer a mismatch with a conflict, and save the losing version as a conflicted copy that syncs like any other file, so a person can open both and decide.

Sources and further reading

  • Dropbox, Content hash (opens in a new tab): 4 MiB blocks hashed with SHA-256, then hashed together.
  • Dropbox HTTP API, list_folder/continue and list_folder/longpoll (opens in a new tab): cursors, a reset for an invalid cursor, and a long poll.
  • Sujay Jayakar, Rewriting the heart of our sync engine (opens in a new tab) (2020), and Isaac Goldberg, Testing sync at Dropbox (opens in a new tab) (2020): the Remote, Local and Synced trees, and how sync is tested.
  • Idilio Drago and others, Inside Dropbox: understanding personal cloud storage services, IMC 2012: chunking at up to 4 MB, bundling of small chunks, deduplication and delta encoding.
  • Athicha Muthitacharoen, Benjie Chen and David Mazières, A low-bandwidth network file system, SOSP 2001: content-defined chunking with Rabin fingerprints.
  • Wen Xia and others, FastCDC: a fast and efficient content-defined chunking approach for data deduplication, USENIX ATC 2016: the Gear hash, normalized chunking and cut-point skipping.
  • Andrew Tridgell and Paul Mackerras, The rsync algorithm, 1996: a rolling checksum that finds matching blocks at any offset.
  • The restic project's chunker library (opens in a new tab): content-defined chunking with a Rabin fingerprint and default chunk sizes between 512 KiB and 8 MiB.
  • Syncthing, Block Exchange Protocol v1 (opens in a new tab) and Understanding synchronization (opens in a new tab): blocks of 128 KiB to 16 MiB, and conflicts kept as .sync-conflict- files.
  • Dutch Meyer and William Bolosky, A study of practical deduplication, FAST 2011: whole-file against block-level deduplication across 857 desktop file systems.
  • Danny Harnik, Benny Pinkas and Alexandra Shulman-Peleg, Side channels in cloud services: deduplication in cloud storage, IEEE Security and Privacy, 2010; Martin Mulazzani and others, Dark clouds on the horizon: using cloud storage as attack vector and online slack space, USENIX Security 2011; Shai Halevi, Danny Harnik, Benny Pinkas and Alexandra Shulman-Peleg, Proofs of ownership in remote storage systems, CCS 2011.
  • John Douceur and others, Reclaiming space from duplicate files in a serverless distributed file system, ICDCS 2002: convergent encryption.
  • The Linux inotify(7) (opens in a new tab) manual page, Microsoft's ReadDirectoryChangesW (opens in a new tab) reference and Apple's File System Events guide: each can lose events and says how to notice.
  • The collaborative editor lesson, for merging edits that a file sync service leaves alone, and the lessons on object storage, erasure coding and logs and streams.
Lesson 36 of 44

Nice. Lock it in, then keep going.

Up next · Lesson 37Case study: design object storageA senior-level walkthrough of an S3-style object store: metadata apart from data, an atomic PUT checked over every crash and interleaving, listing over a flat key space, durability and repair, and tail latency.

Send a message

It goes straight to my inbox. I usually reply within a few days.