SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
  • Design a Chat App
  • Design a News Feed
  • Design a Notification System
  • Design a Web Crawler
  • Design Search Autocomplete
  • Design File Storage (Dropbox)
  • Design Video Streaming (YouTube/Netflix)
  • Design a Distributed Cache
  • Design a Leaderboard
  • Design a Job Scheduler
  • Design a Social Media Platform (Facebook)
System Design/Case Studies/Medium
Interview case study

Design File Storage (Dropbox)

Store and sync files across devices: chunks, deduplication, sync and sharing.

⏱ 36 min readMedium case studyAdvanced24 cross-questionsHas visualizer
Prompt60-sec answer45-min plan1 Clarify2 Estimate3 API + Data4 Design5 Deep dives6 Scale7 Wrap upCross-questionsVariationsScoringMistakesCheat-sheet

StartThe prompt and what is really being tested

The interviewer says

β€œDesign Dropbox. Or Google Drive. Something that keeps my files in sync across my devices.”

It is short on purpose. Your first job is to make it specific.

What they checkWhy it matters
Seeing that files are not rowsA file can be 10 GB and edited by small amounts. A strong candidate splits the file into chunks and treats metadata and bytes as two separate systems.
Bandwidth and storage thinkingThe numbers show bytes, not requests, are the load. The interviewer wants to see you keep file bytes off the API servers and save bytes with dedup and delta sync.
A sync protocol, not just an upload APIMany devices change the same files. You need a change journal, a cursor, and a notification, so each device pulls only what it missed.
Conflict and consistency judgementTwo devices edit offline. Never losing a user's work is the product promise, and you should say how you detect and keep both versions.
Storage lifecycle and deletionChunks are shared by many files and versions. Deleting one safely, without racing a new upload, is where careless designs lose data.

TL;DRThe whole design in 60 seconds

Cut every file into chunks of about 4 MB and name each chunk by its hash. Keep two systems: a block store that holds chunks (in object storage) and a metadata service that holds the folder tree and, for each file version, the ordered list of chunk hashes. The client uploads only the chunks the server does not already have, then commits the new version in one atomic step.

  • Upload: the client chunks the file, asks "which of these hashes are new?", uploads only those straight to the block store, then commits the chunk list with its base version.
  • Sync: every change goes into a per-namespace journal with a growing cursor. A notification service tells other devices "something changed", and they pull the changes since their cursor.
  • Dedup and delta: identical chunks are stored once (reference counted), so repeated files and small edits cost little. Content-defined chunking keeps inserts from changing every chunk.
  • Conflicts: a commit carries the version it was based on. If the file moved on, we keep both: the second becomes a conflicted copy. No silent overwrite.
  • Storage: chunks in object storage with erasure coding, metadata in a sharded relational database, old chunks removed by a garbage collector after a grace period.
  • Scale: about 2,300 commits a second but about 18 Gbps of file data, so file bytes bypass the API servers and clients talk to the block store directly.
πŸ’‘How to use this page
Read the 60-second answer first. Then work through steps 1 to 7 in order, and try each step yourself before reading the model answer. Finish with the cross-questions: say your answer out loud, then open the model one.

PlanA 45-minute plan

4
3
5
8
15
7
3
Minutes per step (total 45). A guide, not a rule: move time to the part the interviewer cares about.
StepMinutesWhat to get done
1. Clarify4File size, devices, sharing, versions, offline. Rule out real-time co-editing.
2. Estimate3Storage, upload bandwidth, commit rate, connections for notifications.
3. API and data5Upload session, chunk put, commit, changes feed. Metadata tables and the block store.
4. High-level design8Client sync engine, metadata service, block store, notification service.
5. Deep dives15Chunking and dedup, the sync protocol, conflicts, then storage lifecycle and deletion.
6. Scale and failures7Hot shared folders, upload failures, orphaned chunks, security, monitoring.
7. Wrap up3Recap, trade-offs, what you would add next.

Step 1Clarify requirementsabout 4 min

πŸ€”
Pause. Try it yourself first
You have 60 seconds. Write down the questions that change the design. Think about what a file is, who else touches it, and what happens when two devices disagree.

Questions to ask, and why

AskWhy you ask itTypical answerHow it changes the design
What is the largest file, and what is the average?It decides whether chunking and resumable upload are needed, and how much bandwidth to plan for.Up to 10 GB. Most files are small (around 1 MB).Chunk files, upload in parallel, and make uploads resumable.
Do users have several devices that must stay in sync?Sync is the hard part. One device would just be file hosting.Yes: laptop, phone and web. Changes should appear within a few seconds.Change journal, notifications, and a per-device cursor.
Can people share files and folders?Sharing adds permissions and means many users can change one file.Yes: share a file or folder with view or edit rights.A shared folder is its own namespace with an access list. Updates fan out to all members.
Do we keep version history?It controls how long old chunks must be kept, so it drives storage cost.Yes, 30 days of versions, and deleted files can be restored.Versions point to chunk lists. Garbage collection needs a retention rule.
Does the app work offline?Offline edits are what create conflicts.Yes. Edits are saved locally and synced later.Client keeps a local database. The server must detect and handle conflicts.
Is real-time co-editing of one document needed?That is a different, much harder problem (Google Docs).No. Whole-file sync only.No OT or CRDT in scope. Say it exists, and move on.
How should two conflicting edits behave?Tests whether you protect user data.Never lose work. Keep both and let the user decide.Optimistic concurrency with a base version, and conflicted copies.
How many users, and how much does each store?Gives the storage and bandwidth numbers.500M registered, 100M daily active, about 1 GB stored per user on average, 10 GB quota.Hundreds of petabytes: object storage with erasure coding, and dedup.
Any privacy or compliance needs, such as end-to-end encryption?End-to-end encryption conflicts with server-side dedup.Encrypted in transit and at rest. End-to-end encryption is out of scope.Server can see chunk hashes, so dedup works. Mention the trade-off.

