Skip to content

    System Design

    Case Study: File Storage (Drive/Dropbox-Style)

    Design a Drive-style file storage service: chunked uploads, content-hash dedup, a metadata tree, change-feed sync, conflicts, sharing and chunk cleanup.

    By Published 22 min read

    Share

    Case studyadvancedBackend System Design

    Before this: Case Studies: The Hard Problems Map and the Template, Object and Blob Storage

    What you'll learn: By the end of this lesson you will be able to (1) split a file service into a small metadata tier and a large block store, (2) explain chunking, content hashes and deduplication with a measured example, (3) design an upload that only sends missing chunks and a sync loop built on a change feed with cursors, (4) choose a conflict policy, and (5) explain sharing inheritance, versions and the garbage-collection race that deletes chunks still in use.

    Picture a self-storage warehouse where every box is labelled by what is inside, not by who owns it. Two tenants who bring an identical box share one box. A ledger at the front desk says which tenant owns which labels, in which room, in which order. The boxes are heavy and sit on shelves; the ledger is small and is read all day.

    A file storage service has the same two halves. The bytes are cheap to keep and expensive to move. The ledger (names, folders, versions, who may see what) is tiny by comparison, yet every click touches it. This lesson works through the design in the usual case-study order. The storage mechanics (keys, multipart uploads, signed URLs) are in object and blob storage, and the upload and processing pipeline is in file upload and media pipelines; here they are building blocks.

    This is an educational reference design, not the verified internal architecture of any company. Where the lesson cites Google Drive, Microsoft OneDrive or Dropbox pages, it cites their public API documentation for one documented behaviour, and does not claim how those products work inside. The method (requirements, estimate, API, data, design, deep dives, failures, trade-offs) is the one in A repeatable approach and the case-study template.

    Verified on 2026-12-02 against the Google Drive API guides, the Microsoft Graph delta documentation, the Dropbox content hash reference, the rsync technical report, the PostgreSQL sequence documentation and the Google SRE book. The Node script on this page was run; there is no other lab.

    The core idea

    Keep the metadata small, transactional and ordered; keep the bytes immutable, content-addressed and dumb. A file is a list of chunk hashes plus a row of metadata. The chunks never change once written. Every edit makes a new list, and "the file changed" is one atomic metadata commit. Everything else follows: uploads send only chunks the server lacks, sync is "give me the commits after my cursor", and deletion is "forget this list, collect chunks nobody lists".

    Three illustrations run through the lesson: a minimal example (a 2 MiB file edited by 100 bytes, measured below), a realistic example (ShopStream store documents, in the final section) and a failure example (a sync client that silently misses a change).

    Requirements and scope

    Functional: upload and download files up to a size limit (assume several GiB), folders with move and rename, a desktop and mobile sync client that mirrors a folder, version history with restore, a trash, sharing with individuals and by link, and a "what changed" feed.

    Out of scope: real-time co-editing of documents (that is a different design; see CRDTs and conflict resolution for the idea), full-text search, previews and antivirus (the media pipeline lesson covers the pattern), billing and quotas beyond a per-user limit.

    Non-functional (assumptions):

    • Durability first. Losing a stored file is the worst outcome; the Google SRE book says storage systems often emphasise latency, availability and durability, and durability leads here.
    • Metadata calls fast: listing a folder p99 under about 200 ms.
    • Sync is eventually consistent: a change appears on other devices within seconds, not milliseconds.
    • Bandwidth is the scarce resource, so never re-send bytes the server already has.

    Back-of-envelope estimate

    All numbers are illustrative assumptions.

    Quantity Assumption Result
    Users 10 million, 2 million daily active
    Stored per user 5 GB average, 1,000 files 50 PB logical, 10 billion file records
    Metadata per file record about 500 bytes about 5 TB
    Chunks per file about 5 on average (illustrative) 50 billion chunk records, at about 64 bytes about 3.2 TB
    File changes per active user per day 10, average 5 MB 20 million changes, about 230 per second, 100 TB per day
    Ingest rate 100 TB per day about 1.2 GB per second, about 9 Gbit/s average, about 28 Gbit/s at a 3x peak
    Bytes actually new after delta and dedup assume 40% about 40 TB per day

    The takeaways: the metadata (about 8 TB with chunk records) is thousands of times smaller than the bytes (50 PB), so the two tiers scale by different rules, and the metadata fits a sharded relational store. Ingest bandwidth, not request count, is the capacity driver: 230 changes per second is trivial, while 9 Gbit/s sustained is a fleet. The 40% figure is a pure assumption; measure it on real traffic before trusting any saving.

    API design

    POST /v1/uploads                      {parentId, name, size, chunkHashes[]}  -> 200 {uploadId, missing[]: [{hash, putUrl}]}
    PUT  <putUrl>                         (chunk bytes, signed URL, one chunk)    -> 200
    POST /v1/uploads/{uploadId}/commit    {baseVersion}                           -> 201 {fileId, version} | 409 {current}
    GET  /v1/files/{fileId}/content?v=7   -> 302 to signed download URLs for each chunk (or a streamed body)
    POST /v1/files/{fileId}/move          {newParentId, newName, baseVersion}     -> 200 | 409
    GET  /v1/changes?cursor=<opaque>      -> 200 {items[], nextCursor, hasMore}
    POST /v1/files/{fileId}/permissions   {principal, role}                       -> 201

    The pivot is the first call: the client sends the chunk hashes, the server answers with only the ones it lacks. The commit is a separate call that carries the base version the edit started from, which is how a lost-update conflict is detected.

    Data model

    Metadata lives in a sharded relational store, sharded by namespace (a user's drive or a shared team folder tree) so that a folder listing, a move and the change feed for one namespace sit in one shard.

    erDiagram accTitle: Metadata model for a file storage service accDescr: A namespace owns nodes arranged as a tree by parent id. A file node has many versions. Each version lists chunks in order through a version chunk table. Chunks are stored once by content hash. Permissions attach to nodes. Changes record each commit in a namespace. NAMESPACE ||--o{ NODE : contains NODE ||--o{ NODE : parent_of NODE ||--o{ VERSION : has VERSION ||--o{ VERSION_CHUNK : lists CHUNK ||--o{ VERSION_CHUNK : referenced_by NODE ||--o{ PERMISSION : grants NAMESPACE ||--o{ CHANGE : logs NAMESPACE { string namespace_id PK bigint cursor } NODE { string node_id PK string parent_id FK string name boolean is_folder boolean deleted int head_version } VERSION { string node_id FK int version bigint size string content_hash } VERSION_CHUNK { string node_id FK int version int position string chunk_hash FK } CHUNK { string chunk_hash PK int length int refcount }

    Figure 1. Tree and versions in metadata, bytes by hash. How to read this: a folder or file is a NODE that points to its parent by id, never by path. A version is an ordered list of chunk hashes. A CHUNK row exists once per distinct hash, however many versions list it, and refcount feeds garbage collection. The namespace holds a counter that numbers its changes.

    Two choices are worth stating. Nodes point to parents by id, not by path, so renaming or moving a folder with a million descendants is one row update; the Microsoft Graph delta page gives the same advice to clients ("always track items by id") because a folder rename returns none of its descendants. And deleted is a flag, not a removed row, so the change feed can say "this node is gone" and a restore is possible.

    High-level design

    File storage high-level designSync client to API gateway (metadata calls); API gateway to Metadata service; Metadata service to Metadata shards (commit); Sync client to Block store (chunks, signed); Metadata service to Notify service (changed); Notify service to Sync client (poke); Chunk collector to Metadata shards (unreferenced?); Chunk collector to Block store (delete)Sync client: chunk, hash, uploadSync clientchunk, hash,uploadAPI gateway: auth, limitsAPI gatewayauth, limitsMetadata service: tree, commitsMetadataservicetree, commitsMetadata shards: by namespaceMetadatashardsby namespaceNotify service: long-lived channelsNotify servicelong-livedchannelsChunk collector: backgroundChunkcollectorbackgroundBlock store: chunks by hashBlock storechunks by hashmetadata callscommitchunks, signedchangedpokeunreferenced?delete

    Figure 2. Two tiers and a nudge channel. How to read this: the client talks to the metadata service for names, versions and permissions, and sends chunk bytes straight to the block store with signed URLs so the application tier carries no bulk data. After a commit the metadata service nudges other devices through a notify service; the nudge carries no data, the client then asks for changes. The collector reads metadata to decide which chunks are unreferenced and deletes them from the block store.

    The block store is an object store (object and blob storage) with the chunk's content hash as its key. The metadata service is the only writer of the tree, which makes every namespace change a single-shard transaction.

    Deep dive 1: chunks, content hashes and deduplication

    Why chunk. One edit to a 2 GiB video should not re-upload 2 GiB. If a file is a list of chunks, only the chunks that changed are new. Naming each chunk by a hash of its bytes also gives deduplication: a chunk the store already holds is never stored or sent again, even when a different user or an older version produced it.

    Fixed or content-defined boundaries. Cutting every 16 KiB is simple, but inserting one byte at the start moves every later boundary and changes every chunk. A content-defined chunker places a boundary wherever a rolling value of the last few bytes matches a pattern, so boundaries follow the content and an insert disturbs only the chunk around it. The rsync technical report solves the same problem differently: the receiver sends checksums of its fixed blocks, and the sender searches its file "at any offset, not just multiples of S", sending literal data only for the unmatched parts. A weak 32-bit rolling checksum can be moved one byte forward using only the byte leaving and the byte entering the window, so checking every offset stays cheap, and a strong checksum confirms candidate matches. rsync needs the receiver's old version to exist and costs the sender CPU; chunk hashes move the cost to a one-off hash on the client and let the server answer "do I have this?" from an index.

    A measured example. The script below builds a 2 MiB pseudo-random file (illustrative), then compares fixed 16 KiB chunks with a simple content-defined chunker (a rolling value over recent bytes, cut when its low 14 bits are zero, with 4 KiB minimum and 64 KiB maximum). It was written for this lesson and is not any product's algorithm. It counts how many chunks of the edited file the server has not seen.

    import { createHash } from "node:crypto";
    const sha256 = (b) => createHash("sha256").update(b).digest();
    const KiB = 1024;
    
    // Deterministic pseudo-random bytes (mulberry32).
    function bytes(n, seed) {
      let s = seed >>> 0;
      const out = Buffer.alloc(n);
      for (let i = 0; i < n; i++) {
        s = (s + 0x6d2b79f5) >>> 0;
        let t = Math.imul(s ^ (s >>> 15), s | 1);
        t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
        out[i] = (t ^ (t >>> 14)) & 255;
      }
      return out;
    }
    const GEAR = Array.from({ length: 256 }, (_, i) => bytes(4, 100 + i).readUInt32LE(0));
    
    function fixedChunks(buf, size) {
      const out = [];
      for (let i = 0; i < buf.length; i += size) out.push(buf.subarray(i, i + size));
      return out;
    }
    
    // Content-defined: cut where a rolling value of the recent bytes has its low bits all zero.
    function contentChunks(buf, { min, max, mask }) {
      const out = [];
      let start = 0, h = 0;
      for (let i = 0; i < buf.length; i++) {
        h = ((h << 1) + GEAR[buf[i]]) >>> 0;
        const len = i - start + 1;
        if ((len >= min && (h & mask) === 0) || len >= max) {
          out.push(buf.subarray(start, i + 1));
          start = i + 1;
          h = 0;
        }
      }
      if (start < buf.length) out.push(buf.subarray(start));
      return out;
    }
    
    function report(name, chunker, before, after) {
      const known = new Set(chunker(before).map((c) => sha256(c).toString("hex")));
      const chunks = chunker(after);
      const fresh = chunks.filter((c) => !known.has(sha256(c).toString("hex")));
      const freshBytes = fresh.reduce((n, c) => n + c.length, 0);
      console.log(`${name}: ${chunks.length} chunks, ${fresh.length} new, ${freshBytes} bytes to upload`);
    }
    
    const v1 = bytes(2 * 1024 * KiB, 42); // a 2 MiB file (illustrative)
    const inserted = Buffer.concat([bytes(100, 9), v1]); // 100 bytes added at the start
    const edited = Buffer.concat([v1.subarray(0, 1000 * KiB), bytes(100, 5), v1.subarray(1000 * KiB + 100)]); // 100 bytes overwritten mid-file
    const fixed = (b) => fixedChunks(b, 16 * KiB);
    const content = (b) => contentChunks(b, { min: 4 * KiB, max: 64 * KiB, mask: (1 << 14) - 1 });
    
    console.log("file size:", v1.length, "bytes");
    console.log("100 bytes inserted at the start");
    report("  fixed 16 KiB   ", fixed, v1, inserted);
    report("  content-defined", content, v1, inserted);
    console.log("100 bytes overwritten in the middle");
    report("  fixed 16 KiB   ", fixed, v1, edited);
    report("  content-defined", content, v1, edited);

    Output of that script, run with Node 26.13.1 on 2026-12-02:

    file size: 2097152 bytes
    100 bytes inserted at the start
      fixed 16 KiB   : 129 chunks, 129 new, 2097252 bytes to upload
      content-defined: 101 chunks, 1 new, 6957 bytes to upload
    100 bytes overwritten in the middle
      fixed 16 KiB   : 128 chunks, 1 new, 16384 bytes to upload
      content-defined: 101 chunks, 1 new, 16015 bytes to upload

    Read the result carefully. An in-place overwrite is cheap with both chunkers (one chunk). An insert at the front is the case that separates them: fixed chunking re-sends the whole file, content-defined chunking re-sends one chunk. Text editors, archive formats and databases that rewrite headers hit that case constantly. The cost of content-defined chunking is CPU on every byte, and chunk sizes that vary between the minimum and maximum.

    The whole-file hash. The Dropbox content hash reference gives a recipe: split into 4 MB blocks, SHA-256 each block, concatenate the binary hashes and SHA-256 that. The page states its purpose as letting API apps verify uploaded contents or compare remote files to local files without downloading them. Store such a hash on every version: a cheap "is this the same file?" check and an end-to-end integrity check after upload and download.

    A chunk-size trade-off. Small chunks dedupe better and make retries cheaper but multiply index entries and requests. Large chunks do the opposite. Pick the average from the measured change pattern of real files and the index budget (the estimate above assumed about five chunks per average file, an illustrative figure).

    NOTE

    If the server answers "I already have chunk X", a client learns that someone stored it. Dedup across accounts can therefore leak that fact, and per-account encryption keys defeat cross-account dedup entirely (encryption at rest and in transit). Many designs dedupe within an account or organisation only. This is a design reasoning point, not a claim about any product.

    Deep dive 2: uploads that send only what is missing

    sequenceDiagram accTitle: Upload with deduplication and atomic commit accDescr: The client chunks the file and hashes each chunk, then sends the hash list to the metadata service. The service replies with the hashes it lacks and signed URLs. The client uploads only those chunks to the block store. It then calls commit with the base version. The service checks the chunks exist, writes the new version and a change entry in one transaction and returns the new version. participant C as Client participant M as Metadata service participant B as Block store C->>C: chunk file, hash each chunk C->>M: start upload with chunk hashes M-->>C: missing hashes with signed URLs C->>B: PUT each missing chunk C->>M: commit with base version M->>B: confirm every chunk exists M->>M: write version and change entry in one transaction M-->>C: new version, or 409 on a stale base

    Figure 3. Chunks first, pointer last. How to read this: nothing is visible to other users until the commit. A crash before the commit leaves orphan chunks (collected later) and no half-written file. The commit is the single moment the file changes.

    Because chunks are immutable and named by their hash, an upload is naturally idempotent and resumable: repeating a chunk upload overwrites the same bytes with the same bytes, and resuming after a failure is "ask which hashes are still missing and send those" (idempotency keys and safe retries). Many real APIs expose a session-based variant instead. The Google Drive upload guide describes resumable uploads for files over 5 MB or flaky networks: chunks in multiples of 256 KB except the last, a session URI that expires after one week, a status query using an empty PUT with Content-Range: */total that returns 308 and a Range header showing what the server has, and a restart with a new session URI after any 4xx error. The session URI is a credential: treat it like the signed URLs in the object storage lesson.

    The commit step verifies that every listed chunk exists before it writes. Without that check a malicious or buggy client could commit a file that lists chunks never uploaded, or chunks belonging to someone else it merely guessed the hash of. Authorisation for "may this account reference this chunk" is the second reason the chunk question should be answered per account.

    Deep dive 3: sync with a change feed

    A sync client must answer one question cheaply: "what changed since I last looked?" The robust answer is a per-namespace change log with a cursor. Every commit (create, edit, move, delete, permission change) appends an entry numbered by a counter. The client stores the last cursor it fully processed and asks for entries after it.

    flowchart TD accTitle: Client sync loop with cursor and resync accDescr: The client waits for a poke or a timer, then requests changes after its cursor. If the service says the cursor is too old it starts a full resync and compares with local state. Otherwise it applies each change by node id, saves the new cursor only after applying the page, and repeats while more pages remain. A["Wait for poke or timer"] --> B["GET changes after cursor"] B --> C{"Cursor still valid?"} C -->|no, 410| R["Full resync, then reconcile with local state"] C -->|yes| D["Apply each change by node id"] D --> E["Save new cursor after the page is applied"] E --> F{"More pages?"} F -->|yes| B F -->|no| A R --> E

    Figure 4. Apply first, then advance the cursor. How to read this: the cursor is saved only after the page is applied, so a crash replays a page instead of skipping it. Applying a change by node id must therefore be idempotent.

    The public APIs show the same shape, which is why it is a safe design. Google Drive returns a start token for the account's current position, lists changes with the oldest first, follows a nextPageToken until it is absent and then stores the newStartPageToken for next time. The Microsoft Graph delta call begins with no token, follows @odata.nextLink pages until it receives an @odata.deltaLink, and uses that link next time. Points from the Graph page that carry over to any design:

    • The feed shows the latest state of each item, not every change. A twice-renamed file appears once, with its last name, and the same item may appear more than once, so use the last occurrence.
    • Deletions are explicit (a deleted facet), and the page warns to delete a folder locally only when it is empty after all changes are applied.
    • Track by id, because renaming a folder returns none of its descendants.
    • Enumerate with the feed, not by paging folders. The page says paging through children is not guaranteed to return every item if writes happen during the enumeration, and that using delta is the only way to guarantee you have read everything.
    • Tokens expire. When a token cannot be served the service returns 410 Gone with a location to start a fresh enumeration, and the client reconciles: replace local items with the server's version if it was in sync, or upload local changes the server lacks, keeping both copies when unsure.

    Telling clients to look. Polling every few seconds from millions of devices is wasteful, and pushing the data itself is fragile. The Drive push guide says its notifications "don't contain resource metadata, content, or directory paths": the client is only told something changed and then calls the changes API. Channels expire and the guide says there is no automatic renewal, so a replacement channel must be created before the old one lapses. A client should therefore also poll on a slow timer, so a lost or expired notification delays sync instead of stopping it (WebSockets, SSE and long polling covers the transports).

    Assigning the cursor. The counter must follow commit order, or a reader can advance past an entry that has not committed yet and never see it. The failure example below shows how a plain database sequence causes this. A reliable approach is a counter on the namespace row, incremented in the same transaction as the change: transactions on one namespace queue on that row lock, so numbers follow commit order. Per-namespace writes serialise; across namespaces they run in parallel. Change data capture is the alternative when the change log is derived from the database log instead.

    Deep dive 4: conflicts and moves

    Lost updates. Two devices edit the same file offline. Both commits carry the same base version. The first commit wins; the second gets 409 because its base is stale. The server must choose what happens next:

    flowchart TD accTitle: Choosing a conflict policy accDescr: A stale commit is detected by its base version. If the file format can be merged automatically, merge and create a new version. Otherwise keep both by saving the loser as a conflicted copy next to the original, and tell the user. Last writer wins is allowed only for data that is cheap to lose. A["Commit with stale base version"] --> B{"Can the format be merged safely?"} B -->|yes| C["Merge, write a new version"] B -->|no| D{"Is losing one edit acceptable?"} D -->|yes| E["Last writer wins, keep old version in history"] D -->|no| F["Keep both: save a conflicted copy, tell the user"]

    Figure 5. Default to keeping both. How to read this: merging needs format knowledge and a structured edit model (the CRDT lesson covers it), so a general file service usually cannot. Silent last-writer-wins loses a user's work, so it is a deliberate choice for cheap-to-lose data, and the older version stays in history either way.

    Moves. A move changes one parent id, so it is cheap, but two moves can race into a cycle: one user moves folder A into B while another moves B into A. The metadata service must check, inside the transaction, that the new parent is not a descendant of the node being moved, and reject the move with a clear error. Because the tree lives in one shard per namespace, that check is a single-shard read.

    Deep dive 5: sharing, versions and collecting garbage

    Permissions inherit down the tree. The Drive sharing guide states that permissions propagate from parent folders to child items by default, that a child's inherited permission cannot be removed or reduced there, that a child may add a more permissive role, that moving an item re-evaluates it against its new parent's permissions, and that removing a user from a parent revokes only the inherited access (direct grants on the child stay). Two designs follow. Compute at read time: walk up the tree and combine grants, which is simple and always correct but costs a few reads per check, so cache the result and invalidate on any permission or move change. Materialise: copy effective permissions to every descendant, which makes checks cheap and makes a permission change on a big folder a huge write. Most services compute at read time and cache. The same page says concurrent permission changes on one item are not supported, which is the same advice as the move check: serialise per namespace. A share link is a bearer token, so give it an expiry, a role and a revoke button, as with signed URLs. Authorisation models are in RBAC, ABAC and ReBAC.

    Versions are cheap, retention is a policy. Because a version is a list of hashes, keeping history costs only the chunks that differ. Drive's revision guide shows one retention policy: the head revision is never auto-purged, other revisions of binary files are typically kept for 30 days but can be purged sooner, and a revision can be marked keep-forever (up to 200 per file) and then counts toward storage. Choose a policy in terms of the product promise and the cost, and write it down.

    Garbage collection and the dedup race. Deleting a file version should free chunks only nobody else lists. Reference counts per chunk are one approach; a periodic mark-and-sweep over the version-chunk table is another. Both share a dangerous race:

    1. Client A starts an upload; the server says "chunk X already exists, skip it".
    2. The last version that listed X is deleted; the collector sees no references and deletes X.
    3. Client A commits a version that lists X. The commit's existence check may pass just before the delete, or fail; if the check and the delete are not ordered, the file is committed with a missing chunk. That is permanent data loss.

    Defences: never delete a chunk younger than a grace period longer than any upload can last; or make "chunk exists" answers create a lease (a short-lived reference) that the collector respects; and make the commit transaction re-verify and pin chunk references. The reference count must be updated in the same transaction as the commit. The commit's existence check is the one that matters; the answer given at upload start is only a hint.

    Failure modes

    Failure Effect Mitigation
    Client crashes mid-upload Orphan chunks, no visible file Chunks are idempotent; resume by asking what is missing; collect old unreferenced chunks
    Commit with stale base Lost update if silently accepted Base version check, 409, keep-both policy
    Collector deletes a needed chunk Permanent corruption of a file Grace period, leases, re-verify in the commit, periodic integrity scan against stored hashes
    Notification lost or channel expired A device stops updating Slow timer poll, renew channels before expiry
    Cursor too old or lost Client cannot continue 410 and a full resync with reconciliation
    Change entry numbered out of commit order A client skips a change forever Counter on the namespace row, assigned in the commit transaction
    Hot shared folder One shard's namespace row is a bottleneck Split very large shared trees into several namespaces, rate-limit writers
    Block store region outage Downloads fail Replicate chunks to a second region (see multi-region lessons), serve metadata separately
    Corrupt chunk Wrong bytes served Verify the chunk hash on read and the whole-file hash after download

    Trade-offs worth stating

    Decision Option A Option B How to choose
    Chunk boundaries Fixed size Content-defined Fixed is simple; content-defined wins when inserts are common, at CPU cost
    Dedup scope Global Per account or organisation Global saves most; per account avoids the existence side channel
    Conflict policy Keep both Last writer wins or merge Keep both for general files; merge only with a known format
    Permissions Compute at read Materialise per descendant Read-time with a cache unless checks dominate
    Cursor source Namespace counter Database log (CDC) Counter is simple; CDC avoids writing the log twice
    Notify Poke plus poll Push the data Poke plus poll: small, and a lost poke only delays
    Retention Short, with keep-forever Long by default Set by product promise and storage cost

    Build it

    There is no lab. The measured part is the Node script above; every service behaviour comes from the cited documentation. A good first build is the metadata schema with the commit transaction (base version, cursor increment, change entry) and a test that runs two concurrent commits and a reader.

    In practice: ShopStream store documents

    This is a realistic scenario, not a case history.

    The situation

    ShopStream has 5,000 stores (the shared figure, illustrative). Stores exchange invoices, price lists and onboarding forms with ShopStream operations by email. Attachments get lost, and nobody can tell which price list is current. A product owner asks for a shared "store documents" folder, with a small desktop client so back-office PCs keep a local copy. Documents are PDFs and spreadsheets, mostly a few MB.

    Starting architecture

    Starting architecture: email attachmentsStore staff to Shared mailbox (send file); Shared mailbox to Operations staff (manual save)Store staffStore staffShared mailbox: attachmentsShared mailboxattachmentsOperations staffOperationsstaffsend filemanual save

    Figure 6. Email as the file system. How to read this: the mailbox holds every version as a separate message, so "which is current" is a human question and access is all or nothing.

    Options considered

    Option Gain Cost Wrong when
    A. Buy a hosted drive No build Per-seat cost; stores need ShopStream tenant isolation and audit A vendor already fits the contract
    B. Object storage by whole-file version, metadata in PostgreSQL, change feed, no chunking or dedup Small, fits the data, reuses multi-tenancy and the upload pipeline Re-sends a whole file per edit Files are large and edited often
    C. Full chunked, deduplicated store with a custom sync client Least bandwidth Largest build, hard client Files are a few MB and edits are rare

    The decision

    Option B. At a few MB per file, chunk-level delta saves little and the index and client complexity are real costs, so the first version stores each version as one immutable object under a server-chosen key, keeps the tree, versions and permissions in PostgreSQL with parent ids, and numbers changes with a counter on the store's namespace row updated in the commit transaction. Conflicts keep both copies. The schema keeps a content_hash per version, so chunking could be added later without changing the API. The trigger to revisit: files over a few tens of MB, or upload bandwidth becoming a visible cost.

    Rollout and verification

    Pilot with ten stores. Verify with tests that a crash mid-upload leaves no visible file, that two concurrent commits produce one 409, that a folder move into its own child is rejected, that a client with an old cursor gets 410 and reconciles, and that a reader running during many concurrent writers never misses an entry. Watch commit latency, 409 rate, notification-to-applied delay and the number of full resyncs.

    The 2 a.m. failure

    Support reports that one store's office PC "never got" a price list its colleague uploaded; a manual resync fixes it. The first release had numbered changes with a database sequence instead of the namespace counter. A sequence value is taken when the statement runs, not at commit, and the PostgreSQL documentation notes that sequences have gaps and cannot be used to obtain gapless values. So two concurrent uploads can take numbers 41 and 42, 42 can commit first, a client can read up to 42 and save that cursor, and then 41 commits behind it and is never returned.

    sequenceDiagram accTitle: A change skipped because the cursor followed number order, not commit order accDescr: Transaction A takes sequence number 41 but is slow to commit. Transaction B takes number 42 and commits first. A reader then asks for changes after 40, sees only 42 and stores 42 as its cursor. Transaction A commits entry 41 later. The next request after 42 never returns 41. participant A as Transaction A participant B as Transaction B participant DB as Change log participant R as Reader A->>DB: take number 41 B->>DB: take number 42 B->>DB: commit entry 42 R->>DB: changes after 40 DB-->>R: entry 42 only R->>R: save cursor 42 A->>DB: commit entry 41 R->>DB: changes after 42 DB-->>R: nothing, entry 41 is lost to this client

    First checks: compare the missing entry's number with the committing times of its neighbours, and look for the client's saved cursor being larger than the entry. Mitigation: switch to the namespace counter incremented inside the commit transaction, so numbers follow commit order, and add a daily full-resync reconcile per device as a safety net, the same recovery the Graph page prescribes for tokens it cannot serve. Follow-up: a concurrency test that fails on the old design.

    Architect's notes

    • Split bytes from metadata first; everything else is a consequence.
    • Make commit the only visibility point, and put the version, the reference counts and the change entry in one transaction.
    • Treat the cursor as a correctness feature, not an id: it must follow commit order.
    • Decide the conflict policy with the product owner before building the client.
    • Never delete bytes on a count alone. Use a grace period and an integrity scan that compares stored bytes with their hash.
    • Measure before chunking. The saving depends on file sizes and edit patterns, not on the algorithm.

    Common mistakes

    • Using paths as identity, which turns every folder rename into a mass update and breaks clients.
    • Numbering changes with a plain sequence and letting clients trust the number order.
    • Trusting "chunk exists" from upload start instead of re-verifying at commit.
    • Silent last-writer-wins on files users edit by hand.
    • Pushing data in notifications instead of a nudge plus a fetch, and no slow poll as a fallback.
    • Cross-account dedup with no thought to the existence side channel.
    • Moves with no cycle check and permission changes that race.
    • No integrity check: a hash that is never compared protects nothing.

    Key takeaways

    • A file is metadata plus an ordered list of immutable, content-addressed chunks; the metadata tier is thousands of times smaller than the byte tier.
    • Upload by hash list, send only missing chunks, commit with a base version; the commit is the single visibility point.
    • Content-defined chunking survives inserts; fixed chunking does not (129 new chunks versus 1 in the measured example).
    • Sync is a per-namespace change feed with cursors, a poke plus a slow poll, idempotent application by node id, and a full resync for an expired cursor.
    • The cursor must follow commit order; a plain sequence can skip entries.
    • Keep both copies on conflict unless the format can be merged.
    • Permissions inherit down the tree; compute at read time and cache.
    • Collect chunks with a grace period or leases, never on a reference count alone.

    Practice exercises

    Exercise 1 (30 min). Using the estimate, compute metadata size if the average file has 20 chunks instead of 5, and the daily ingest if only 20% of bytes are new.

    Exercise 2 (2 hours). Write the SQL for the commit transaction: check the base version, insert the version and its chunk rows, bump refcounts, increment the namespace counter and insert the change entry. Explain what a concurrent commit sees.

    Exercise 3 (half day). Design the collector: list the states of a chunk (new, referenced, unreferenced, deletable), the grace period and how a lease prevents the race, then write the integrity scan.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments