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.
- 1Files are cut into chunks by content and stored once by hash. An edit uploads only the chunks that changed.
- 2Metadata lives in Postgres: the head of each path, and a journal of every change numbered per namespace with no gaps.
- 3A device syncs by reading the journal after its cursor. A long poll wakes it when a commit lands.
- 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.
"Design a file-sync service like a cloud drive: upload, download, sync across devices, share."
| question | answer 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.
| functional |
|---|
| Upload, download and sync files across devices. |
| Work offline; sync on reconnect. |
| Share folders with roles. |
| Version history, trash and restore. |
| non-functional | target |
|---|---|
| Edits lost | 0 |
| Convergence | Every device ends with the server's tree |
| Change seen on another device | p95 < 5 s online |
| Bytes for a small edit | The changed chunks, not the file |
| Durability of stored files | The 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.
| quantity | arithmetic | result |
|---|---|---|
| Commits | 100 M × (20 + 2) ÷ 86,400 | ≈ 25,000/s; 3× peak ≈ 76,000/s |
| New files | 100 M × 2 × 1 MB | 200 TB a day |
| Edits, whole files | 100 M × 20 × 256 KiB | ≈ 520 TB a day |
| Edits, changed chunks | 100 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 rows | 100 B + 40 chunk hashes × 32 B = 1.4 KB × 2.2 B rows | ≈ 3.0 TB a day |
| Open long polls | 100 M × 2 devices × 50% online | 100 M |
| Idle re-polls | 100 M ÷ 60 s timeout | ≈ 1.7 M requests/s |
| Metadata nodes | 76,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.
| call | body | success | errors |
|---|---|---|---|
| POST /v1/chunks/missing | ns, hashes | 200 hashes the server lacks | 403 |
| PUT <presigned chunk URL> | chunk bytes | 200; the store checks the SHA-256 | 400 bad hash |
| POST /v1/commit | ns, path, base_rev, blocks, size | 200 seq, rev | 409 head rev, 403, 422 missing chunk |
| GET /v1/changes?ns=&cursor=&limit= | none | 200 changes, new cursor, more | 403, 410 cursor too old |
| GET /v1/changes/wait?ns=&cursor= | none | 200 changed: true or false | 403 |
| GET <chunk URL> | none | 200 bytes, cacheable forever | 403, 404 |
| POST /v1/shares | ns, user, role | 201 | 403, 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.
| on the device | holds |
|---|---|
| Local tree | The files the user sees |
| Synced state | Per path: the revision and chunk list last synced |
| Chunk cache | Chunks it holds, by hash; a pull downloads only the rest |
| Cursor | Per namespace: the last journal number applied |
-- 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)
);- 1The journal counter of this namespace. Its row lock orders commits.
- 2Every commit and every pull checks the role first.
- 3Content addressed: the same bytes in any file, of any user, are stored once.
- 4The head. A commit names the rev it started from and fails if the head moved.
- 5A revision is a list of chunk hashes. Rebuilding the file is a lookup per hash.
- 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.
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.
| tool | capability | what it gives this design | also used for |
|---|---|---|---|
| Postgres | UPDATE ... RETURNING under a row lock | A journal number per namespace with no gaps, visible in order. | Chat sequence numbers |
| Postgres | INSERT ... ON CONFLICT DO UPDATE WHERE | Compare and set on the head revision in one statement. | Optimistic locking |
| Postgres | LISTEN and NOTIFY | A notification sent only when the commit succeeds. | Cache invalidation |
| Postgres | bytea[] with unnest and ANY | Which of 1,000 hashes are missing, in one query. | Bulk existence checks |
| Postgres | Transactions | Role check, number, chunk check, head and journal row commit together. | Everything |
| Object store | Immutable objects, presigned URLs | Chunks keyed by hash; devices send and fetch bytes directly. | Media, backups |
| Client | Content-defined chunking (gear hash) | Boundaries follow content, so an insert changes one chunk. | Backup dedupe |
| Client | SHA-256 | A chunk's name. Equal bytes get equal names on every device. | Integrity checks |
| inotify, FSEvents | File system events | The 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.
| method | status | an insert in the middle costs |
|---|---|---|
| Upload the whole file | Not approved | The whole file, every save. |
| Fixed-size blocks | Appends only | Every block after the insert. |
| Content-defined chunks | Approved | The chunk around the edit: 6.3 KiB here (2.5% of the file). |
| A delta against the old file (rsync) | Server reads old file | Small, but the server must read and diff the old version. |
| lab step | chunks sent | bytes |
|---|---|---|
| First upload of report.txt | 29 of 29 | 256.0 KiB |
| Insert one line in the middle | 1 of 29 | 6.3 KiB |
| Conflicting edit from B | 1 of 29 | 14.1 KiB |
| B's conflicted copy | 0: the chunks are stored | 0 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.
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- 1A file system event names the path. The client never rescans a 100 k file tree.
- 2A rolling hash picks cut points from the bytes, so they move with an insert.
- 3One query for the whole list. Chunks from other files and users count too.
- 4The revision this edit started from. The server refuses it if the head moved.
- 5The first try's ack was lost. Equal chunk lists mean the head is this edit.
- 6Losing a deleted file is cheap to undo; losing an edit is not.
- 7Its chunks are already uploaded, so the copy costs one commit.
Tested source Go: push
// 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.
| number changes by | status | why |
|---|---|---|
| Modification time | Not approved | Device clocks differ; two changes in one second tie. |
| A sequence (bigserial) | Not approved | Rows appear in commit order, not number order. The lab shows a cursor passing a row for good. |
| A counter per namespace under its row lock | Approved | Commits in one namespace become visible in number order. |
| A log partition per namespace group | At large scale | Offsets are gap-free per partition (B6). |
| wake the device by | status | why |
|---|---|---|
| Poll every N seconds | Few devices | Delay up to N; most polls find nothing. |
| Long poll, woken by NOTIFY | Approved | Woke 0.3 ms after the commit in the lab (median of 20, loopback). |
| WebSocket from a notification tier | Approved | One socket, server push; the tier fans out (C6). |
| Mobile push | Background apps | Wakes 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.
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- 1The next commit in this namespace waits here, so rows become visible in seq order.
- 2A revision never names bytes the store lacks.
- 3One statement: insert a new path at rev 1, or move rev only from base.
- 4The rollback releases the counter update, so the journal keeps no gap.
- 5Postgres delivers a NOTIFY only if the transaction commits.
Tested source Go: commit · SQL: next number · SQL: compare and set
// 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
}
-- 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;-- 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;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- 1Pages keep each response small. A new device with 100 k files reads 1,000 pages.
- 2A file edited 5 times while away is downloaded once.
- 3A device that already has most chunks downloads only new ones.
- 4Moved after the page is applied, so a crash re-reads the page; applying twice is harmless.
- 5Listen before reading the head, so a commit between the two still wakes the poll.
Tested source Go: pull · Go: long poll
// 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
}
}
// 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.
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.
| policy | status | why |
|---|---|---|
| Last writer wins | Not approved | One edit disappears without a trace. |
| Keep both: a conflicted copy | Approved | Nothing is lost; the user merges by hand. |
| Merge the bytes automatically | Structured documents | Needs a format with operations, such as a CRDT (X7). |
| Lock a file while it is open | Online only | An offline device cannot take or release the lock. |
| first commit | second commit | result |
|---|---|---|
| Edit | Edit | The second becomes a conflicted copy. |
| Delete | Edit | The edit commits on top of the delete; the file returns. |
| Edit | Delete | The delete is refused; the next pull restores the file. |
| Delete | Delete | The 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.
| need | how |
|---|---|
| Share a folder | Make it a namespace; add members with a role. |
| See shared folders | Mount each namespace in the user's tree; one cursor each. |
| Viewer edits | Commit refused with 403 before any number is taken. |
| Stranger reads | Pull refused with 403. |
| Revoke access | Delete the member row; the device drops that namespace. |
| First sync of 100 k files | Page 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.
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- 1Devices learn of a delete the same way they learn of an edit.
- 2Restore commits an old chunk list. No bytes move.
- 3A device that was away for months still reads the delete after its cursor.
- 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
-- 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;-- 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.
| event | result | why it is safe | saved by |
|---|---|---|---|
| Upload stops half way | Some chunks stored, no commit | Nothing points at them yet. The retry skips the stored ones. | Missing check |
| Commit names a chunk not stored | 422 | A revision never names missing bytes. | Chunk check |
| Commit ack lost; the device retries | 409 with its own chunk list at the head | The device takes that revision; no copy is made. | Compare and set |
| Two devices edit offline | 409 for the second | Its edit becomes a conflicted copy. | Compare and set |
| Two commits race in one namespace | Numbers 7 and 8 in commit order | A reader never moves its cursor past an unseen row. | Row lock |
| NOTIFY lost or listener restarts | The long poll times out | The device pulls anyway; the journal is the truth. | Journal |
| Device crashes mid-pull | Cursor before the page | It reads the page again; writing a file twice is harmless. | Cursor |
| Device away past the purge | Old revisions gone | The tombstone remains; a cursor older than the journal gets 410 and a full resync. | Tombstone |
| Chunk shared by two files | One file is purged | Collection checks every revision before freeing a chunk. | Global GC |
| step | add | it handles | move up when you see |
|---|---|---|---|
| 1 | One 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. |
| 2 | Chunks 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. |
| 3 | A 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. |
| 4 | Shard 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. |
| 5 | Regions: 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.
| question | answer | deeper |
|---|---|---|
| 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 |
0 of 9 known
A user inserts one line in the middle of a 256 KiB document. What is uploaded?
Why not cut files into fixed 8 KiB blocks?
Why number journal rows under a namespace row lock and not with a sequence?
How does an idle device learn about a change within a second?
Two offline devices edit the same file. What does the second one see when it syncs?
Why is last writer wins wrong for files?
One device deletes a file while another edits it offline. What survives?
When may the server delete a chunk?
A device was offline for 6 months and trash was purged. How does it learn a file is gone?
- 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.