Write the scope on the board

Functional (must do)
  • β€’Upload and download files up to 10 GB, and organise them in folders.
  • β€’Sync changes automatically across a user's devices.
  • β€’Share files and folders with other users, with view or edit rights.
  • β€’Keep 30 days of version history, with restore and undelete.
  • β€’Work offline and sync when back online.
Non-functional (how well)
  • β€’Durability: files are never lost (design for 11 nines per object).
  • β€’Availability: 99.99% for metadata and downloads.
  • β€’Sync latency: a change shows on other devices in under 5 seconds (p95).
  • β€’Efficient: re-upload only what changed, and store identical data once.
  • β€’Scale: 500M users, 100M daily active, hundreds of PB of data.
Out of scope (say it)
  • β€’Real-time co-editing inside a document (OT or CRDT).
  • β€’End-to-end (client-side) encryption.
  • β€’Full-text search of file contents, previews and thumbnails.
  • β€’Virus scanning and the admin or billing console (mention, do not design).
🎀
Say it out loud
β€œLet me confirm the scope. We store files up to 10 GB, sync them across a user's devices within a few seconds, support sharing with view and edit rights, keep 30 days of versions, and work offline. Conflicts must never lose work. I will leave out real-time co-editing, end-to-end encryption and search. Scale is 500M users, 100M daily active. Does that match?”

Step 2Estimate the scaleabout 3 min

πŸ€”
Pause. Try it yourself first
Which is bigger: the number of requests, or the number of bytes? Work out both, and say which one drives the design.

Assumptions (say them first)

AssumptionValue
Registered users500 million
Daily active users100 million
File changes per active user per day2 (new files or edits)
New bytes per change1 MB on average (after delta sync)
Stored per registered user1 GB on average (quota 10 GB)
Savings from dedup and compression30%
Download to upload ratio2 to 1
Open sync connections1 per active device, 2 devices per active user, half connected at once

The arithmetic, line by line

WhatMathsResult
File changes per day100M users Γ— 2200M / day
Commit rate (average)200M Γ· 86,400 sabout 2,300 / s
Commit rate (peak, 3Γ— average)2,300 Γ— 3about 7,000 / s
New data per day200M Γ— 1 MB200 TB / day
Upload bandwidth (average)200 TB Γ· 86,400 s = 2.3 GB/s Γ— 8about 18.5 Gbps
Upload bandwidth (peak)18.5 Gbps Γ— 3about 55 Gbps
Total stored, before savings500M users Γ— 1 GB500 PB
Total stored, after 30% savings500 PB Γ— 0.7350 PB
With 3 full copies, or erasure coding (1.5Γ—)350 PB Γ— 3, or Γ— 1.51,050 PB, or 525 PB
Number of chunks350 PB Γ· 2 MB average chunkabout 175 billion
Chunk index size175B Γ— 50 bytesabout 9 TB
File metadata500B files Γ— 2 KBabout 1 PB (under 0.3% of the data)
Download bandwidth (average)2 Γ— upload = 400 TB/day Γ· 86,400 Γ— 8about 37 Gbps
Sync connections100M users Γ— 2 devices Γ— 50%100M, about 1,000 servers at 100k each
What the numbers tell us about the design
  • β€’Commits are only about 2,300 a second, which is easy. The load is bytes: about 18 Gbps in and 37 Gbps out on average. So file data must never pass through the API servers.
  • β€’Metadata is tiny next to the data (about 1 PB against 350 PB) but it is hot and transactional. It needs a sharded relational store and a fast chunk index (about 9 TB).
  • β€’Erasure coding halves the raw disk bill compared with 3 copies (525 PB against 1,050 PB). Dedup and compression save another 30%.
  • β€’100 million idle-but-open connections need a separate, cheap notification service. It only says β€œchanged”, so messages are tiny.
🎀
Say it out loud
β€œI am assuming 100 million daily users making 2 changes each, so 200 million commits a day: about 2,300 a second, and 7,000 at peak. That is small. The real load is bytes: 1 MB per change is 200 TB a day, about 18 Gbps in and roughly twice that out. Total storage is about 350 PB after dedup, or about 525 PB on disk with erasure coding. So file bytes go straight to the block store, and the metadata service only handles small, transactional requests.”

Step 3Define the API and the data modelabout 5 min

πŸ€”
Pause. Try it yourself first
Sketch the upload as a few calls. What do you send first, to avoid uploading what the server already has? What makes the change visible to other devices?

Endpoints

