Skip to content

File storage

A file storage service keeps a user’s folders in the cloud and keeps the same folders on all of the user’s devices. Change a file on a laptop and the change reaches the phone. The user never thinks about the protocol, and the design is mostly about three costs that are hidden from them: moving bytes that did not need to move, asking the same question over and over, and keeping the list of files right when several devices change it.

Functional requirements. Upload a file and download it. Keep a folder in step across devices: a change on one appears on the others. Keep the older versions of a file. When two devices change the same file, lose neither change. Sharing with other users, permissions, search and previews are real features and are left out.

Non-functional requirements. These are targets chosen for this lesson. A change appears on another online device within a few seconds. A file that was acknowledged is never lost. A device that was offline for days catches up without re-downloading everything. The list of files and their versions is never half-updated: a file is either at its old version or at its new one.

Scale. 12.5 million users a day, each making 5 file changes. Files are about 16 MiB, and an edit usually changes a small part of one. Devices ask the service whether anything changed.

Mental model. A file storage service is two systems with different jobs. One keeps the bytes: large pieces, never changed once written, named by their content. The other keeps the story: which pieces make which version of which file, in which folder, in what order. The bytes are cheap to scale and the story must stay consistent, so the two are built differently and kept apart.

The pastebin already split a blob from its details. This case study goes further in three directions that the pastebin did not need: a blob that is edited a little at a time (chunking), many devices that must agree on a folder (sync and consistency), and identical content stored by many users (deduplication).

The method is the one from requests per second, storage and bandwidth. The assumptions are in the table so that you can change them and see what moves. In the lab, one request is one call from a device, and the mix of 100 calls is 50 devices asking whether anything changed, 6 commits, 24 chunk uploads and 20 chunk downloads.

Quantity Working Result
File changes a day 12.5 million users × 5 62.5 million
Chunk uploads a day, if an edit changes one chunk one chunk per change 62.5 million
Chunk uploads per second, on average 62.5 million ÷ 86,400 about 720
Chunk uploads per second at the peak, assuming 3 times the average 720 × 3 about 2,200
Requests per second at the peak 2,200 ÷ 0.24, since uploads are 24 of every 100 requests about 9,000
Of those, per second 50% asking, 6% commits, 24% uploads, 20% downloads 4,500 asking, 540 commits, 2,160 uploads, 1,800 downloads
New data a day, as an upper bound 62.5 million × 4 MiB about 260 TB
Traffic in at the peak 2,160 × 4 MiB about 9 GB/s, which is 72 Gbit/s
Traffic out at the peak 1,800 × 4 MiB about 7.5 GB/s, which is 60 Gbit/s
Chunk index, for each PiB of distinct chunks 2^50 ÷ 2^22 = 2^28 chunks × 64 bytes about 17 GB

The 3 times for the peak, one changed chunk per edit, 64 bytes per index entry and the mix of 100 calls are assumptions, and 4 MiB is the size of a chunk in the model (Dropbox documents 4 MB blocks for its content hash). Four things follow whatever the exact values. The bytes dominate the traffic: tens of gigabits a second move through the chunk path, while the metadata path carries small requests. Half of the requests are devices asking whether anything changed, and nearly all of those get the answer “nothing”. The upper bound for new data is large because it counts a whole 4 MiB for every change, so what the service pays for depends on how many of those chunks are already stored. And the chunk index is small enough to keep in fast storage: 17 GB for a PiB of data.

Three kinds of calls carry the traffic. The first two touch the metadata and the third touches the chunks.

GET /changes?namespace=n42&cursor=1800713 → {"entries": [...], "cursor": 1800729}
POST /commit {"namespace": "n42", "path": "/work/plan.docx", "baseVersion": 7,
"chunks": ["9f86d0…", "a3c1b2…", "77e0f4…", "c0ffee…"]}
→ 200 {"version": 8} or 409 Conflict or 200 {"missing": ["a3c1b2…"]}
PUT /chunks/a3c1b2… (4 MiB of bytes) GET /chunks/a3c1b2…

/changes is how a device catches up: the cursor is the last change it has seen in that folder. /commit records a new version of a file, which is a list of chunk hashes; if some chunks are not stored yet the server answers with the missing ones and the client uploads them and commits again. The chunk calls move the bytes, and a chunk is named by its own hash.

The metadata is a few tables, and every row belongs to a namespace, which is one user’s folder tree or one shared folder.

