Skip to content

Pastebin

A pastebin lets someone paste a block of text, get a link, and share the link. The person who opens the link sees the text. Most pastes are opened a few times and then forgotten, so every paste has an expiry time, and the service is as much about throwing data away as about keeping it.

Functional requirements. Create a paste of up to 1 MB of text and get a link. Open a link and read the text. Choose when it expires: 10 minutes, 1 day, 1 week, 1 month or 1 year. Delete a paste with a token given at creation. Accounts, editing, syntax highlighting and abuse detection are left out.

Non-functional requirements. These are targets chosen for this lesson. A paste opens in under 200 ms at the 99th percentile. A paste is never shown after it has expired, which is a correctness rule and not a performance goal. A paste is never lost before it expires. Anyone with the link can read the paste, and nobody without it should be able to find it.

Scale. 10 million new pastes a day, about 10 KB on average, each opened about 9 times. We assume the average paste lives 30 days.

Mental model. A pastebin is two kinds of data with two different lives. The text is big, never changes, and is read whole by its key. The details (who, when, how big, when it expires) are small, are searched by time, and decide what is visible. Most of the design is keeping those two apart, and making the second decide for the first.

This case study does not repeat how to hand out unique codes or how to scale a read-heavy lookup: the URL shortener covers both. Here the new questions are where a large blob lives, and how a service forgets things.

The same method as before (requests per second, storage), with one difference: the data is large enough that retention matters.

Quantity Working Result
New pastes per second, on average 10 million ÷ 86,400 about 116
Reads per second, on average 116 × 9 about 1,040
Peak, assuming 3 times the average (116 + 1,040) × 3 about 3,500 requests per second, rounded up to 4,000
New data per day 10 million × 10 KB 100 GB
Live data with expiry, average life 30 days 10 million × 30 pastes, × 10 KB 300 million pastes, 3 TB
Live data without expiry, after 1 year 100 GB × 365 36.5 TB, about 12 times more
Details of the live pastes 300 million × about 200 bytes about 60 GB
Traffic out at the peak 3,600 reads per second × 10 KB 36 MB/s, about 290 Mbit/s
Same, if an edge cache answers 80% of the reads 720 reads per second × 10 KB 7.2 MB/s, about 58 Mbit/s

The peak factor 3 and the 30-day life are assumptions; so is the 10 KB. Four conclusions hold for any reasonable values. The text is almost all of the bytes: 3 TB against 60 GB of details, a ratio of 50 to 1. The reads are repeats of a small set: a paste is read mostly in the hours after it is shared. Expiry is not housekeeping, it decides whether the service stores 3 TB or 36.5 TB. And deletion is a workload: with every paste expiring once, there are as many deletions as creations, 400 per second at the lab’s peak.

An identifier has to resist guessing, because the link is the only access control. Twelve characters of base 62 are 62 to the power 12, about 3.2 × 10²¹ values. With 300 million live pastes, a random guess hits a live paste with probability about 1 in 10 trillion. The 7-character codes of the URL shortener would be too short here, because the link is the only protection a paste has.

POST /pastes {"content": "…", "expiresIn": "1d"}
201 Created {"id": "k3Fq9TzP1xWb", "url": "https://paste.example/k3Fq9TzP1xWb", "deleteToken": "…"}
GET /k3Fq9TzP1xWb
200 OK Cache-Control: max-age=… (the text)
404 Not Found an identifier that does not exist
410 Gone a paste that has expired or been deleted
DELETE /k3Fq9TzP1xWb Authorization: Bearer <deleteToken>

The details are one row for each paste, in a database.

Column Meaning
id The primary key: 12 random characters.
blob_key The name of the text in the object storage.
size, created_at How big, and when.
expires_at When the paste stops being visible. This column has an index: the sweeper searches by it.
delete_token_hash A hash of the deletion token, never the token.

The text itself is an object in an object store, named by blob_key. The row says where the text is and whether it may be shown; the object is only bytes.

The lab grows the design one decision at a time. Every figure is model output from illustrative inputs; the model notes under the lab say what it leaves out.

A service where people paste text and share a link to it. A paste is written once, read many times and expires. Step through five stages, each adding the one thing the previous stage’s numbers called for, and raise the load to see what breaks.

Stage 1 of 5

Start simple: one API and one database

Design load of this stage: 100 req/s

