Course contents

17. Real-World System Design Lesson 7 of 20

File Storage System

Design file storage and sync: chunked hashed uploads, metadata vs object storage, dedup, presigned URLs, notify-then-pull sync, conflicts and CDN downloads.

25 minAdvanced10 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • A file is a versioned list of chunk hashes (metadata); chunks are immutable blobs keyed by hash.
  • Chunked uploads resume after failures and upload only changed chunks.
  • Presigned URLs let clients move bytes directly to object storage.
  • Notifications are hints; a per-device cursor over the change log makes sync complete.
  • Conditional commits on a base version turn lost updates into visible conflicts.
  • A CDN absorbs most downloads; when its cache empties the origin sees the full load, and coalescing softens that.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A file storage and sync service stores users' files durably, keeps every device up to date, and lets users share links. Dropbox, Google Drive and OneDrive are the familiar examples. Underneath, two very different systems cooperate: a small, strongly consistent metadata system (files, folders, versions, permissions) and a huge, cheap blob system (the bytes).

Why it exists

Files are large, networks are unreliable, users have several devices, and storage costs real money at scale. Uploading whole files on every change wastes bandwidth; storing every copy wastes disk; letting two devices overwrite each other loses work. The design exists to make uploads resumable and incremental, storage deduplicated, and sync both fast and correct.

How it works

Requirements. Functional: upload, download, delete, rename and move files; versions; sync across devices; shared links. Non-functional: durability above all (no lost files), metadata consistency (no lost updates, no phantom files), sync latency of seconds, efficient use of bandwidth and storage.

Estimates (illustrative). 10 million daily users changing 10 files a day is 100 million changes a day, about 1 200 per second on average and a few thousand at peak. At 1 MB per change that is roughly 100 TB of new data a day before deduplication, so storage growth, not request rate, dominates cost. Metadata requests outnumber byte transfers because every sync check is a metadata read.

Chunking. The client splits each file into chunks (fixed 4 MiB, or content-defined chunking that finds boundaries from the data so inserting a byte does not shift every later chunk) and computes a SHA-256 hash per chunk. A file version is the ordered list of hashes.

Upload flow. The client sends the hash list; the metadata service replies with the hashes it does not have; the client uploads only those; then it commits the version. A failed chunk is retried alone. Object storage multipart uploads (S3, GCS, Azure Blob) provide the same resumability for single large objects.

Presigned URLs. For each missing chunk the API returns a URL signed for one operation on one key, valid for minutes. The client talks to object storage directly; the API never carries bytes. Downloads use presigned GET URLs or signed CDN URLs.

Deduplication. Because chunks are keyed by hash, identical content is stored once: across versions of a file, across files, and optionally across users. Reference counts (or periodic mark-and-sweep over all versions) decide when a chunk can be deleted.

Sync. Every metadata change appends to a per-user change log. Devices hold a long-lived connection (WebSocket, long polling or mobile push) to a notification service that says only "something changed". The device then asks for changes since its cursor, applies them, and fetches missing chunks. A device that was offline catches up the same way.

Conflicts. A commit carries the version it was based on. The metadata service commits only if that is still the current version (compare-and-set). Otherwise the commit is rejected and the client keeps its edit as a conflicted copy. Collaborative editors (Docs, Figma) avoid this with operational transforms or CRDTs, which a generic file service cannot apply to arbitrary binaries.

Downloads at scale. Shared links can be hot. A CDN caches popular files near users; misses go to object storage. Request coalescing at the edge (and an origin shield) keeps concurrent misses for the same object from multiplying.

When to use it

Any product where users bring their own files and expect them everywhere: sync clients, document management, backups, media libraries, collaboration tools with attachments.

When not to

  • Only a few uploads per user, no sync: object storage plus a metadata table and presigned URLs is enough; skip chunking and dedup.
  • Real-time collaborative documents: model the document as operations, not files.
  • Strictly end-to-end-encrypted storage: server-side cross-user dedup is impossible by design.

Trade-offs

Choice You gain You pay
Small chunks Better dedup, smaller retries More metadata rows and requests per file
Content-defined chunking Dedup survives inserts and shifts CPU on the client, variable chunk sizes
Global (cross-user) dedup Maximum storage savings Leaks whether a file exists; harder deletion accounting
Presigned direct uploads API not on the data path, cheap scaling Signing logic, expiry handling, harder server-side validation
Strongly consistent metadata store No lost updates, simple conflict rules Harder to scale than an eventually consistent store; partition by user or namespace

Alternatives

  • Whole-file uploads to object storage with multipart upload: simpler, fine for media libraries without sync.
  • Operation-based sync (CRDTs, OT) for structured documents.
  • Peer-to-peer LAN sync between a user's own devices to save bandwidth, with the server still as source of truth for metadata.

Failure modes

  • Lost update: last writer wins silently. Prevent with conditional commits.
  • Orphan chunks: uploaded but never committed; clean up after a grace period.
  • Premature garbage collection: deleting a chunk a pending commit is about to reference. Use grace periods and reference checks inside the commit.
  • Missed notifications: harmless if devices always pull by cursor; fatal if the notification itself carries the data.
  • Cold CDN cache or viral file: the origin suddenly sees the full download rate. Coalesce misses, add an origin shield, rate-limit per object.
  • Hot metadata partition: one huge shared folder concentrates writes on one shard.