Table Meaning
file_versions Namespace, path, version number, the ordered list of chunk hashes, size, who and when.
changes Namespace, an increasing cursor, and what changed (path and new version). This is the log that devices read.
chunk_index Chunk hash, where it is stored, and a count of the file versions that refer to it.

The lab starts with the simplest design that works and adds one thing at a time. Each stage is designed for a load, and the slider raises the load to 3 times and 10 times that, which shows where the stage runs out. Every figure is model output with illustrative inputs, and the model notes under the lab list what it leaves out.

A service that keeps users’ files and keeps their devices in step, in the style of Dropbox or Google Drive. Most requests ask whether anything changed; the heavy ones move chunks of 4 MiB. Step through six stages, each adding the one thing the previous stage’s numbers called for, and raise the load to see what breaks.

Stage 1 of 6

Start simple: one server keeps whole files

Design load of this stage: 100 req/s

What we add
One API server accepts whole files and keeps them on its own disk, and one database records file names and versions. A device uploads a changed file in full, and every other device downloads it in full.
Why: the number that forced it
At 100 requests per second the disk handles 44 whole-file transfers per second. A 16 MiB file takes about 60 ms and the disk works on 4 at a time, so it can do about 67 per second: it is at 66%. The database is at 13% and the API server at 3%.
What it costs
Nothing to run but one server and one database. The cost is in what is repeated: change one line of a 16 MiB file and all 16 MiB travel again, in each direction. An upload that breaks at 90% starts over from zero. The disk also holds the only copy of everyone’s files.
What breaks next
At 3 times the load, 300 requests per second, the disk is asked for 132 transfers per second against its 67: it is at 198% and 22% of the requests fail. The database is at 38%, so the disk is the first to go.
Design load (100 req/s)
0.3 ms0.3 ms0.2 msDesktop andmobile appsHealthy<1%File APIHealthy3%MetadatadatabaseHealthy13%Server disk(whole files)Busy66%
0.3 ms0.3 ms0.2 msDesktop andmobile appsHealthy<1%File APIHealthy3%MetadatadatabaseHealthy13%Server disk(whole files)Busy66%

Each dot stands for many requests. The numbers show the real rate.

No bottleneck: every component has headroom.

Figures at this load

Busiest component
Server disk (whole files)Busy66% of its capacity
p95, whole request
162 ms
p99, whole request
281 ms
Requests served
100%100 req/s
Requests failed
0%0 req/s
Bottleneck
none
0 ms
Metrics
ComponentStateUtilisationOffered (req/s)Served (req/s)Rejected (req/s)p50p95p99
Desktop and mobile appsHealthy<1%10010000 ms0 ms0 ms
File APIHealthy3%10010002.8 ms12 ms18 ms
Metadata databaseHealthy13%767603.5 ms15 ms23 ms
Server disk (whole files)Busy66%4444057 ms213 ms314 ms
Traffic
100 req/s
Successful
100 req/s
Error rate
0%
Mean latency
42 ms
All stages at a glance

Each cell is the engine’s steady state for that stage at that load: the busiest component, how much of its capacity it uses, and the share of requests that fail.

All stages at a glance
StageDesign loadDesign load3× the design load10× the design load
1. Start simple: one server keeps whole files100 req/s100 req/sServer disk (whole files): 66%none fail300 req/sServer disk (whole files): 198%22% fail1K req/sServer disk (whole files): 660%47% fail
2. Split files into chunks and keep them in a block store300 req/s300 req/sMetadata database: 38%none fail900 req/sMetadata database: 114%9.3% fail3K req/sMetadata database: 380%56% fail
3. Tell devices when something changed1K req/s1K req/sMetadata database: 43%none fail3K req/sMetadata database: 130%6% fail10K req/sMetadata database: 347%25% fail
4. Shard the metadata by namespace3K req/s3K req/sFile API: 38%none fail9K req/sFile API: 113%5.6% fail30K req/sFile API: 375%37% fail
5. Scale out the API and the block store9K req/s9K req/sBlock store (chunks): 35%none fail27K req/sBlock store (chunks): 105%2% fail90K req/sBlock store (chunks): 248%37% fail
6. Store each chunk once: deduplicate by hash9K req/s9K req/sBlock store (chunks): 25%none fail27K req/sBlock store (chunks): 76%none fail90K req/sBlock store (chunks): 181%30% fail

Illustrative values, not benchmarks of any real product.

Model notes