What we add
One API server stores each paste, its text and its details together, in one database row, and reads it back by the random identifier in the link. Each paste has an expiry time, and a background sweeper deletes the rows whose time has passed.
Why: the number that forced it
At 100 requests per second, 90 reads and 10 new pastes, plus the 10 deletions of pastes that expire, the database gets 110 queries per second. A row that holds a paste of about 10 KB takes about 8 ms, 4 at a time, which is 500 queries per second, so the database is at 22%.
What it costs
Simple: one database to run and to back up, and a paste and its details can never disagree. The price is that every byte of every paste lives in the database, its backups and what it copies to a replica, and each part is a single point of failure.
What breaks next
At 10 times the load, 1,000 requests per second, the 1,000 queries and 100 deletions (1,100 queries per second) are 220% of the database’s 500: it is overloaded and 55% of the requests fail.
Design load (100 req/s)
0.3 ms0.3 ms0.3 ms0.3 msBrowsersand appsHealthy<1%Paste APIHealthy1%Database (metadataand content)Healthy22%Expiry sweeperHealthy<1%
0.3 ms0.3 ms0.3 ms0.3 msBrowsersand appsHealthy<1%Paste APIHealthy1%Database (metadataand content)Healthy22%Expiry sweeperHealthy<1%

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

No bottleneck: every component has headroom.

Figures at this load

Busiest component
Database (metadata and content)Healthy22% of its capacity
p95, whole request
28 ms
p99, whole request
40 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
Browsers and appsHealthy<1%10010000 ms0 ms0 ms
Paste APIHealthy1%10010001.4 ms6 ms9.2 ms
Database (metadata and content)Healthy22%11011005.6 ms24 ms37 ms
Expiry sweeperHealthy<1%101000.69 ms3 ms4.6 ms
Traffic
100 req/s
Successful
100 req/s
Error rate
0%
Mean latency
11 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 API and one database100 req/s100 req/sDatabase (metadata and content): 22%none fail300 req/sDatabase (metadata and content): 66%none fail1K req/sDatabase (metadata and content): 220%55% fail
2. Keep the text in object storage1K req/s1K req/sMetadata database: 55%none fail3K req/sMetadata database: 165%39% fail10K req/sMetadata database: 440%90% fail
3. Cache pastes at the edge4K req/s4K req/sMetadata database: 76%none fail12K req/sMetadata database: 228%15% fail40K req/sMetadata database: 543%25% fail
4. Split the metadata over 4 shards4K req/s4K req/sObject storage (paste content): 31%none fail12K req/sObject storage (paste content): 93%none fail40K req/sObject storage (paste content): 221%20% fail
5. Delete expired pastes in batches4K req/s4K req/sObject storage (paste content): 23%none fail12K req/sObject storage (paste content): 68%none fail40K req/sObject storage (paste content): 163%15% 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.
  • The mix is 9 reads for each paste created: 90% of the requests read a paste and 10% create one. The ratio is a teaching figure, not a measurement of a real service.
  • Every number (service times, capacities, the edge cache hit ratio, the design loads) is illustrative model output, chosen to make the limit of each stage visible. None of them is a benchmark of a real database, object store, CDN or server. The object storage is given about 4,900 requests per second only so that it can be a limit in this lab: a real one spreads its load over many partitions.
  • Every paste expires, so in steady state each paste created is deleted once: the sweeper does one metadata delete and one content delete for each paste created. The edge cache answers 80% of the reads.

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 cold edge cache warming up and a deploy are not modelled.
  • The edge cache hit ratio is fixed at 80%. A real one depends on how the reads are spread over the pastes, and a cached paste has to be dropped when it expires or is removed, which the model does not charge for.
  • Deleting is modelled as the load it puts on the metadata database and the object storage. How the sweeper finds the expired pastes (an index or a partition on the expiry time) is not modelled.
  • Storage size and cost, the upload of large pastes (the API carries the bytes here), abuse prevention, access control for private pastes and several regions are not modelled.

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

Stage 1, one API and one database. The text sits in the database row with its details, and a sweeper deletes the rows that have expired. At 100 requests per second, with the 10 deletions per second of expiring pastes, the database gets 110 queries per second of the 500 that a row of about 10 KB allows: 22%. At 10 times the load, 1,000 requests per second, it is asked for 1,100 and is at 220%: 55% of the requests fail.