MethodPathRequestResponseNotes
POST/v1/uploads{ path, size, chunks: [{ hash, size }] }201 { upload_id, missing: [hash], put_urls }Server answers which chunk hashes it does not have. Known chunks are skipped. Idempotent for the same upload_id.
PUT/chunks/{hash}chunk bytes (checksum header)200Goes to the block store with a short-lived pre-signed URL. Server checks the bytes hash to {hash}. Safe to retry (same bytes, same name).
POST/v1/uploads/{id}/commit{ base_version }200 { file_id, version } or 409 { conflict }Atomic. Succeeds only if every chunk exists and base_version is still current. 409 triggers a conflicted copy.
GET/v1/files/{id}/content?version=none200 { chunks: [{ hash, url }] }Returns pre-signed block URLs. The client fetches chunks in parallel and joins them. Range reads for resume.
GET/v1/changes?cursor=&ns=none200 { entries, next_cursor, has_more }The sync feed. Returns changes after the cursor for a namespace, in order. Page size is capped.
POST/v1/shares{ ns_or_file, user, role }201Adds a member with role viewer or editor. Revoking is a DELETE that also invalidates cached grants.

Data model

TableKey columnsNotes
namespacens_id, owner, type (user | shared), journal_cursorUnit of sharding and of sync. A shared folder is its own namespace.
filefile_id, ns_id, parent_id, name, is_folder, deleted, latest_versionThe tree. Move and rename change only parent_id and name.
file_versionfile_id, version, size, chunk_hashes (ordered list), author, created_atA version is a list of hashes. Old versions are kept for 30 days.
journalns_id, cursor (increasing), file_id, op, versionAppend-only change log per namespace. This is what devices read.
aclns_id, user_id, roleWho can view or edit a namespace.
device_statedevice_id, ns_id, last_cursorWhere each device is up to (also kept on the client).
Block storeKeyValue
chunkSHA-256 of the bytesThe bytes (kept in object storage)
chunk_indexhashlocation, size, reference count, created_at
What a commit and the journal look like
POST /v1/uploads/u_91/commit  { "base_version": 7 }
200 { "file_id": "f_55", "version": 8 }

journal for namespace ns_12:
  cursor 1041  op=update  file=f_55  version=8
  cursor 1042  op=create  file=f_60  version=1

device pulls:  GET /v1/changes?cursor=1040&ns=ns_12
  -> entries 1041, 1042, next_cursor=1042
πŸ“Which store, and why
Two different stores, because the data is different. Metadata is small, relational and needs transactions (a commit must update the version, the journal and permissions together), so use a sharded relational database, sharded by namespace id. File bytes are large, immutable and named by hash, so use object storage with erasure coding, in front of a chunk index (hash, reference count). Never keep file bytes in the metadata database.
🎀
Say it out loud
β€œUpload is three calls. First the client sends the chunk hashes, and the server replies with the ones it is missing. Then the client puts only those chunks, straight to the block store with pre-signed URLs. Finally it commits with its base version. The commit is atomic and adds an entry to a journal for that namespace. Other devices read the journal with a cursor. Metadata goes in a sharded relational database. Chunks, named by hash, go in object storage.”

Step 4Draw the high-level designabout 8 min

πŸ€”
Pause. Try it yourself first
Draw the client, the two backends, and how another device finds out about a change. What path do the file bytes take?
File storage and sync: high-level design
πŸ’»Clientwatcher, chunker, local DB
→↓HTTPS
βš–οΈAPI gatewayauth, rate limit
→↓small requests
Metadata side
πŸ—‚οΈMetadata servicetree, versions, commits
πŸ—„οΈMetadata DBsharded by namespace
πŸ“œJournalchanges with a cursor
Bytes (direct from the client)
🧱Block servicededup check, pre-signed URLs
πŸ“‡Chunk indexhash, location, refcount
πŸͺ£Object storageerasure coded chunks
Telling other devices
πŸ“¨Queuecommit events
πŸ””Notification servicelong poll / WebSocket
πŸ“±Other devicespull changes since cursor
Background
🧹Garbage collectorunreferenced chunks
❄️Tieringold versions to cold storage
Bytes go to the block store. Small metadata requests go to the metadata service. The notification service only says that something changed.
ComponentWhat it does
Client sync engineWatches the folder, cuts changed files into chunks, hashes them, uploads missing chunks, and keeps a local database of what it has synced.
Metadata service and databaseStores the folder tree, the versions and the ACLs. Does commits in a transaction. Sharded by namespace id.
JournalAn ordered, append-only list of changes per namespace, each with a growing cursor. The source of truth for sync.
Block serviceTells the client which chunks are missing, and hands out short-lived pre-signed URLs to the block store.
Chunk index and object storageThe index maps hash to location and reference count. Object storage holds the chunk bytes with erasure coding.
Notification serviceHolds a long-poll or WebSocket connection per device and sends a small β€œnamespace changed” hint. It does not carry data.
Garbage collectorFinds chunks that no file version needs any more, and deletes them after a grace period.
Sharing and ACL serviceChecks who may view or edit a namespace on every metadata request, and on every URL it signs.
Write path (follow one request)
  1. The client sees a file change, cuts it into chunks and computes the SHA-256 of each.
  2. It calls POST /v1/uploads with the list of hashes. The block service checks the chunk index and answers with the hashes it does not have.
  3. The client uploads only those chunks, in parallel, straight to object storage with pre-signed URLs. Each upload can be retried.
  4. Each stored chunk is checked against its hash and added to the chunk index with reference count 0 (not yet used).
  5. The client calls commit with its base_version. The metadata service checks the chunks all exist and the base is current.
  6. In one transaction it writes the new file version (the ordered hash list), raises reference counts, and appends an entry to the journal.
  7. It publishes a β€œchanged” event, and the notification service pings the other devices of that namespace.