Assumptions

  • Requests arrive at random, as a Poisson process, at a constant average rate.
  • Each node is one queue, served first-come first-served by several identical slots (instances × concurrency).
  • Service times are random with the stated mean; by default they are exponentially distributed.
  • Each node is analysed separately, with the traffic it receives treated as Poisson.
  • For every 100 requests, 50 are devices asking whether anything changed, 6 are commits that record new file versions, 24 are chunk uploads and 20 are chunk downloads. The ratios are teaching figures, not measurements of a real service.
  • A file is 16 MiB, which is 4 chunks of 4 MiB, and an edit changes one chunk. A whole-file transfer takes 60 ms and a chunk transfer 15 ms on one slot of the storage. In the last stage half of the chunks that devices upload are already stored. Every number (service times, capacities, the mix, the hit ratio) is illustrative model output, not a benchmark of a real disk, database or network.

Simplifications

  • Above capacity there is no steady state. The model switches to a fluid approximation: the node serves at capacity, its queue grows until it reaches its limit, and further requests are rejected.
  • Percentiles assume an exponential tail. A service-time variability other than exponential changes the mean wait but not the shape of the tail.
  • A node frees its slot as soon as it has done its own work, before waiting on the services it calls. Real thread-per-request servers hold the slot, so a slow dependency exhausts them faster than this model shows.
  • A request calls its dependencies one after another. Parallel fan-out is not modelled.
  • When a caller times out and gives up, the callee still finishes the work, so abandoned requests keep consuming capacity.
  • Retries add load. Their backoff and jitter decide when that load arrives, which only the per-request simulation shows.
  • Retry feedback is solved from the healthy starting point, so it finds one stable outcome. Systems that stay stuck in overload after the cause is gone are not shown.
  • A throughput limit (for example maximum writes per second) is modelled as slower service, not as a separate rate limiter.
  • A caller’s timeout counts the mean time its dependencies take, not their full distribution.
  • Latency percentiles for a whole request are estimated, over every request, including those that are rejected and fail quickly. The mean is exact, and the percentiles come from a gamma distribution that has that mean and the variance of the time spent in each component.
  • Each stage is shown in a steady state: the load is held and the engine says where queues build. A burst, a device that comes back after weeks offline and the first sync of a large folder are not modelled.
  • Bytes are not modelled, only the time a transfer occupies a slot. The bandwidth of a link, the network between data centres and the cost of storage are left out.
  • A notification is priced as one short call. A real service holds one connection for each online device, which costs memory and file descriptors and is a limit of its own.
  • The model sends chunk bytes through the API servers. Real systems usually give the client the address of a block server or a signed link, so the bytes bypass the API tier.
  • Conflicts, sharing between users, permissions, version history, deletion and the clean-up of chunks that nothing refers to, encryption and several regions are not modelled.

Parameter values are illustrative. They are not benchmarks of any real product.

Stage 1, one server keeps whole files. At 100 requests per second the disk handles 44 whole-file transfers per second. A 16 MiB file takes about 60 ms and the disk works on 4 at a time, so its limit is about 67 per second and it is at 66%. The database is at 13%. At 3 times the load the disk is asked for 132 transfers per second and is at 198%: 22% of the requests fail. The number that ends this stage is the cost of moving a whole file for every edit.

Stage 2, chunks. The client cuts each file into chunks of 4 MiB, hashes them, and uploads only what changed. A chunk transfer takes a quarter of the time, and 10 block servers can do about 5,300 per second, so at 300 requests per second the block store is at 2%. The price is metadata: a file version is now a list of hashes. The next limit is the single metadata database. At 3 times the load, 900 requests per second, it is asked for 684 queries per second against 600, which is 114%, and 9% of the requests fail. Of those queries, 450 are devices asking whether anything changed.

Stage 3, a change feed. A notification service holds a connection to each online device and tells it when its folder changed. At 1,000 requests per second the database is asked for 260 queries per second, 43%, where polling would have asked for 760 (127%). The price is an open connection for each online device, which the model does not count. Now the commits and downloads alone overload the database: at 3 times the load it is at 130% (780 queries per second against 600) and 6% of the requests fail.

Stage 4, metadata shards. The database becomes 16 shards by namespace, which can do 9,600 queries per second together. At the same 3,000 requests per second the shards are at 8%. Sharding by namespace, not by file, keeps a folder’s files together, and the next section explains why that matters. The limit moves to the single API server: at 3 times the load, 9,000 requests per second, it is asked for 4,500 against 4,000, which is 113%, and 6% of the requests fail, while the shards are at 22%.