Stage 2, the text in object storage. The text moves to an object store, and the database keeps only the details. A row of details is small, so the metadata database can do 2,000 queries per second instead of 500, and the object storage about 4,900 requests per second (the model gives it a limit so that it can matter; Amazon documents at least 3,500 write or delete requests per second per prefix, and a real store can be spread over many prefixes). At 1,000 requests per second the two are at 55% and 22%. At 3 times the load the metadata database is asked for 3,300 queries per second and is at 165%: 39% of the requests fail, while the object storage is at 67%.

Stage 3, an edge cache. A paste never changes, so a copy is right until it expires or is removed. With an edge cache that answers 80% of the reads, a load of 4,000 requests per second reaches the API as 1,120: 720 reads that missed and 400 new pastes. With the 400 deletions the metadata database sees 1,520 queries per second, 76% of its 2,000. At 3 times the load it is asked for 4,560 and is at 228%: 15% of the requests fail. The object storage is already at 93%.

Stage 4, metadata in 4 shards. The metadata is split into 4 shards by the identifier, which is random and so spreads the pastes evenly (see choosing a shard key). Four shards can do 8,000 queries per second between them, so the same 4,560 are 57%. A lookup carries the identifier from the link, so it goes to one shard. At 3 times the load the object storage is now the busiest component, at 93% of its 4,900 requests per second, and 1,200 of the 4,560 requests per second it receives are deletions, one paste at a time.

Stage 5, batched deletions. The sweeper collects expired pastes and removes 100 at a time: one query for 100 rows, and one request for 100 objects (the DeleteObjects call of Amazon S3 takes up to 1,000 keys). At 12,000 requests per second the 1,200 deletions per second on each system become 12. The object storage falls from 93% to 68%, at 3,372 requests per second. At 10 times the load, 40,000 requests per second, the object storage is overloaded at 163%, the API server at 140% and the metadata shards at 100%. The lab stops here; the next steps are to let browsers upload straight to the object store with a presigned URL so that the API stops carrying the bytes, to spread the object store over more key prefixes, and to add API servers (as in the URL shortener).

Why the text and its details are stored apart

Section titled “Why the text and its details are stored apart”

Putting the text in the database row is the simplest design, and stage 1 shows it working. It stops being a good idea for reasons that are not all in the lab. Every byte of every paste then lives in the database’s backups and in what it ships to each replica. The database is built to find and change small rows; the object store is built to keep large objects durably and to serve them whole. And the two scale differently: the text grows with the bytes, while the details grow with the number of pastes and with the search load.

Splitting them creates a rule about order. When a paste is created, the service writes the object first and the row second. The row is the commit: a paste exists once its row exists. If the service crashes between the two writes, what is left is an object that no row points to, an orphan. It costs a little storage and nobody can see it. The opposite order is worse: a row that points to an object that was never written is a paste that exists and cannot be shown. Orphans are found later by comparing, and deleted: for example a job that lists the objects older than a day and removes those with no row. An alternative is to write a row marked pending first and mark it ready after the object is stored, so that unfinished pastes are known and not found by searching.

How a service forgets: three layers of expiry

Section titled “How a service forgets: three layers of expiry”

Expiry is not one mechanism. It is three, and each one does a job the others cannot.

The check on read. Every read looks at expires_at, and a paste that has expired answers 410 Gone even if its row and object are still there. This is the layer that makes the correctness rule true. It does not depend on anything finishing on time, so if the layers below are late, nothing expired is ever shown. It uses the time of one clock per decision, the database’s, and a few seconds of difference between machines is acceptable here (see physical clocks).

The background deletion. A sweeper finds the rows whose time has passed, using the index on expires_at, and removes them to free the space. This is the layer that decides whether the service stores 3 TB or 36.5. Order matters here too, and it is the reverse of creation: delete the objects first, then the rows. If the sweeper crashes after the objects and before the rows, the rows are still there, are already refused by the check on read, and the next pass deletes them again. Deleting twice must be harmless. The other order leaves objects that no row can lead you to, which is how storage leaks. The batches of stage 5 fit this: 100 rows, 100 objects, then 100 rows. Each shard runs its own sweeper over its own index, so no query has to cross shards.

The time limit at the edge. The text is cached with Cache-Control: max-age set to the time the paste has left, never more (HTTP caching, RFC 9111 defines the directive). A copy at the edge then expires when the paste does. This layer does nothing for a paste removed early, which is why a delete or an abuse takedown has to purge the edge, or why a service that cannot purge quickly caps max-age at a few minutes and accepts a lower hit ratio.