Read path (follow one request)
  1. Another device receives the hint, or its long poll returns, and it calls GET /v1/changes with its last cursor.
  2. The metadata service reads the journal after that cursor (checking the ACL) and returns the entries and a new cursor.
  3. For each changed file, the device compares the new version with its local copy and works out which chunks it is missing.
  4. It calls GET content to receive pre-signed URLs, and downloads only the missing chunks, in parallel, from the block store (or a CDN in front).
  5. It verifies each chunk by hash, rebuilds the file locally, and updates its local database and its saved cursor.
🎀
Say it out loud
β€œHere is the picture. The client chunks and hashes files. The metadata service holds the tree, versions and a journal, sharded by namespace. File bytes never touch it: the block service answers which chunks are missing, and the client uploads straight to object storage with pre-signed URLs. A commit is one transaction that records the new version and appends to the journal. A notification service pings other devices, and they pull the journal from their cursor and download only the chunks they lack.”

Step 5Deep dive into the hard partsabout 15 min

🧠The pattern for every deep dive
Problem β†’ options β†’ pick one β†’ say why β†’ say what it costs. Interviewers score the reasoning more than the choice.
5.1

Chunking and deduplication

The problem: A 10 GB file edited by a few bytes must not be uploaded again in full. The same file owned by a million people should not be stored a million times.

OptionHow it worksGoodBad
Whole filesHash the file. Upload it if the hash is new.Simplest. Dedup of exact copies.One changed byte re-uploads the whole file. No resume. A 10 GB upload that fails starts over.
Fixed-size chunks (for example 4 MB)Cut at fixed offsets and hash each chunk.Simple and fast. Resumable. Great for appends and in-place edits.An insert near the start shifts every later chunk, so all of them hash differently and are re-uploaded.
Content-defined chunkingA rolling hash scans the bytes and cuts where the hash matches a pattern (with a minimum and maximum size).Cut points follow the content, so an insert changes only the chunk it lands in.More CPU on the client. Chunk sizes vary. More code to get right.
Delta sync (rsync style)Compare the old and new versions with rolling checksums and send only the differences.Smallest uploads, even inside a chunk.Needs the old version on both sides, and is heavy. Used only in addition to chunking.
Pick
Content-defined chunking, about 4 MB on average (min 1 MB, max 8 MB), named by SHA-256, with the dedup check done before upload

Content-defined chunks keep an edit local. The visualizer below shows it: with a 160 MB file, inserting 1 MB at the start uploads 161 MB with fixed chunks (every boundary shifts) but only 4 MB with content-defined chunks. Appending to the end is the one case where fixed chunks win (1 MB against 4 MB), which is why fixed-size is fine for logs and media.

Naming each chunk by its hash gives us dedup for free. Before uploading, the client sends the hash list and the server says which ones it has. The same chunk is stored once, with a reference count of how many file versions use it. Systems like Dropbox have described using blocks of about 4 MB named by SHA-256. See Compression and Deduplication and Checksums.

Edit to a 160 MB fileFixed 4 MB chunks uploadContent-defined chunks upload
Add 1 MB at the end1 MB4 MB
Change 1 MB in the middle (in place)4 MB5 MB
Insert 1 MB in the middle85 MB6 MB
Insert 1 MB at the start161 MB4 MB
⚠️Two honest caveats about dedup
Privacy: if the server says "upload not needed" the moment you send a hash, it tells you that somebody already has that file. Attackers use this to test whether a known file exists. Defences: dedup only inside one account or organisation, or ask the client to prove it holds the bytes. Encryption: with end-to-end encryption using a different key per user, identical files become different bytes, so cross-user dedup stops working. Convergent encryption (key derived from the content) restores it but leaks the same "does someone have this?" signal.
🎀
Say it out loud
β€œI would cut files with content-defined chunking, about 4 MB on average, and name each chunk by its SHA-256. Fixed chunks break when bytes are inserted near the start, because every later boundary shifts. With content-defined chunks only the chunk holding the edit changes. The client sends the hash list first, the server replies with the missing ones, and only those are uploaded. Identical chunks are stored once with a reference count. I would limit cross-user dedup, because β€œalready stored” leaks that someone has that file.”
5.2

The sync protocol and the atomic commit

The problem: Many devices change the same files at any time. Each device must find out what changed, in order, without missing anything and without re-reading the whole tree. And a commit must never point to chunks that are not there.

OptionHow it worksGoodBad
Poll the whole treeEach device fetches the full folder tree every few seconds and diffs it.Trivial to build.Far too heavy at 100M devices. Slow to notice changes.
Per-file timestampsAsk for files modified since a time.Simple query.Clocks differ between machines, and two changes in the same millisecond can be missed.
A change journal with a cursorEvery commit appends an entry with the next number. A device remembers its last number and asks for everything after it.Ordered, exact, cheap, easy to resume. No clocks.The journal must be ordered per namespace, and old entries need compaction.
Merkle tree of foldersEach folder has a hash of its children. Compare hashes down the tree to find what differs.Good for repairing a device that is badly out of sync.More work to keep up to date. Use it as a fallback, not the main path.
Pick
A per-namespace journal with a cursor, plus a push hint so devices do not poll