Stage 5, scale out. A load balancer spreads requests over 8 API servers, which can do 32,000 requests per second, and the block store grows to 17 servers. At 9,000 requests per second the API is at 14% and the block store at 35%. At 3 times the load, 27,000 requests per second, the block store is the first to run out: 11,880 chunk transfers per second against about 11,300, which is 105%, with the metadata shards at 73% close behind.

Stage 6, deduplication. A chunk index tells an upload whether the chunk is already stored. The model assumes half of the uploaded chunks are. At 27,000 requests per second the block store is then asked for 8,640 transfers per second instead of 11,880, and is at 76%: there is no bottleneck. At 10 times the load, 90,000 requests per second, everything is over its limit: the block store at 181%, the metadata shards at 173%, the API servers at 141%, and 30% of the requests fail. More shards, a cold tier for chunks nobody reads, and several regions come next, and they are outside this model.

Cutting a file into chunks is what lets a small edit stay small. The usual way is to cut at fixed offsets, every 4 MiB, and hash each piece with a function such as SHA-256. The name of a chunk is then its hash. Dropbox documents exactly this for its content hash: blocks of 4 MB, the last one possibly smaller, each hashed with SHA-256. Its storage system holds blocks of up to 4 MB named, for most uses, by the SHA-256 of the block.

A name that is the hash of the content has useful properties. Two identical chunks have the same name, so the second upload can be skipped (stage 6). A chunk never changes, because changing it would change its name, so chunks can be cached and copied freely. And a client can check what it downloaded against the name. The cost of a fixed offset is what an insertion does: add a few bytes at the start of a file and every later chunk shifts, so every chunk’s hash changes and the whole file is uploaded again. Content-defined chunking avoids that by choosing the boundaries from the content itself, so an insertion changes only the chunks near it; it costs more CPU to compute. Chunk size is a trade-off too, and the Syncthing protocol shows another choice: blocks from 128 KiB to 16 MiB, with the size chosen for each file and constant within it.

The bytes are easy to keep right, because a chunk is written once and never changed. The hard part is the story. A device that sees a file in the list must be able to download all of its chunks, and two devices that change the same file must not silently overwrite each other. Three rules do most of the work.

Chunks first, metadata last. A commit makes a new version visible, so it must happen only after every chunk of that version is stored. The client commits, the server answers with the chunks it lacks, the client uploads them, and commits again; the server checks that every chunk is present and then, in one transaction, writes the new version and appends an entry to the changes log. The commit is the single moment the change becomes real. A device that dies halfway leaves chunks that nothing refers to, which are harmless and are cleaned up later.

One namespace, one shard, one transaction. The changes log of a namespace needs an increasing cursor with no gaps, and a commit must check the version it is based on and write the new one atomically. That is easy inside one database and hard across two. So the metadata is sharded by namespace: every row of a folder tree is in one shard, and a commit or a list of changes is a query to one shard. Dropbox describes its metadata store as sharded and strongly consistent by default. The price is the operation that crosses namespaces, such as moving a file from a shared folder to a private one. It touches two shards and needs a protocol such as a saga or two-phase commit, the same trade that the lesson on cross-shard queries describes.

A commit names the version it is based on. The commit says “this is version 8, built on version 7”. If the file is already at version 8 because another device committed first, the check fails and the server answers 409. The client does not overwrite: it keeps its copy as a separate file. Many sync services call this a conflicted copy. The user sees two files and decides, which is worse than a clean merge and better than a lost edit. Dropbox’s account of rewriting its sync engine says the same thing about the setting: clients can be offline for a long time and reconcile when they return, so partitions are normal operation and not an exception.

Sync is then a cursor. A device remembers the last cursor it saw for each namespace and asks for entries after it. The notification of stage 3 does not replace this. It carries no data, only “look again”, so a lost notification delays a change and cannot lose one, and devices still ask slowly as a backstop.

What happens if two devices change a file offline

Section titled “What happens if two devices change a file offline”

