System Design

C10

File sync

A cloud drive: upload, download, sync across devices, and share. The hard parts are moving only the bytes that changed, telling every device what changed, and never losing an edit.

Not startedSaved in this browser only.
  1. 1Files are cut into chunks by content and stored once by hash. An edit uploads only the chunks that changed.
  2. 2Metadata lives in Postgres: the head of each path, and a journal of every change numbered per namespace with no gaps.
  3. 3A device syncs by reading the journal after its cursor. A long poll wakes it when a commit lands.
  4. 4A commit is a compare and set on the revision. When two devices edit the same file, the second keeps its edit as a conflicted copy.
C10
    A

    The prompt

    as the interviewer says it
    "Design a file-sync service like a cloud drive: upload, download, sync across devices, share."
    questionanswer assumed
    How many users?100 M daily, 2 devices each.
    Changes a day?20 saves of existing files and 2 new files of 1 MB per user.
    Edited files?Documents of about 256 KiB; small edits.
    Offline?Yes. Edits sync when the device returns.
    Sharing?Folders shared with other users as viewer or editor.
    Large folders?Up to 100 k files in one shared folder.
    Deleted files?In trash for 30 days, then purged.

    I confirm file sizes and edit rate, devices per user, how sharing works, and how long deleted files stay.

    B

    Requirements

    as numbers
    functional
    Upload, download and sync files across devices.
    Work offline; sync on reconnect.
    Share folders with roles.
    Version history, trash and restore.
    non-functionaltarget
    Edits lost0
    ConvergenceEvery device ends with the server's tree
    Change seen on another devicep95 < 5 s online
    Bytes for a small editThe changed chunks, not the file
    Durability of stored filesThe object store's, many nines

    No edit may be lost, every device must converge to the same tree, and an edit must not upload the whole file.

    C

    Estimates

    the arithmetic, on the board
    quantityarithmeticresult
    Commits100 M × (20 + 2) ÷ 86,400≈ 25,000/s; 3× peak ≈ 76,000/s
    New files100 M × 2 × 1 MB200 TB a day
    Edits, whole files100 M × 20 × 256 KiB≈ 520 TB a day
    Edits, changed chunks100 M × 20 × 6.3 KiB (lab)≈ 13 TB a day
    Upload bandwidth(200 + 13) TB × 8 ÷ 86,400≈ 20 Gbit/s; downloads about the same
    Journal rows100 B + 40 chunk hashes × 32 B = 1.4 KB × 2.2 B rows≈ 3.0 TB a day
    Open long polls100 M × 2 devices × 50% online100 M
    Idle re-polls100 M ÷ 60 s timeout≈ 1.7 M requests/s
    Metadata nodes76,000/s peak ÷ 4,228/s measured per node≈ 18 Postgres shards

    Inputs are the assumed answers in panel A. Chunk counts use the lab's 8.0 KiB average. The per-node rate is the lab's 16-namespace case on one laptop, so the shard count is an order of magnitude. Method: R2.

    About 25,000 commits a second on average. Chunking cuts edit uploads from about 520 TB to 13 TB a day.

    D

    API

    metadata calls; chunk bytes go to the store
    callbodysuccesserrors
    POST /v1/chunks/missingns, hashes200 hashes the server lacks403
    PUT <presigned chunk URL>chunk bytes200; the store checks the SHA-256400 bad hash
    POST /v1/commitns, path, base_rev, blocks, size200 seq, rev409 head rev, 403, 422 missing chunk
    GET /v1/changes?ns=&cursor=&limit=none200 changes, new cursor, more403, 410 cursor too old
    GET /v1/changes/wait?ns=&cursor=none200 changed: true or false403
    GET <chunk URL>none200 bytes, cacheable forever403, 404
    POST /v1/sharesns, user, role201403, 409
    • Commit is safe to retry: the retry gets 409, finds its own chunk list at the head, and takes that revision.
    • A chunk URL names its hash, so its bytes never change and any cache may keep them.

    A device asks which chunks are missing, uploads them, then commits a chunk list against the revision it started from.

    E

    Data model

    metadata in Postgres, bytes by hash in the store
    metadata: five tables in Postgres; bytes elsewhere1 : n1 : n1 : nhead = a rown : mnamespacesPKidnamejournal_seqrow locka drive or a shared foldermembersPK FKns_idPKuser_idroleowner, editor, vieweridx (user_id)filesPK FKns_idPKpathrevcompare and setdeletedthe head of each pathjournalPK FKns_idPKseq1, 2, 3 ...UQpathUQrevblockschunk hashesdeviceone row per changechunksPKhashSHA-256sizebytes in the object store
    on the deviceholds
    Local treeThe files the user sees
    Synced statePer path: the revision and chunk list last synced
    Chunk cacheChunks it holds, by hash; a pull downloads only the rest
    CursorPer namespace: the last journal number applied
    namespaces, members, chunks, files, journalsql
    -- One tree: a user's drive or a shared folder, with its own journal.
    CREATE TABLE namespaces (
      id          bigint PRIMARY KEY,
      name        text   NOT NULL,
      journal_seq bigint NOT NULL DEFAULT 01   -- the last journal entry
    );
    
    CREATE TABLE members (
      ns_id   bigint NOT NULL REFERENCES namespaces (id),
      user_id bigint NOT NULL,
      role    text   NOT NULL
              CHECK (role IN ('owner', 'editor', 'viewer'))2,
      PRIMARY KEY (ns_id, user_id)
    );
    CREATE INDEX members_user ON members (user_id);
    
    -- Keyed by the SHA-256 of the bytes; the bytes are in the store.
    CREATE TABLE chunks (
      hash bytea PRIMARY KEY3,
      size int   NOT NULL
    );
    
    -- The head of every path. A commit compares and sets rev here.
    CREATE TABLE files (
      ns_id   bigint NOT NULL REFERENCES namespaces (id),
      path    text   NOT NULL,
      rev     int    NOT NULL4,
      deleted bool   NOT NULL DEFAULT false,
      PRIMARY KEY (ns_id, path)
    );
    
    -- One row per change, numbered per namespace with no gaps.
    -- Older revisions stay as history until a purge removes them.
    CREATE TABLE journal (
      ns_id   bigint      NOT NULL REFERENCES namespaces (id),
      seq     bigint      NOT NULL,
      path    text        NOT NULL,
      rev     int         NOT NULL,
      deleted bool        NOT NULL,
      size    bigint      NOT NULL,
      blocks  bytea[]     NOT NULL5,    -- chunk hashes, in file order
      device  text        NOT NULL,
      at      timestamptz NOT NULL,
      PRIMARY KEY (ns_id, seq)6,
      UNIQUE (ns_id, path, rev)
    );
    1. 1The journal counter of this namespace. Its row lock orders commits.
    2. 2Every commit and every pull checks the role first.
    3. 3Content addressed: the same bytes in any file, of any user, are stored once.
    4. 4The head. A commit names the rev it started from and fails if the head moved.
    5. 5A revision is a list of chunk hashes. Rebuilding the file is a lookup per hash.
    6. 6Reading changes after a cursor is one index range, in order.

    Each namespace has a journal numbered 1, 2, 3 with no gaps, and a files table with the head revision of each path. Chunk bytes live in the object store under their hash.

    F

    The architecture

    click a step; its path lights up
    Device Awatcher, chunkerMetadata APImissing, commit, pullPostgresjournal, heads, chunksObject storechunks by hashNotificationlong pollsDevice Bcursor 3

    Step 1: Edit and chunk

    • The file watcher reports a changed path.
    • The client cuts the file into chunks by content and hashes each.
    • Unchanged regions give the same chunks as before.

    If it fails

    The device is offline: the change waits in the local tree until the next sync.

    Devices upload chunks to the store and commit metadata to Postgres. A commit wakes the other devices' long polls, and they pull the journal after their cursors.

    G

    Capabilities used

    what each tool gives you
    toolcapabilitywhat it gives this designalso used for
    PostgresUPDATE ... RETURNING under a row lockA journal number per namespace with no gaps, visible in order.Chat sequence numbers
    PostgresINSERT ... ON CONFLICT DO UPDATE WHERECompare and set on the head revision in one statement.Optimistic locking
    PostgresLISTEN and NOTIFYA notification sent only when the commit succeeds.Cache invalidation
    Postgresbytea[] with unnest and ANYWhich of 1,000 hashes are missing, in one query.Bulk existence checks
    PostgresTransactionsRole check, number, chunk check, head and journal row commit together.Everything
    Object storeImmutable objects, presigned URLsChunks keyed by hash; devices send and fetch bytes directly.Media, backups
    ClientContent-defined chunking (gear hash)Boundaries follow content, so an insert changes one chunk.Backup dedupe
    ClientSHA-256A chunk's name. Equal bytes get equal names on every device.Integrity checks
    inotify, FSEventsFile system eventsThe client checks only changed paths, not the whole tree.Build watchers

    Postgres gives me a gap-free counter under a row lock, a compare and set with ON CONFLICT, and LISTEN and NOTIFY. The store gives me cheap immutable chunks.

    H

    Deep dive: chunks and dedupe

    move only what changed
    methodstatusan insert in the middle costs
    Upload the whole fileNot approvedThe whole file, every save.
    Fixed-size blocksAppends onlyEvery block after the insert.
    Content-defined chunksApprovedThe chunk around the edit: 6.3 KiB here (2.5% of the file).
    A delta against the old file (rsync)Server reads old fileSmall, but the server must read and diff the old version.
    lab stepchunks sentbytes
    First upload of report.txt29 of 29256.0 KiB
    Insert one line in the middle1 of 296.3 KiB
    Conflicting edit from B1 of 2914.1 KiB
    B's conflicted copy0: the chunks are stored0 B
    • A second file with the same bytes uploads nothing: every hash is already stored.
    • Chunking in depth, with fixed blocks drawn beside it: B9.
    the device: pushpseudo code
    push(device):
      FOR EACH path the file watcher reported1:
        blocks = content_defined_chunks(file)2  // about 8 KiB each, SHA-256
        missing = server.missing(blocks)3       // one round trip
        upload each missing chunk              // straight to the store
        r = server.commit(path, base = synced_rev4, blocks)
        IF r is 409 and the head has these blocks:
          take the head's rev                  // a retry of this commit5
        ELSE IF r is 409 and the head is a delete:
          commit again on top of the delete    // an edit beats a delete6
        ELSE IF r is 409:
          commit as "name (conflicted copy, device)"7
          the original path takes the winner at the next pull
    1. 1A file system event names the path. The client never rescans a 100 k file tree.
    2. 2A rolling hash picks cut points from the bytes, so they move with an insert.
    3. 3One query for the whole list. Chunks from other files and users count too.
    4. 4The revision this edit started from. The server refuses it if the head moved.
    5. 5The first try's ack was lost. Equal chunk lists mean the head is this edit.
    6. 6Losing a deleted file is cheap to undo; losing an edit is not.
    7. 7Its chunks are already uploaded, so the copy costs one commit.
    Tested source Go: push
    Go: pushgo
    // Push sends every local change. For an edit it uploads only the chunks the server lacks, then
    // commits the chunk list against the revision the device started from. When another device got
    // there first, the edit is kept as a conflicted copy and the original path takes the other
    // device's version at the next pull. An edit against a delete restores the file; a delete
    // against an edit gives way.
    func (d *Device) Push(ctx context.Context) ([]Pushed, error) {
      if !d.Online {
        return nil, ErrOffline
      }
      var out []Pushed
      for _, p := range d.Dirty() {
        data, exists := d.files[p]
        base := d.synced[p].rev
        res := Pushed{Path: p}
        var conflict *ConflictError
        if !exists {
          _, rev, err := d.Server.Commit(ctx, d.User, Commit{NS: d.NS, Path: p, Base: base, Deleted: true, Device: d.Name})
          switch {
          case errors.As(err, &conflict): // edited elsewhere: the edit wins, the next pull restores it
            res.Outcome = "kept"
          case err != nil:
            return out, err
          default:
            res.Outcome, res.Rev = "deleted", rev
            delete(d.synced, p)
          }
          out = d.emit(out, res)
          continue
        }
        blocks, err := d.upload(ctx, data, &res)
        if err != nil {
          return out, err
        }
        c := Commit{NS: d.NS, Path: p, Base: base, Blocks: blocks, Size: int64(len(data)), Device: d.Name}
        _, rev, err := d.Server.Commit(ctx, d.User, c)
        if errors.As(err, &conflict) && !conflict.Deleted && slices.Equal(conflict.Blocks, blocks) {
          rev, err = conflict.Head, nil // a retry: the head is this edit already
        }
        if errors.As(err, &conflict) && conflict.Deleted {
          c.Base = conflict.Head // deleted elsewhere: commit on top of the delete
          _, rev, err = d.Server.Commit(ctx, d.User, c)
          res.Outcome = "restored"
        }
        if errors.As(err, &conflict) {
          res.Outcome = "conflict"
          out = d.emit(out, res)
          cp, err := d.keepCopy(ctx, c)
          if err != nil {
            return out, err
          }
          out = d.emit(out, cp)
          continue
        }
        if err != nil {
          return out, err
        }
        if res.Outcome == "" {
          res.Outcome = "committed"
        }
        res.Rev = rev
        d.synced[p] = synced{rev: rev, blocks: blocks}
        out = d.emit(out, res)
      }
      return out, nil
    }
    

    I cut files by content into chunks of about 8 KiB and name each by its SHA-256. A one-line edit of a 256 KiB file sent 6.3 KiB in the lab.

    I

    Deep dive: the journal and the cursor

    the sync protocol
    number changes bystatuswhy
    Modification timeNot approvedDevice clocks differ; two changes in one second tie.
    A sequence (bigserial)Not approvedRows appear in commit order, not number order. The lab shows a cursor passing a row for good.
    A counter per namespace under its row lockApprovedCommits in one namespace become visible in number order.
    A log partition per namespace groupAt large scaleOffsets are gap-free per partition (B6).
    wake the device bystatuswhy
    Poll every N secondsFew devicesDelay up to N; most polls find nothing.
    Long poll, woken by NOTIFYApprovedWoke 0.3 ms after the commit in the lab (median of 20, loopback).
    WebSocket from a notification tierApprovedOne socket, server push; the tier fans out (C6).
    Mobile pushBackground appsWakes a sleeping phone; it then pulls.
    • Commits in one namespace wait on its row lock: 1,313 pushes a second with 16 writers on one namespace, 4,228 across 16.
    • A namespace is one user's drive or one shared folder, so one namespace rarely sees many writers.
    the server: commitpseudo code
    commit(user, ns, path, base, blocks):
      BEGIN
        require role owner or editor
        seq = namespaces.journal_seq + 1       // row lock until COMMIT1
        require every block in chunks2
        UPDATE files SET rev = rev + 1
          WHERE path AND rev = base            // compare and set3
        IF no row: ROLLBACK; 409 with the head4
        INSERT journal (seq, path, rev, blocks)
        NOTIFY journal_{ns}, seq               // sent at COMMIT5
      COMMIT
    1. 1The next commit in this namespace waits here, so rows become visible in seq order.
    2. 2A revision never names bytes the store lacks.
    3. 3One statement: insert a new path at rev 1, or move rev only from base.
    4. 4The rollback releases the counter update, so the journal keeps no gap.
    5. 5Postgres delivers a NOTIFY only if the transaction commits.
    Tested source Go: commit · SQL: next number · SQL: compare and set
    Go: commitgo
    // Commit appends one change to the namespace journal. In one transaction it checks the role,
    // takes the next journal number under the namespace row lock, checks that every chunk is
    // stored, and moves the head only if it is still at the device's base revision. Listeners hear
    // about it when the transaction commits.
    func (s *Server) Commit(ctx context.Context, user int64, c Commit) (seq int64, rev int, err error) {
      err = pgx.BeginFunc(ctx, s.DB, func(tx pgx.Tx) error {
        if err := s.role(ctx, tx, c.NS, user, true); err != nil {
          return err
        }
        if err := tx.QueryRow(ctx, stmts["next_seq"], c.NS).Scan(&seq); err != nil {
          return fmt.Errorf("next seq of namespace %d: %w", c.NS, err)
        }
        distinct := map[Hash]bool{}
        for _, h := range c.Blocks {
          distinct[h] = true
        }
        var known int
        if err := tx.QueryRow(ctx, stmts["known"], raw(c.Blocks)).Scan(&known); err != nil {
          return fmt.Errorf("check chunks: %w", err)
        }
        if known != len(distinct) {
          return fmt.Errorf("%s: %d of %d chunks: %w", c.Path, known, len(distinct), ErrMissingChunks)
        }
        err := tx.QueryRow(ctx, stmts["set_head"], c.NS, c.Path, c.Base, c.Deleted).Scan(&rev)
        if errors.Is(err, pgx.ErrNoRows) { // the head moved: roll back, which also returns the seq
          conflict := &ConflictError{Path: c.Path}
          var blocks [][]byte
          if err := tx.QueryRow(ctx, stmts["head"], c.NS, c.Path).Scan(&conflict.Head, &conflict.Deleted, &blocks); err != nil {
            return fmt.Errorf("read head of %s: %w", c.Path, err)
          }
          for _, b := range blocks {
            conflict.Blocks = append(conflict.Blocks, Hash(b))
          }
          return conflict
        }
        if err != nil {
          return fmt.Errorf("set head of %s: %w", c.Path, err)
        }
        if _, err := tx.Exec(ctx, stmts["append"], c.NS, seq, c.Path, rev, c.Deleted, c.Size, raw(c.Blocks), c.Device, s.Now()); err != nil {
          return fmt.Errorf("append %s: %w", c.Path, err)
        }
        if _, err := tx.Exec(ctx, stmts["notify"], c.NS, seq); err != nil {
          return fmt.Errorf("notify namespace %d: %w", c.NS, err)
        }
        return nil
      })
      if err != nil {
        return 0, 0, err
      }
      return seq, rev, nil
    }
    
    SQL: next numbersql
    -- Holds the namespace row lock until commit, so the commits of
    -- one namespace become visible in seq order.
    UPDATE namespaces SET journal_seq = journal_seq + 1
    WHERE id = $1
    RETURNING journal_seq;
    SQL: compare and setsql
    -- Compare and set: the commit wins only if the head is still the
    -- revision the device started from. A new path starts at rev 1.
    INSERT INTO files AS f (ns_id, path, rev, deleted)
    VALUES ($1, $2, 1, $4)
    ON CONFLICT (ns_id, path) DO UPDATE SET rev = f.rev + 1, deleted = $4
    WHERE f.rev = $3
    RETURNING rev;
    the device: pull and waitpseudo code
    pull(device):
      LOOP:
        page = changes(ns, after = cursor, limit 1001)
        IF page is empty: RETURN
        FOR EACH path, only its last change in the page2:
          IF a delete: remove the local file
          ELSE: fetch chunks not in the local cache3; write
        cursor = last seq of the page4
    
    wait(ns, cursor):                          // the long poll
      LISTEN journal_{ns}5
      IF journal_seq > cursor: RETURN now
      sleep until a notification or 60 s
    1. 1Pages keep each response small. A new device with 100 k files reads 1,000 pages.
    2. 2A file edited 5 times while away is downloaded once.
    3. 3A device that already has most chunks downloads only new ones.
    4. 4Moved after the page is applied, so a crash re-reads the page; applying twice is harmless.
    5. 5Listen before reading the head, so a commit between the two still wakes the poll.
    Tested source Go: pull · Go: long poll
    Go: pullgo
    // Pull reads the journal after the cursor, one page at a time. Within a page only the last
    // change of each path matters. A device fetches only the chunks it does not hold, then moves its
    // cursor past the page.
    func (d *Device) Pull(ctx context.Context) (Pulled, error) {
      var res Pulled
      if !d.Online {
        return res, ErrOffline
      }
      for {
        page, err := d.Server.Changes(ctx, d.User, d.NS, d.Cursor, d.PageSize)
        if err != nil {
          return res, err
        }
        res.Requests++
        if len(page) == 0 {
          return res, nil
        }
        last := map[string]Change{}
        for _, c := range page {
          last[c.Path] = c
        }
        for _, c := range page {
          if last[c.Path].Seq != c.Seq || d.synced[c.Path].rev >= c.Rev {
            continue // a later change replaces it, or this device made it
          }
          if c.Deleted {
            if _, ok := d.files[c.Path]; !ok {
              delete(d.synced, c.Path)
              continue // this device deleted it already
            }
            delete(d.files, c.Path)
            delete(d.synced, c.Path)
            res.Removed = append(res.Removed, c.Path)
            continue
          }
          data := make([]byte, 0, c.Size)
          for _, h := range c.Blocks {
            b, ok := d.cache[h]
            if !ok {
              if b, err = d.Server.GetChunk(h); err != nil {
                return res, err
              }
              d.cache[h] = b
              d.Down += len(b)
              res.Bytes += len(b)
            }
            data = append(data, b...)
          }
          d.files[c.Path] = data
          d.synced[c.Path] = synced{rev: c.Rev, blocks: c.Blocks}
          res.Applied = append(res.Applied, c.Path)
        }
        d.Cursor = page[len(page)-1].Seq
      }
    }
    
    Go: long pollgo
    // Wait is the long poll: it returns true as soon as the journal has an entry after seq, or false
    // when timeout passes with none. It listens before it reads the head, so a commit that lands
    // between the two still wakes it.
    func (s *Server) Wait(ctx context.Context, ns, after int64, timeout time.Duration) (bool, error) {
      conn, err := s.DB.Acquire(ctx)
      if err != nil {
        return false, fmt.Errorf("acquire listener: %w", err)
      }
      defer conn.Release()
      channel := pgx.Identifier{"journal_" + strconv.FormatInt(ns, 10)}.Sanitize()
      if _, err := conn.Exec(ctx, "LISTEN "+channel); err != nil {
        return false, fmt.Errorf("listen: %w", err)
      }
      defer func() {
        bg := context.WithoutCancel(ctx)
        if _, err := conn.Exec(bg, "UNLISTEN "+channel); err != nil {
          log.Printf("unlisten %s: %v; closing the connection", channel, err)
          if err := conn.Conn().Close(bg); err != nil {
            log.Printf("close listener: %v", err)
          }
        }
      }()
      var head int64
      if err := conn.QueryRow(ctx, stmts["cursor"], ns).Scan(&head); err != nil {
        return false, fmt.Errorf("read journal head: %w", err)
      }
      if head > after {
        return true, nil
      }
      wctx, cancel := context.WithTimeout(ctx, timeout)
      defer cancel()
      if _, err := conn.Conn().WaitForNotification(wctx); err != nil {
        if errors.Is(wctx.Err(), context.DeadlineExceeded) && ctx.Err() == nil {
          return false, nil // nothing new: the device asks again
        }
        return false, fmt.Errorf("wait for journal %d: %w", ns, err)
      }
      return true, nil
    }
    

    Each namespace has a journal numbered without gaps under a row lock. A device keeps a cursor, reads the rows after it, and long-polls for the next one.

    J

    See it: two devices, one offline, one conflict

    recorded on Postgres
    Device Aonline · cursor 0photo.jpgchanged here · 512 KiB · b59fe80creport.txtchanged here · 256 KiB · ad51d1b0sent 0 B · received 0 BDevice Bonline · cursor 0no filessent 0 B · received 0 BPostgres: the journalseq · path · rev · byemptychunks stored: 0, 0 Blive files: 0
    step 1 of 21

    After this step

    moved
    no chunk bytes
    journal
    empty
    device A
    online; cursor 0; 2 files, some changed here
    device B
    online; cursor 0; 0 files

    Chunks are cut by content: 2 KiB minimum, 8 KiB on average, 32 KiB maximum. The one-line edit of a 256 KiB file sent 6.3 KiB.

    The lab also runs 3 devices through 150 seeded random edits, deletes and offline spells, pulling 2 journal rows a page. It checks: every device ends with the server's tree, and every edit a device pushed is in the journal.

    Two devices edit the same file. The second commit is refused, its edit becomes a conflicted copy, and both devices end with the same three files.

    K

    Deep dive: conflicts

    two devices, one file
    Device Afiles row: report.txtcompare and set on revDevice Bhas rev 2edits the first linehas rev 2, offlineappends a paragraphhead 2 → 3back onlinecommit report.txt, base rev 2ok: rev 3, seq 4commit report.txt, base rev 2409: head is rev 3commit "report (conflicted copy, B).txt"ok: rev 1pull: report.txt rev 3✓ Both edits survive: A's in report.txt, B's in the conflicted copy
    policystatuswhy
    Last writer winsNot approvedOne edit disappears without a trace.
    Keep both: a conflicted copyApprovedNothing is lost; the user merges by hand.
    Merge the bytes automaticallyStructured documentsNeeds a format with operations, such as a CRDT (X7).
    Lock a file while it is openOnline onlyAn offline device cannot take or release the lock.
    first commitsecond commitresult
    EditEditThe second becomes a conflicted copy.
    DeleteEditThe edit commits on top of the delete; the file returns.
    EditDeleteThe delete is refused; the next pull restores the file.
    DeleteDeleteThe second is refused and drops its local record.

    The lab tests both orders of edit against delete: the edit survives on every device.

    A commit names its base revision. If the head moved, I keep the losing edit as a conflicted copy instead of overwriting anything.

    L

    Sharing and large folders

    namespaces and pages
    needhow
    Share a folderMake it a namespace; add members with a role.
    See shared foldersMount each namespace in the user's tree; one cursor each.
    Viewer editsCommit refused with 403 before any number is taken.
    Stranger readsPull refused with 403.
    Revoke accessDelete the member row; the device drops that namespace.
    First sync of 100 k filesPage through the journal, or read a snapshot of the files table, then the journal after it.
    • Per-namespace journals keep a busy shared folder from slowing anyone's own drive.
    • Download links for people without an account are signed URLs with an expiry (O5).

    A shared folder is its own namespace with members and its own journal. A device keeps one cursor per namespace it can see.

    M

    Deletes, trash and garbage

    tombstones first, bytes last
    delete, restore, purge, collectpseudo code
    delete(path):
      commit a revision with deleted = true    // a tombstone in the journal1
    restore(path, rev):
      commit the chunk list of rev again       // old revisions are the trash2
    purge(ns, cutoff = now - 30 days):
      drop old revisions of paths deleted before cutoff
      keep the tombstone row itself3
    collect():
      drop chunks that no revision in any namespace lists4
      delete their bytes from the store
    1. 1Devices learn of a delete the same way they learn of an edit.
    2. 2Restore commits an old chunk list. No bytes move.
    3. 3A device that was away for months still reads the delete after its cursor.
    4. 4Dedupe shares chunks, so only a global check is safe. The lab keeps a chunk a live file still uses.
    Tested source SQL: purge trash · SQL: collect chunks
    SQL: purge trashsql
    -- Drop old revisions of files deleted before $2. The delete row
    -- stays, so a device that was away still learns the file is gone.
    DELETE FROM journal j
    USING files f, journal t
    WHERE f.ns_id = $1 AND f.deleted
      AND t.ns_id = f.ns_id AND t.path = f.path AND t.rev = f.rev
      AND t.at < $2
      AND j.ns_id = f.ns_id AND j.path = f.path AND j.rev < f.rev;
    SQL: collect chunkssql
    -- Garbage: no revision in any namespace lists the chunk. Dedupe
    -- shares chunks between files, so this is the only safe test.
    DELETE FROM chunks c
    WHERE NOT EXISTS
      (SELECT 1 FROM journal j WHERE c.hash = ANY (j.blocks))
    RETURNING hash;

    A delete is a revision. Purge drops old revisions after the trash window but keeps the tombstone, then a collector frees chunks that no revision lists.

    N

    Failure cases

    what breaks, and why nothing is lost
    eventresultwhy it is safesaved by
    Upload stops half waySome chunks stored, no commitNothing points at them yet. The retry skips the stored ones.Missing check
    Commit names a chunk not stored422A revision never names missing bytes.Chunk check
    Commit ack lost; the device retries409 with its own chunk list at the headThe device takes that revision; no copy is made.Compare and set
    Two devices edit offline409 for the secondIts edit becomes a conflicted copy.Compare and set
    Two commits race in one namespaceNumbers 7 and 8 in commit orderA reader never moves its cursor past an unseen row.Row lock
    NOTIFY lost or listener restartsThe long poll times outThe device pulls anyway; the journal is the truth.Journal
    Device crashes mid-pullCursor before the pageIt reads the page again; writing a file twice is harmless.Cursor
    Device away past the purgeOld revisions goneThe tombstone remains; a cursor older than the journal gets 410 and a full resync.Tombstone
    Chunk shared by two filesOne file is purgedCollection checks every revision before freeing a chunk.Global GC
    O

    Scale ladder

    start simple; climb only on a signal
    Each step adds one component1One Postgres2+ object store3+ notify tier4+ shards by ns5+ regionsmore load →
    Commits per second against this prompt's demand1001k10k100k1MDemand: average: 25,463 commits per secondDemand: average25,463Demand: 3× peak: 76,389 commits per secondDemand: 3× peak76,389Lab: 1 namespace, 1 writer: 850 commits per secondLab: 1 namespace, 1 writer850Lab: 1 namespace, 16: 1,313 commits per secondLab: 1 namespace, 161,313Lab: 16 namespaces: 4,228 commits per secondLab: 16 namespaces4,228commits per second, log scale
    stepaddit handlesmove up when you see
    1One Postgres for metadata and chunks, whole files in bytea.A team's files. Every save rewrites the file.Database size and backups grow with the bytes.
    2Chunks in an object store by hash, as on this sheet.About 4,200 small-file pushes a second per node in the lab; edits send changed chunks only.Open long polls exhaust the API servers.
    3A notification tier that holds long polls or sockets and LISTENs once per namespace.Millions of idle devices on a few machines.Commits pass one primary; the journal outgrows one disk.
    4Shard metadata by namespace (X2).A namespace's journal stays on one shard, so its counter stays local. About 18 shards at this prompt's peak.Users far from the region see slow syncs.
    5Regions: each namespace has a home region; chunks replicate.Local uploads and downloads everywhere.Top of the ladder.

    Demand from panel C. Lab rates: each push asks which chunks are missing, uploads one 4 KiB chunk and commits; Postgres on a shared laptop, median of 3 runs of 2 s. Read them as orders of magnitude.

    I start with one Postgres for metadata and an object store for chunks. I add a notification tier when long polls outgrow the API, and shard metadata by namespace when commits outgrow one primary.

    P

    Follow-ups

    what the interviewer asks next
    questionanswerdeeper
    How do you handle renames?Give each file a stable ID and make the path a column. A rename is then one journal row that moves no bytes.D3
    Can two people edit one document live?Not with whole-file sync. Use a document model with operations merged by a CRDT or a central sequencer.X7
    How do you keep the bytes durable and cheap?Erasure-code chunks across failure domains. Move chunks of cold files to a cheaper storage class.B9
    How do you push changes to millions of idle devices?A gateway tier holds the connections and subscribes per namespace, as chat gateways do.C6
    Why not one global journal?Every commit would wait on one counter. Per-namespace journals spread the lock and shard cleanly.X2
    How do you stop one user filling the store?Count bytes per namespace at commit and refuse past the quota; dedupe counts a chunk once per owner.O6
    Encrypt files so the server cannot read them?Encrypt chunks on the device with a per-file key. Dedupe then works only within one key.O5
    Q

    Drill

    predict, then reveal

    0 of 9 known

    1. A user inserts one line in the middle of a 256 KiB document. What is uploaded?

    2. Why not cut files into fixed 8 KiB blocks?

    3. Why number journal rows under a namespace row lock and not with a sequence?

    4. How does an idle device learn about a change within a second?

    5. Two offline devices edit the same file. What does the second one see when it syncs?

    6. Why is last writer wins wrong for files?

    7. One device deletes a file while another edits it offline. What survives?

    8. When may the server delete a chunk?

    9. A device was offline for 6 months and trash was purged. How does it learn a file is gone?

    R

    Numbers to say

    measured or derived
    demand
    About 25,000 commits a second; 20 Gbit/s up.
    chunks
    2 KiB min, 8 KiB average, 32 KiB max.
    edit, lab
    6.3 KiB sent for one line in 256 KiB (2.5%).
    pull, lab
    downloaded 20.1 KiB for a new file and a conflicted copy.
    commits, lab
    1,313/s in one namespace; 4,228/s across 16.
    wake, lab
    0.3 ms from commit to woken long poll.
    long polls
    100 M open; 1.7 M re-polls a second at 60 s.

    Postgres 16 on an 8-core laptop shared with other runs, over loopback.