Each namespace has an append-only journal. A commit adds an entry with the next cursor number, inside the same transaction that writes the version, so the journal never disagrees with the data. A device keeps its last cursor, calls GET /changes?cursor=N, applies the entries in order, and saves the new cursor. A device that was off for a week just asks from its old cursor. A device that lost its state does a full listing and starts again.

To avoid polling, the notification service keeps a long-poll or WebSocket connection per device (see Long Polling and WebSockets). When a commit lands, a queue event wakes the right connections. The message carries no data, only "namespace 12 changed", so it is tiny, and a lost message is harmless: the device also checks every few minutes. About 7,000 pings a second on average is easy.

The commit is atomic (the order matters)
1. Upload all chunks          (they exist but nothing refers to them yet)
2. POST commit  { base_version: 7 }
   BEGIN TRANSACTION
     check every chunk hash exists in the chunk index
     check file.latest_version == 7        -- else 409 conflict
     insert file_version 8 (ordered hash list)
     increment refcount for each hash
     update file.latest_version = 8
     append journal entry (cursor 1041)
   COMMIT
3. publish "ns_12 changed"                  (after commit, at least once)
🧠Why chunks go first
If we wrote the version first and the chunks later, a reader could see a file whose chunks do not exist yet. Chunks first, commit last means a half-finished upload leaves only unreferenced chunks, which the garbage collector cleans up. It never leaves a broken file.
🎀
Say it out loud
β€œSync is a journal with a cursor. Every commit appends an entry to the namespace's journal in the same transaction that writes the new version, so they cannot disagree. A device remembers its last cursor and asks for everything after it, in order. Chunks are uploaded before the commit, so a failed upload leaves only unreferenced chunks, never a broken file. To avoid polling, a notification service holds a long-poll connection per device and sends a tiny changed hint, which is safe to lose because devices also check periodically.”
5.3

Conflicts when two devices edit offline

The problem: A laptop and a phone both change the same file while offline, both starting from version 3. When they come back, the server has two different version 4s.