A laptop and a phone both hold version 7 of plan.docx, and both go offline. The laptop edits it and commits version 8 when it reconnects. The phone, which was based on version 7, then commits its edit. The server sees a commit built on 7 for a file that is at 8, and answers 409. The phone’s client stores its file as plan (phone's conflicted copy).docx and uploads that as a new file. Nothing was lost, and nothing was merged: the chunks of both versions are stored, and the user gets two files. A service that accepts the second commit without the check keeps whichever arrived last and loses the other edit without saying so.

What happens if a device dies halfway through an upload

Section titled “What happens if a device dies halfway through an upload”

The client has uploaded 3 of the 4 chunks of a new version and its battery dies. Nothing was committed, so no other device sees the file. The 3 chunks sit in the block store with nothing referring to them. When the device returns it commits again, the server answers with the one missing chunk, the client uploads it and commits. If the device never returns, the 3 orphan chunks stay until a clean-up job deletes chunks that have no reference after a grace period. The grace period matters: delete too soon and you can remove a chunk that a slow upload is about to commit.

What happens if the chunk index points at nothing

Section titled “What happens if the chunk index points at nothing”

Deduplication trusts the index. If an entry says a chunk is stored when it is not, because a disk was lost or a delete raced an upload, the next upload of that chunk is skipped, the version refers to a chunk that does not exist, and a file cannot be downloaded. Three defences work together. Check that every chunk exists when the commit happens, not only that the index says so. Keep a count of the file versions that refer to each chunk and delete a chunk only when the count is zero and a delay has passed. And scrub the store regularly, reading chunks back and comparing them with their hashes. Because the name is the hash, a corrupt chunk is detectable.

A device does not hear that its folder changed. It keeps showing the old state until its slow poll asks, which can be a minute or more. The cursor means it then receives every change after the one it last saw, in order, so it ends in the right state. The cost of a lost notification is delay, which is why the message carries no data. If it did, a lost message would be a lost change.

Decision What you gain What you pay When to choose otherwise
Chunks of 4 MiB A small edit moves one chunk, uploads can resume, identical chunks are stored once A row of metadata for every chunk, hashing on the client, and no gain for a file smaller than a chunk Mostly small files, or very large files that change everywhere (smaller or larger chunks, or whole files)
Content-defined chunk boundaries An insertion changes only the chunks near it More CPU to find the boundaries, and chunk sizes that vary Files that are only appended to or replaced, where fixed offsets are enough
A notification service Devices learn of a change in seconds and stop asking A connection for every online device, and a service to keep up A small number of devices, where a slow poll is enough
Metadata sharded by namespace A commit and a list of changes are one query on one shard, with a gapless cursor Cross-namespace moves need a protocol, and a very busy shared folder lives in one shard When the workload is mostly shared folders spanning huge numbers of users, where you may shard inside a namespace and accept a harder protocol
Deduplicating across users One copy of popular content, fewer bytes uploaded An exact index, reference counts before deletion, and a side channel that reveals whether a file exists When privacy matters more than storage: deduplicate within one account only

On the last row, Harnik, Pinkas and Shulman-Peleg described in 2010 how deduplication across users lets someone learn whether another user has a given file, by seeing that an upload of it is skipped.

An interviewer asks for this system in 45 minutes. A good answer starts with the numbers (small requests are most of the count, large chunks are most of the bytes), separates the bytes from the metadata, builds the stages in the order the numbers force them, and says out loud what the commit order guarantees. Write your answer before you read the strong one.

Interview question

Writing and reviewing an answer needs JavaScript.

The interviewer asks

Design a file storage and sync service like Dropbox: a user keeps folders on several devices, and a change made on one device appears on the others. Walk through your design.

Assume 12.5 million daily users who make 5 file changes each, files of about 16 MiB, and edits that usually change a small part of a file. Devices can be offline for days.

Write your answer first. The strong answer unlocks once you have written a real attempt.

0 of 80 characters written to unlock the strong answer

  • 12.5 million users making 5 changes a day are 62.5 million chunk uploads, about 720 per second on average and 2,200 at the peak, which makes about 9,000 requests per second. New data is up to about 260 TB a day, and traffic at the peak is about 72 Gbit/s in and 60 Gbit/s out.
  • Stage 1 keeps whole files on one disk: it is at 66% at 100 requests per second and at 198% at 300. Chunks of 4 MiB make a transfer a quarter of the size and put the block store at 2%.
  • Half of the requests are devices asking whether anything changed. A change feed cuts the database from 760 to 260 queries per second at 1,000 requests per second, and metadata shards by namespace take 780 queries per second at 8% of their 9,600.
  • Scaling out the API and the block store, and then deduplicating by chunk hash, take the block store from 105% to 76% at 27,000 requests per second.
  • A commit puts chunks first and metadata last, in one transaction on the namespace’s shard, and names the version it is based on: a conflict becomes a second file and not a lost edit.
  • A lost notification costs delay, an interrupted upload leaves harmless orphan chunks, and a wrong index entry is the dangerous one: check existence at commit, count references, and scrub.

Next: Notification system, which fans a message out over several channels and never sends it twice.

Your progress

Built by GhaziAlibi.

© ShardCraft. All rights reserved.