In production

Partition metadata by user or namespace; keep the change log append-only with monotonically increasing cursors. Verify chunk hashes server-side after upload. Watch commit conflict rates, sync lag (time from commit to other devices applying it), upload retry rates by network type, CDN hit ratio and origin read rate. Encrypt chunks at rest and decide explicitly on the dedup scope. Set lifecycle rules so old versions move to colder, cheaper storage classes.

Common misconceptions

  • "Object storage is the database." It stores bytes well; listing, renaming, permissions and versions belong in a metadata store.
  • "Notifications keep devices in sync." They only shorten the delay; the cursor guarantees completeness.
  • "Dedup is free savings." It costs metadata, garbage-collection complexity and, at global scope, privacy.
  • "A CDN only makes downloads faster." It also hides most of the read load from the origin, which is exactly what you lose when the cache is cold.

Interview angle

Lead with the split: metadata service and database versus object storage, then chunking. Interviewers probe: how a resumed upload works, how dedup is keyed and scoped, how devices learn about changes and catch up after being offline, what happens when two devices edit the same file, how large downloads avoid the API (presigned URLs, CDN), and how you garbage-collect chunks. Estimating storage growth per day and noticing it dominates cost stands out.

Model assumptions

The upload, dedup, presigned-URL, sync and conflict steps are scripted illustrations: packets show who talks to whom and in which order; the engine does not model uploads, hashing, signatures or notification channels. The CDN steps are simulated and simplified, not a benchmark: viewers request 3 000 files with Zipf-distributed popularity (exponent 1.1); the edge cache is an LRU of 300 files; object storage is modelled as a database with 10 connections, about 60 ms per read (lognormal, cv 0.4) and a 200 ms wait limit for a connection, roughly 165 reads per second. Network hops take a fixed 1–40 ms. A restarted cache comes back empty. Coalescing shares one origin read among concurrent misses for the same file on the same edge. Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. Files of any size, on every device

    Users upload files from any device, see them on all their other devices within seconds, and share links. Files must never be lost; metadata (names, folders, versions) must be consistent. Illustrative estimate: 10 million daily users changing 10 files a day is about 1 200 file changes per second on average, and at 1 MB per change about 10 TB of new data a day before deduplication.

    The naive upload is one big request. Watch it: a 2 GB video goes up as a single stream and the connection drops at 80%. Everything must be sent again. On mobile networks that is not an edge case, it is normal.

    Scene: The phone sends a 2 GB file as one request to the Files API; the connection drops and the API returns an error, so the whole upload must start over. Scripted illustration.

    Key idea: Big files over unreliable networks need uploads that can resume; a single request cannot.

  2. 2. Split files into hashed chunks

    The client splits the file into fixed-size chunks (4 MiB is a common size) and computes a SHA-256 hash of each. It first sends the list of hashes to a metadata service, which records the file and answers which chunks it still needs. Then the chunks go up one by one.

    Chunk 3 fails on the way: only chunk 3 is sent again. When all chunks are stored, the client commits the file: the metadata service writes “file X, version 1 = h1 h2 h3 h4”. Bytes live in object storage keyed by hash; the file itself is just a list of hashes in the metadata database. This step is a scripted illustration.

    Scene: The phone sends four chunk hashes to the metadata service, uploads four chunks to object storage through the API, re-sends only the chunk that failed, and commits the file as a list of hashes. Scripted illustration.

    Key idea: Chunks make uploads resumable and turn a file into a list of content hashes: metadata in a database, bytes in object storage.

  3. 3. Only new chunks travel

    The user edits a few pages of the same document. Only one 4 MiB region changed, so the new chunk list is h1 h2 h5 h4. The metadata service already stores h1, h2 and h4, so it asks for h5 only: one chunk is uploaded instead of four, and version 2 is committed.

    This is deduplication by content hash. It saves bandwidth and storage across versions, and across users when two people upload the same file. Cross-user dedup has a privacy cost: if uploading is instant, the uploader learns that someone else already has that exact file. Many services therefore dedup only within one account. Scripted illustration.

    Scene: After an edit, the phone sends the new chunk list; the metadata service already has three of the four chunks and asks only for the new one, which is uploaded before version 2 is committed. Scripted illustration.

    Key idea: Same bytes, same hash, stored once. Choose the dedup scope (per user or global) deliberately: global dedup leaks whether a file exists.

  4. 4. Keep the API off the data path

    So far every byte passed through the Files API, which then had to be sized for the full upload bandwidth. Instead, the API asks the metadata service which chunks are needed and returns a presigned URL for each: a URL to object storage with a signature that allows one PUT of one key until it expires (here 15 minutes).

    The phone uploads the chunk directly to object storage, which checks the signature. Then it commits through the API as before. The API now handles only small metadata requests; object storage, built for bandwidth, carries the bytes. Downloads work the same way with presigned GET URLs. Scripted illustration.

    Scene: The API returns a presigned URL; the phone uploads the chunk directly to object storage, which acknowledges it, and then commits through the API and metadata service. Scripted illustration.

    Key idea: Presigned URLs let clients move bytes straight to and from object storage while the API keeps control of who may do what.

  5. 5. Other devices learn about the change

    The laptop keeps a long-lived connection (WebSocket or long poll) to a notification service. After the commit, the metadata service publishes “file X changed”; the notification service pushes it to the laptop. The message carries no data, only a nudge.

    The laptop then asks the API for changes since its cursor (41 → 42), gets the new chunk list h1 h2 h5 h4, sees that it already has three of them, and downloads only h5 from object storage. If the laptop was offline and missed the nudge, it asks for changes since its cursor when it reconnects: the cursor, not the notification, guarantees nothing is missed. Scripted illustration.

    Scene: The metadata service notifies the notification service, which nudges the laptop. The laptop asks the API for changes since its cursor and then downloads only the one new chunk from object storage. Scripted illustration.

    Key idea: Notify, then pull: the notification is a hint; a per-device cursor over the change log is what makes sync complete.

  6. 6. Two devices edit the same version

    Both devices edited version 2 while offline. They reconnect and commit almost at once. The metadata service commits only if the client’s base version is still the current one (compare-and-set): the phone’s commit wins and becomes version 3; the laptop’s commit, still based on version 2, is rejected.

    The service cannot merge arbitrary binary files, so the laptop keeps its edit as a “conflicted copy” next to the original and the user decides. Nothing is silently overwritten. That is why metadata needs a strongly consistent store with conditional writes, while chunks, being immutable and content-addressed, never conflict. Scripted illustration.

    Scene: The phone and the laptop both commit edits based on version 2. The phone’s commit succeeds as version 3; the laptop’s is rejected because its base version is outdated, and it keeps a conflicted copy. Scripted illustration.

    Key idea: Conditional commits on a base version turn lost updates into visible conflicts. Immutable chunks never conflict; only metadata does.

  7. 7. Shared links are served from the edge

    A shared link to a popular file can be opened thousands of times. Downloads go through a CDN: the edge checks its cache and only fetches misses from object storage. Here 200 downloads per second spread over 3 000 shared files, with a few very popular ones, and the edge cache holds 300 files.

    About 70% of downloads are served from the edge; object storage sees only the misses and stays lightly loaded. Typical downloads are fast; P95 includes the slower trips to the origin. This step is simulated.

    Scene: Viewers download shared files through the CDN edge at 200 per second. About 70% are served from the edge cache; object storage handles only the misses and is lightly loaded.

    Key idea: Popular content is a small set of files: a modest edge cache absorbs most reads and shields object storage.

  8. 8. The edge cache restarts empty

    One second in, the edge cache restarts (a deploy, a crash, an eviction storm) and comes back two seconds later empty. While it is gone, every download is a miss: 200 reads per second land on object storage, which in this model can do about 165.

    Connections run out, reads wait, some time out waiting for a connection, and P95 shoots up. When the cache is back it refills gradually, so the origin stays under pressure for a while after. A cache that absorbs 70% of reads also hides 70% of the load you would otherwise have to provision for.

    Scene: The edge cache goes down for two seconds. All downloads go to object storage, which saturates; latency rises and some reads fail waiting for a connection. The cache comes back empty and refills.

    Key idea: A cache is also a load-shedding device: when it empties, the origin sees the full load at once.

  9. 9. Collapse identical misses

    Same restart, one change: the edge now coalesces requests. When several viewers miss on the same file at the same moment, the edge sends one read to object storage and gives the answer to all of them (CDNs call this request collapsing).

    Popular files are exactly the ones requested concurrently, so the origin receives noticeably fewer reads while the cache is cold, fewer of them time out, and the system recovers faster. An origin shield, a second cache layer in front of the origin shared by all edges, goes further; the video-streaming case study shows it.

    Scene: The same two-second cache outage, but the edge collapses concurrent misses for the same file into one read. Object storage receives fewer reads and fewer requests fail.

    Key idea: Request coalescing turns N concurrent misses for one object into one origin read, which is what saves the origin during a cold start.

  10. 10. The design and its trade-offs

    The finished design: clients chunk and hash files; a metadata service with a strongly consistent database stores files as versioned lists of hashes and arbitrates conflicts; object storage holds immutable chunks, reached directly with presigned URLs; a notification service nudges devices, which pull changes since their cursor; shared downloads go through a CDN with coalescing.

    Trade-offs to discuss: chunk size (small chunks dedup better but mean more metadata rows and requests; content-defined chunking survives inserts that shift every fixed boundary), dedup scope versus privacy, garbage-collecting chunks no version references any more, and end-to-end encryption, which makes server-side dedup across users impossible.

    Scene: The complete design: phone and laptop, Files API, metadata service and database, object storage, notification service, and the CDN edge with its cache serving viewers.

    Key idea: Metadata is small, hot and must be consistent; bytes are big, immutable and must be cheap. Design the two paths separately.