A fourth tool exists for the objects: the storage’s own lifecycle rules, such as Amazon S3’s expiration actions. They work in whole days from the object’s creation, and the documentation says there can be a delay between the expiration date and the removal. A 10-minute paste cannot use it, and the rows would still need deleting. It suits one prefix per retention class, such as “30 days”, as a backstop to the sweeper.

The check on read keeps the correctness rule true: nothing expired is shown. What stops is the freeing of space. New data arrives at 100 GB a day, so a stopped sweeper adds about 100 GB of expired data each day to the 3 TB; over a year, without it, the service would hold the 36.5 TB. This failure is quiet, because nothing a user sees is wrong. The alarm to set is on the age of the oldest row that has expired and still exists: it should stay under the sweep interval, and a rising value is the sign.

Take the final design at its design load of 4,000 requests per second and set the edge hit ratio to 0 (the lab has no control for this; the figures are the engine’s answer for that graph). All 3,600 reads reach the API, which is at 50% of its 8,000 requests per second. The shards are at 50%. The object storage receives 4,004 requests per second, 81% of its 4,900: it survives, but with almost no room. At 3 times the load it would not. Losing the cache is survivable here only because the design left the origin room for one; the question to ask of any cache is what the origin does without it (the cache failure lesson works through the same arithmetic).

The user sends a paste, the object is stored, and the service crashes before the row is written. The user gets an error and sends it again. The first object is an orphan and the second attempt creates a second object and a row. Nothing is shown twice, and the orphan is found and deleted by the comparison job. If the user’s request was retried by a client library without the user doing anything, the same thing happens, and an idempotency key would make the retry reuse the first identifier instead of creating a second paste.

Decision What you gain What you pay When to choose otherwise
Text in object storage, details in a database Cheap durable storage for the bytes, and a small fast database Two systems, an order of writes, orphans to collect When pastes are tiny and few: one table with the text inline is simpler and has one failure mode
Object first, row second A row never points at nothing; a crash leaves only an invisible orphan Orphans, and a job to find them When orphans are costly to find: write a pending row first and finish it after
Edge cache with max-age equal to the time left Most reads never reach the origin A removed paste can be served until it is purged or its time limit passes Private pastes, or deletions that must take effect at once: short limits or no edge cache
Sweeper in batches The deletion load nearly disappears (12 per second instead of 1,200 at 3 times the load in the lab) Space is freed late; a batch must be safe to run twice Lifecycle rules, when expiry is in whole days and the rows can be removed another way
Metadata sharded by random identifier Even load, one shard per lookup More databases, and moving data when shards are added A single database with replicas, until the metadata is too big or too busy for one

An interviewer asks you to design a pastebin. The weak answers describe a table and a web page. A good answer separates the text from its details and says why, makes the row the commit and says what a crash leaves behind, and treats expiry as three layers with a reason for each. Write your answer first.

Interview question

Writing and reviewing an answer needs JavaScript.

The interviewer asks

Design a pastebin: a user pastes a block of text, gets a link, and shares it. Anyone with the link can read the text, and every paste expires. Walk through your design.

Assume 10 million new pastes a day of about 10 KB each (up to 1 MB), each read about 9 times, and an average life of 30 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

  • 10 million pastes a day of 10 KB are 100 GB a day. With an average life of 30 days the service holds 3 TB; without expiry it would hold 36.5 TB after a year, about 12 times more.
  • Peak traffic is about 3,500 requests per second, rounded up to 4,000. With every paste expiring once, there are as many deletions as creations: 400 per second at the peak.
  • Stage 1 keeps the text in the database, which is at 22% at 100 requests per second and at 220% at 1,000. Moving the text to object storage lets the metadata database do 2,000 queries per second.
  • An edge cache that answers 80% of the reads brings 4,000 requests per second down to 1,120 at the origin. Sharding the metadata in 4 raises its limit to 8,000 queries per second.
  • Deleting 1,200 pastes per second one at a time puts the object storage at 93%. Deleting in batches of 100 makes it 12 per second and brings the storage to 68%.
  • Write the object before the row, so a crash leaves an invisible orphan. Expire in three layers: a check on every read, a sweeper that deletes objects before rows, and a max-age that ends with the paste.

Next: File storage, which splits files into chunks to sync them and store them once.

Your progress

Built by GhaziAlibi.

© ShardCraft. All rights reserved.