OptionHow it worksGoodBad
Last writer winsAccept whichever save arrives last and overwrite.Simple. No conflicts ever shown.Silently throws away one person's work. The worst thing a storage product can do.
Reject the second saveReturn an error and make the user fetch, merge and retry.Nothing is lost.Users on a flaky connection are stuck. Bad experience for a background sync client.
Keep both (conflicted copy)Compare base_version with the current version. If different, store the second as a separate file such as β€œplan (Anna's conflicted copy).txt”.Never loses work. No merging logic. Works for any file type.The user has to merge by hand, and conflict files can pile up.
Automatic merge (OT or CRDT)Merge the two edits inside the document model.Smooth for text and shared docs.Needs to understand the file format. Only for native documents. See CRDTs and Operational Transformation.
Pick
Optimistic concurrency with a base version, and a conflicted copy for ordinary files

Every commit says "I changed version 7". If the file is still at 7, it becomes 8. If it is already at 8, someone else got there first, so the server does not overwrite: it stores this save as a conflicted copy in the same folder and tells both devices. That is exactly the "keep both" policy in the visualizer: no edit is hidden. The user sees two files and merges.

Plain files have no merge rules the server can trust, so the safe choice is to keep both. Only for files we understand (such as our own documents) would we use OT or CRDTs. Both versions also stay in the 30-day history, so even last-writer-wins would be recoverable, but users should not have to know that.

CaseWhat the server does
Edit vs edit (same base version)First commit wins. The second becomes a conflicted copy.
Edit vs deleteKeep the edited file and cancel the delete (or restore it), so the edit survives.
Two renames or moves of one fileThe first wins. The second is applied to the new location only if it still makes sense, otherwise it is dropped and reported.
Move folder A into B while B moves into AMoves are checked for loops. The second is rejected, because a folder cannot be inside itself.
Two new files with the same nameThe second is renamed (β€œreport (1).pdf”).
πŸ’‘Use ids, not paths
Identify files and folders by id, and store the tree as parent_id plus name. Then renaming or moving a folder changes one row, not thousands, and other devices do not see the whole folder as deleted and re-created.
🎀
Say it out loud
β€œEvery commit carries the base version it was built on. If the file has moved on, the server does not overwrite. It saves the second version as a conflicted copy next to the original and notifies both devices. Nothing is lost, and the user merges. I prefer that to last-writer-wins, which silently drops work. I would only use OT or CRDTs for document types we own. For folders I would key everything by id, so renames are cheap, and reject a move that would put a folder inside itself.”
5.4

Metadata scale, and keeping storage tidy

The problem: There are about 500 billion files, and chunks are shared by many versions and users. The metadata must scale, hot shared folders must not melt a shard, and deleting a chunk must never break a file or race with a new upload.

OptionHow it worksGoodBad
Shard metadata by user idAll of a user's files live on one shard.Simple. Most queries stay on one shard.A shared folder spans users, so shared data lives on several shards. Cross-shard transactions are painful.
Shard by namespace idA namespace (a user root or a shared folder) is the unit. Everything inside it lives on one shard.A commit and its journal are one local transaction. Sharing means sharing a namespace.A very busy shared folder is one hot shard. Moving a file between namespaces is a cross-shard move.
Delete chunks immediately when the count reaches zeroDecrement on delete. At zero, remove at once.Frees space fast.Races with a concurrent upload or dedup hit that is about to use the chunk. A bug here loses user data.
Grace period plus periodic mark-and-sweepAt zero, mark the chunk as a candidate. Delete only after, say, 7 days, and double-check against real references.Safe against races and counting bugs. Cheap to reason about.Disk is freed later. Needs a background job.
Pick
Shard by namespace id, and delete chunks only after a grace period, confirmed by a mark-and-sweep check

A namespace is the natural unit: a commit, its version rows, and its journal entry all sit on one shard, so the commit is a single-shard transaction. A shared folder is simply a namespace with several members. Very hot namespaces can get their own shard, and the placement table is kept in a small routing service. See Sharding and Shard Keys, Hot Shards and Resharding.

For chunks, reference counts are fast but can drift, and a dedup hit can arrive just as the count hits zero. So reaching zero only marks the chunk. It is deleted after a grace period, and only if a full mark-and-sweep (walk every live version and collect the hashes it uses) still finds no reference. A dedup hit or upload also "touches" the chunk, which resets its timer. Cost: some dead data lives a week longer. Benefit: we never delete a chunk a live file needs.

DataWhere it livesLifecycle
Current version chunksHot object storage, erasure codedKept while the file exists
Old versions (up to 30 days)Same, then colder storage after a few daysDropped after retention, if no other version uses the chunk
Deleted files (undelete window)Hidden in metadata, chunks keptPurged after 30 days
Unreferenced chunks (failed uploads)Object storage, refcount 0Deleted after the grace period
πŸ“Durability
Object storage with erasure coding across zones gives very high durability for about 1.5Γ— the data, not 3Γ—. Add checksums on every chunk and a background scrubber that reads and verifies data regularly, repairing from parity when a block is bad. See Erasure Coding and Storage Tiers (Hot, Warm, Cold).
🎀
Say it out loud
β€œI would shard metadata by namespace id, not user id, so a commit and its journal entry are one single-shard transaction, and a shared folder is just a namespace with members. For chunks, I would not delete at refcount zero, because a dedup hit can race with it. I would mark the chunk, wait a grace period such as seven days, and delete it only if a mark-and-sweep still finds no live reference. Chunks sit in object storage with erasure coding, and old versions move to colder tiers.”
VisualizerChunks and conflicts: what is uploaded, and what survivesPart 1: pick fixed or content-defined chunking and an edit, and see which chunks change and how many MB are uploaded. Add an identical second copy to see reference counts. Part 2: let two devices edit offline, and compare last-writer-wins with keeping both.
Part 1: what gets uploaded after an edit?
How is the file cut into chunks?
A colleague uploads the same original file?
What is the edit?
Before: 40 chunks, 160 MB (numbers are MB per chunk)
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
After the edit: 41 chunks, 161 MB. Amber = new, must upload. Green = already stored, skipped
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
1
Uploaded (chunked)
161 MB
41 of 41 chunks
Whole-file upload
161 MB
no chunking
Saved
0%
of the upload
Disk, old + new version
321 MB
old chunks are shared
Inserting bytes shifts everything after the insert point, so every fixed 4 MB cut after it holds different bytes and gets a new hash. 41 of 41 chunks are "new" and 161 MB is uploaded for a 1 MB edit. That is why fixed-size chunking is weak for files that get inserts. Switch to content-defined chunking to see the difference.
Part 2: two devices edit the same file offline

Both devices start from version 3: β€œQ3 plan: ship v2”. Device A adds β€œ+ budget” and device B adds β€œ+ risks”, both while offline. Then they come back online. Who saves first, and what the server does about the second save, decides what you keep.

Which device reaches the server first?
What does the server do on a conflict?
Device A (saved first)
plan.txt
version 5
β€œQ3 plan: ship v2 + risks”
Its edit vanished from the latest file.
Server (after both saves)
plan.txt
version 5
β€œQ3 plan: ship v2 + risks”
Second save carried base_version = 3, server was at 4.
Device B (saved second)
plan.txt
version 5
β€œQ3 plan: ship v2 + risks”
Its edit won. Nothing to do.
Edits silently hidden
1
in the latest file
Files on the server
1
after both saves
Person has to merge
no
(but data was lost)
Device A saved first (version 4). Device B then saved with base version 3, but the server was already at 4. Last-writer-wins simply made it version 5. Device A's edit (β€œ+ budget”) is gone from the latest file, and nobody was told. It still sits in the version history, if anyone thinks to look.

A simulated model with hard-coded chunk sizes (a 160 MB file) and no real hashing. Real clients cut chunks with a rolling hash (for example Rabin or Gear fingerprints) and name each chunk by its SHA-256. The sizes, the 1 MB edit and the file names are illustrative.

Step 6Scale, bottlenecks and failuresabout 7 min

πŸ€”
Pause. Try it yourself first
A shared folder with 100,000 members gets a change. A 10 GB upload dies at 90%. A data centre goes down. What does each look like?

What breaks first, and the fix

BottleneckFix
A hot shared namespace (a company-wide folder)Give it its own shard, batch journal writes, and send one hint per connection, not one per change. Page the changes feed.
Upload bandwidth through the API tierNever carry file bytes there. Pre-signed URLs let clients write straight to the block store, which scales as object storage does.
Chunk index lookups (175 billion chunks)Shard the index by hash prefix. Cache hot hashes. Use a Bloom filter to answer β€œdefinitely not stored” without a lookup.
Many small files (thousands of 1 KB files)Batch them into one commit and one upload request. Pack tiny files into a bundle chunk, so that overhead does not dominate.
Slow and mobile networksResumable chunk uploads, parallel streams on good links, throttling, and metered-data and battery rules on phones.
Notification fan-out for large sharesFan out in a queue-driven worker pool. Coalesce several changes in a short window into one hint.
Download hot spots (a popular shared file)Put a CDN in front of the block store for public links, with signed, expiring URLs.

What if a part fails?

FailureHow the design copes
A chunk upload fails halfwayRetry the chunk. Same bytes, same hash, so the put is idempotent. The upload session lets the client ask which chunks already arrived.
The client dies after uploading chunks but before commitNothing is visible. The chunks are unreferenced and are removed by the garbage collector. The client resumes from the session.
Commit succeeds but the response is lostThe client retries the commit with the same upload id. It is idempotent and returns the same version.
A metadata shard is downReplicas take over (leader failover). Writes to that shard's namespaces pause briefly. Clients keep working offline and sync later.
A zone or storage node is lostErasure coding rebuilds missing pieces from the others across zones. Reads keep working from the surviving pieces.
Notification service is downDevices fall back to polling the changes feed every minute or so. Sync is slower, but correct, because the journal is the truth.
What to monitor
  • β€’Sync latency: time from commit to the last device applying it (p50, p95, p99)
  • β€’Upload success rate, resume rate and bytes uploaded versus bytes in the files (the dedup ratio)
  • β€’Commit conflicts per minute, and the number of conflicted copies created
  • β€’Orphaned chunk count and garbage-collector backlog, and the chunk index hit rate
  • β€’Notification connections, drop and reconnect rate, and the fallback polling load
Security and abuse
  • β€’Authenticate every request. Check the ACL on metadata calls and again when signing each URL.
  • β€’Pre-signed URLs are short-lived (minutes), scoped to one chunk, and read-only or write-only.
  • β€’Encrypt in transit (TLS) and at rest, with keys in a key management service.
  • β€’Limit cross-user dedup so that β€œalready uploaded” does not reveal who has which file.
  • β€’Rate limit uploads and scan for malware and abuse, and keep an audit log of shares and deletes.

Step 7Wrap upabout 3 min

Files are cut into content-defined chunks named by SHA-256. The client uploads only missing chunks straight to object storage, then commits a version (an ordered list of hashes) in one transaction that also appends to a per-namespace journal. Other devices are pinged, and pull the journal from their cursor. Conflicts become conflicted copies. Metadata is sharded by namespace, and unreferenced chunks are removed after a grace period.

Trade-offs you made

DecisionWhat we gainWhat it costs
Chunking with dedupSmall edits upload small amounts. Identical data is stored once.Client CPU, more metadata, and a dedup side-channel to manage.
Content-defined over fixed chunksInserts change one chunk instead of all later ones.More complex client code and variable chunk sizes.
Journal with a cursor, plus a push hintExact, ordered, resumable sync with little polling.A journal per namespace to keep ordered and compact.
Conflicted copies instead of auto-mergeWork is never lost, and it works for any file type.The user merges by hand, and copies pile up.
Shard metadata by namespaceA commit is a single-shard transaction. Sharing is simple.Hot shared folders, and cross-namespace moves are heavier.
Grace period before deleting chunksNo deletion races, and no lost data.Storage freed a week later.
If we had more time, we would…
  • β€’Real-time co-editing for our own documents, with OT or CRDTs.
  • β€’Client-side (end-to-end) encryption, and what it does to dedup.
  • β€’Search over file names and contents, plus previews and thumbnails.
  • β€’Multi-region storage with data residency choices per customer.
  • β€’Smarter tiering: move cold, old versions to archive storage automatically.
🎀
Say it out loud
β€œTo recap: content-defined chunks named by hash, uploaded straight to object storage, and an atomic commit into a sharded metadata store that also writes a journal. Devices sync from a cursor, with a notification hint. Conflicts keep both versions. Chunks are removed only after a grace period. The main trade-offs are client complexity, a dedup privacy side-channel, and manual merges for conflicted copies. Next I would add co-editing and end-to-end encryption.”

Q&ACross-questions (24)

πŸ’‘How to practise
Cover the answer. Say yours out loud in 30 to 60 seconds. Then open the model answer, the follow-up, and the weak answer to see what to avoid. Use Open all at the top for a quick read.
Warm-upProbingCurveballWarm-up = basics. Probing = tests depth. Curveball = changes the problem.

Chunks, upload and sync

The core of the question. Be precise about why each piece exists.

Storage and metadata

What goes where, how big it gets, and how it is cleaned up.

Conflicts, consistency and failures

Where interviewers test whether you protect user data.

Curveballs and product questions

The follow-ups that change the problem. Answer calmly, and say what changes.

What ifIf the interviewer changes the problem

A change in requirements is a test of whether you understand why your design looks the way it does.

New requirementWhat changes in the design
Real-time co-editing of documentsAdd a collaboration service with WebSocket sessions and OT or a CRDT for our own document types. Periodically snapshot to a normal file version.
End-to-end encryptionChunk and encrypt on the client with per-user keys. Cross-user dedup is lost, and server-side search and previews stop working. Key recovery becomes a product problem.
Full-text search inside filesAn indexing pipeline reads new versions from the journal, extracts text, and writes an inverted index. Respect ACLs at query time.
Files up to 1 TB (video, backups)Larger chunks, many parallel streams, and chunk-level resumable sessions. The hash list is large, so store it in pages.
Strict compliance (retention and legal hold)Per-namespace retention rules that override garbage collection, write-once storage for held data, and audit logs for every access.
Mostly photos and videosAdd thumbnail and transcoding jobs, a CDN for viewing, and larger fixed chunks, since media rarely gets small in-place edits.
10Γ— more users, most inactiveTier inactive accounts to cold storage, keep metadata hot, and make cold reads slower but still correct.
A small company needs on-premises storageSame logical design with a local block store and metadata database, and replication to the cloud as a backup.

ScoreHow answers are judged

AreaWeakGoodGreat
RequirementsStarts drawing servers. Never asks about file size, devices or conflicts.Asks about file size, devices, sharing, versions and offline. Rules out co-editing.Also raises encryption and dedup, conflict policy and retention, and states the scope back.
EstimationNo numbers, or counts only requests.Computes storage, commit rate and upload bandwidth.Sees that bytes dominate, concludes that file data must bypass the API tier, and sizes the notification connections.
Core ideaStores whole files in one database.Chunks files, separates metadata from blocks, uses object storage.Explains chunk hashing, dedup, delta sync, reference counting and why each exists.
Sync and conflictsSays β€œpoll for changes” and β€œlast write wins”.Uses a change journal with a cursor and a base version for conflicts.Adds the atomic commit order, idempotent retries, move and delete conflicts, and conflicted copies.
Storage lifecycleNever mentions deleting chunks.Mentions reference counts and garbage collection.Explains the deletion race, the grace period, mark-and-sweep, and tiering.
CommunicationLists components with no reason.Follows the steps and explains choices.States the trade-off for each choice, such as dedup privacy and manual merges.

AvoidCommon mistakes on this question

MistakeDo this instead
Sending file bytes through the API serversUse pre-signed URLs so clients upload straight to the block store. The API tier only carries small metadata calls.
Storing whole files and re-uploading on any changeChunk files, name chunks by hash, and upload only the missing ones.
Last-writer-wins for conflictsUse a base version on every commit and keep both versions as a conflicted copy.
Writing the version before the chunks existChunks first, then one atomic commit. A failed upload then leaves only orphan chunks.
Deleting a chunk the moment its count reaches zeroMark it, wait a grace period, confirm with mark-and-sweep, and touch it on every dedup hit.
Using timestamps to find changesUse a journal with an increasing cursor per namespace. Clocks differ and can tie.
Sharding metadata by user idShard by namespace id so a commit to a shared folder is one single-shard transaction.
Promising dedup with no mention of privacy or encryptionSay that β€œalready stored” leaks existence, and that end-to-end encryption removes cross-user dedup.

Revise60-second revision sheet

  • βœ”Core: chunk files (about 4 MB), name by SHA-256, store chunks in object storage, store the ordered hash list in metadata.
  • βœ”Scale: 100M daily users Γ— 2 changes = 200M commits/day (about 2,300/s). The load is bytes: about 18 Gbps in, 37 Gbps out.
  • βœ”Storage: 350 PB after 30% savings. Erasure coding about 525 PB, against 1,050 PB for 3 copies.
  • βœ”Upload: send hashes, get the missing list, PUT only missing chunks to pre-signed URLs, then commit with base_version.
  • βœ”Chunking: content-defined beats fixed for inserts (4 MB against 161 MB in the example). Fixed wins for appends.
  • βœ”Sync: per-namespace journal with a cursor, plus a tiny push hint (long poll or WebSocket). Safe to lose a hint.
  • βœ”Conflicts: base version on every commit. If it moved on, save a conflicted copy. Never silently overwrite.
  • βœ”Metadata: sharded relational DB by namespace id. A commit is one single-shard transaction.
  • βœ”Deletion: refcount to zero means mark. Delete after a grace period, confirmed by mark-and-sweep.
  • βœ”One line: β€œCut the file into hashed chunks, upload only what is missing, commit once, and let every device pull the journal.”

Read these topics next

Object Storage→

Where the chunks live, with erasure coding and tiers.

Compression and Deduplication→

Why identical chunks are stored once.

Merkle Trees→

A way to find which folders or chunks differ quickly.

Bulk APIs and File Upload→

Resumable, chunked, pre-signed uploads.

Long Polling→

How a device waits for a change hint cheaply.

Erasure Coding→

Durability at 1.5Γ— instead of 3Γ—.

Shard Keys, Hot Shards and Resharding→

Why we shard by namespace and what a hot shard looks like.

Storage Tiers (Hot, Warm, Cold)β†’

Moving old versions to cheaper storage.

← Previous
Design Search Autocomplete
Next β†’
Design Video Streaming (YouTube/Netflix)