To design Pastebin is to build a service where someone stores a piece of text, gets a short link, and anyone with the link can read it until it expires. A good answer explains how the link (the paste id) is made so that it is unique and hard to guess, where the text and its metadata live, how the many reads are served, how expired pastes disappear, how one-time pastes are burned safely, and how the data is split across servers as it grows.

This lesson designs SnipBin, a snippet-sharing site for a campus coding club. Students paste compiler errors, config files and code, and send the link in chat. Six runnable programs in Java, with Python and C++ versions, test the decisions interviewers probe most: paste ids, the read cache, expiry and cleanup, storing duplicate text once, burn-after-reading pastes, and sharding. All sizes, rates and timings are assumptions chosen to make comparisons clear, not benchmarks of a product.

Key takeaways

  • With sequential ids an attacker found 100,000 of 100,000 guessed pastes. Random 4-character ids had 1,357 collisions among 200,000 pastes and let 1,269 of 100,000 guesses hit. 5 characters had 24 collisions and 20 hits, and 6 characters had 1 collision and no hits. A scrambled counter gave no collisions and no collision check at all.

  • An LRU cache holding 1% of the pastes gave a 23.7% hit rate, 5% gave 62.9% and 10% gave 77.3%, which cut the average read from 20 ms to 5.2 ms. When a popular paste had to be reloaded, 198 database reads happened on average without request coalescing and 1 with it.

  • Deleting a paste only when a read finds it expired left 23,478 expired pastes (117.3 MB) stored. A nightly scan left 5,409 and read 34,812 rows a day. Dropping hourly partitions left 249 with no rows examined. A nightly scan with no expiry check on read served 172,172 reads of expired pastes.

  • Storing a text once by its hash cut 548.4 MB to 373.4 MB (31.9% less). Deleting the shared text on the first expiry made 23,928 pastes lose their text. A reference count lost none.

  • A link-preview bot opened 30,109 of 100,000 one-time pastes before the recipient. Separate read and delete steps showed 9,678 pastes to two people. An atomic get-and-delete fixed that, and a reveal button fixed the bot problem: 0 shown twice and 0 lost.

  • Sharding by id range sent 100% of new writes and 82.3% of reads to one shard. A hash spread them to 13.0% and 12.9%. Adding a 9th shard moved 88.9% of the ids with hash modulo 8 and 10.9% with 64 hash slots.

1. Clarifying Requirements

Functional requirements

  • Create a paste from text, with an optional language and a lifetime (10 minutes, 1 hour, 1 day, 7 days or never).

  • Return a short URL. Anyone with the URL can read the paste. Offer a raw text view.

  • Pastes expire and then cannot be read. The author can delete a paste with a delete key.

  • Optional one-time (burn after reading) pastes.

Non-functional requirements

  • Reads are far more frequent than writes, and they must be fast.

  • Ids must be unique and hard to guess, because an unlisted paste is protected only by its link.

  • Pastes must not be lost while they are alive, and must not be served after they expire.

  • The system stays available when a server fails.

Ask about size limits, whether accounts and search exist, and what the service may host. Leave out accounts, comments, syntax-highlight themes and full-text search. Say so.

2. Back-of-the-Envelope Estimation

  • Writes: 1 million new pastes a day is 12 a second.

  • Reads: with 20 reads for each paste, 240 reads a second on average and about 2,400 at the peak.

  • Storage: at 5 KB a paste, 5 GB a day and 1.8 TB a year if nothing expired. Metadata at about 200 bytes a paste is 200 MB a day.

3. Core APIs

  • POST /v1/pastes with {"content": "...", "language": "java", "expires_in": "1d", "visibility": "unlisted", "burn": false}. The reply is 201 with {"id": "Xk3T9q", "url": "https://snip.example/p/Xk3T9q", "delete_key": "..."}.

  • GET /p/{id} returns the page, and GET /raw/{id} returns the plain text. A missing or expired paste gives 404.

  • DELETE /v1/pastes/{id} with the delete key in a header.

  • POST /v1/pastes/{id}/reveal for one-time pastes: it returns the text once and burns the paste.

4. High-Level Design

The API servers are stateless. They check the size and rate, make the id, and write the text to a blob store and a metadata row (id, owner, expiry time, visibility, blob key) to a database. Reads go through a cache. A miss reads the metadata row, checks expiry and visibility, then fetches the text. The text is stored apart from the metadata because it is large, rarely changes and is read as a whole, which is what object storage is good at (see Design Object Storage).

5. Making the Paste Id

The id is the address and, for unlisted pastes, the only secret. It has to be unique, short enough to type, and impossible to enumerate. Three approaches are common: a database counter, a random string with a uniqueness check, and a counter that is scrambled so that it looks random. A key generation service (KGS) can hand out ids in advance so that the write path needs no check.

The first program creates 200,000 pastes and then lets an attacker try 100,000 addresses. It compares a sequential counter, random ids of 4, 5 and 6 characters from a-z, A-Z and 0-9 (a collision means drawing again) and a counter multiplied by a fixed odd number modulo 625. Because that number shares no factor with 625, the multiplication visits each id once, so ids are unique with no check.

Output

200000 pastes created, then 100000 address guesses by an attacker.

how ids are made             possible ids   collisions   random       pastes found by
                                            (redraws)    draws        guessing
sequential counter           -              0            0            100000
random, 4 characters         14776336       1357         201357       1269
random, 5 characters         916132832      24           200024       20
random, 6 characters         56800235584    1            200001       0
scrambled counter, 5 chars   916132832      0            0            18
  • Sequential counter: the attacker found all 100,000 pastes it tried (1 to 100,000). Every paste is effectively public.

  • Random, 4 characters (14,776,336 possible ids): 1,357 collisions among 200,000 pastes and 1,269 guesses that hit a paste. The expected number of collisions is about n squared over twice the space, here 1,353. Four characters is too few.

  • Random, 5 characters (916,132,832): 24 collisions (expected 21.8) and 20 hits.

  • Random, 6 characters (56.8 billion): 1 collision and no hits.

  • Scrambled counter, 5 characters: no collisions and no uniqueness check, and 18 hits, the same as random guessing.

A scramble is obscurity, not secrecy: if the multiplier leaks, ids can be predicted, so keep it secret and change it per deployment, or use a keyed permutation. If a paste is truly confidential, use a long random id (8 or more characters is 2 to the power 47 or more, and 22 characters is a 128-bit token) and never rely on a short link. Say that the real protection is the length of the id, together with a rate limit on failed lookups, as in Design a Rate Limiter.

6. Serving the Reads

A paste is read many times, so the read path should skip the database. A cache in front of the metadata and the text keeps hot pastes in memory. The cache can only hold part of the data, so it evicts something when it is full. The most common rule is least recently used (LRU). Two questions follow: how big should the cache be, and what happens when many requests ask for something that is not in it?

The second program has 100,000 pastes and 400,000 reads. 1% of the pastes get half of the reads, the next 9% get 40% and the other 90% get 10%. A hit costs 1 ms and a database read 20 ms. It tries five cache sizes. A second part loads one popular paste while 5 to 15 requests for it arrive every millisecond for the 20 ms a database read takes, with and without request coalescing (the first request loads, the others wait for its answer).

Output

400000 reads of 100000 pastes, least-recently-used cache.

cache holds  share of     cache hit    database       average
(pastes)     all pastes   rate         reads          read (ms)
0            0.0 %        0.0 %        400000         20.0
500          0.5 %        12.5 %       349687         17.6
1000         1.0 %        23.7 %       304968         15.4
5000         5.0 %        62.9 %       148363         8.0
10000        10.0 %       77.3 %       90508          5.2

Database reads when one popular paste has to be loaded again (100 trials):
loading rule               average reads  worst     
no coalescing              198            239       
one read, others wait      1              1
  • No cache: 400,000 database reads, 20 ms on average.

  • 500 and 1,000 pastes (0.5% and 1%): 12.5% and 23.7% hits. The hot set is 1,000 pastes, but cold one-off reads keep pushing it out of such a small cache.

  • 5,000 pastes (5%): 62.9% hits and 8.0 ms on average.

  • 10,000 pastes (10%): 77.3% hits and 5.2 ms. The hot and warm pastes (10% of all) fit completely. What is left over are reads of cold pastes and the first read of each paste.

  • Reloading a popular paste: 198 database reads on average (239 at worst) without coalescing, and 1 with it.

The curve flattens: the last 5% of cache gained far less than the first. Size the cache from the share of reads that the hot set gets, not from a round percentage of all pastes. Coalescing, and a short random extra time on expiry so that many pastes do not leave the cache together, prevent a stampede on the database. For a very popular paste, a CDN in front of the raw view takes the load off the servers, because the text never changes (see Design a Distributed Cache).

7. Expiry and Cleanup

An expired paste must not be served, and its space must be given back. These are two jobs. The first is simple and must be exact: check the expiry time on every read. The second can be lazy. The question is which cleanup wastes the least work and leaves the least dead data.

The third program has 200,000 pastes created over 30 days, 5 KB each. Their lifetimes are 10 minutes (20%), 1 hour (20%), 1 day (30%), 7 days (20%) or never (10%), and each is read 3 times. It looks at the state at the end of day 30 under five rules: delete a paste only when a read finds it expired; a full scan every night at 03:00 with no expiry check on read; the same scan with the check; pastes stored in hourly partitions and a partition dropped when its hour has passed; and an index on the expiry time with a delete of the expired rows every 5 minutes.

Output

200000 pastes over 30 days, 5 KB each, state at the end of day 30.

cleanup rule                       expired but  space they   rows examined  reads served
                                   still stored use (MB)     per day        after expiry
delete when a read finds it        23478        117.3        0              0
nightly scan, no check             5409         27.0         34812          172172
nightly scan + check               5409         27.0         34812          0
drop hourly partition + check      249          1.2          0              0
expiry index, every 5 min + check  25           0.1          6010           0
  • Delete when a read finds it: 23,478 expired pastes still stored (117.3 MB), because many pastes are never read again after they expire. No expired paste was served, since each read checks.

  • Nightly scan, no check on read: 5,409 expired pastes (27.0 MB) stored at midnight, because they expired after 03:00. The scan read 34,812 rows a day, and 172,172 reads over the 30 days were served from expired pastes.

  • Nightly scan with the check: the same storage and scan cost, and no expired paste served.

  • Hourly partitions dropped: 249 expired pastes left (1.2 MB) and no rows examined, since dropping a partition is a metadata operation.

  • Expiry index, delete every 5 minutes: 25 left (0.1 MB) and 6,010 rows examined a day, only the rows it deleted.

Partitioning by expiry hour is the cheapest, but the lifetimes must be known when the row is written and a paste with a rare lifetime lands in a partition of its own. An expiry index works for any lifetime and costs a range scan. A full scan is the worst of both when the table is large. Whatever you pick, the read check is what guarantees correctness.

8. Storing the Same Text Once

People paste the same thing again and again: the same compiler error, the same starter config. Content-addressed storage names the text by its hash, so that identical text is stored once and each paste points to it. It saves space, and it changes how deletion must work, because several pastes may share one stored text.

The fourth program has 100,000 pastes. About 3 in 10 are copies of one of 1,000 popular texts, and 2 in 10 pastes expire. It compares one copy per paste, shared text deleted when its first paste expires, and shared text with a reference count that deletes it only when the last paste is gone.

Output

100000 pastes, 29979 are copies of 1000 popular texts, 2 in 10 pastes expire.

storage rule                         stored before  stored after   pastes whose
                                     expiry (MB)    expiry (MB)    text is lost
one copy per paste                   548.4          437.8          0
shared text, delete on first expiry  373.4          293.3          23928
shared text, reference count         373.4          299.3          0
  • One copy per paste: 548.4 MB, and 437.8 MB after the expiries.

  • Shared text: 373.4 MB, which is 31.9% less.

  • Deleting on the first expiry: 293.3 MB, and 23,928 pastes that had not expired lost their text.

  • Reference count: 299.3 MB and no paste lost its text. The 6 MB difference is the text that must stay for the pastes still alive.

The count must change in the same transaction as the paste row, or a crash will leave the count wrong. Use a hash long enough that a collision cannot happen in practice (256 bits), and do not share text across users if that would let one user learn that another has pasted a particular text (a paste that finishes instantly reveals that it already exists). If your service has that risk, deduplicate only inside one user's pastes.

9. Burn After Reading

A one-time paste must be shown once. The naive page reads the text, shows it and then deletes it, which are separate steps, so two readers who arrive close together can both see it. A second problem is easy to miss: chat apps fetch a link as soon as it is posted, to build a preview. That fetch is a read, and it burns the paste before the recipient arrives.

The fifth program has 100,000 one-time pastes. In 3 in 10 a preview bot fetches the link 1 to 2,000 ms before the recipient. The link is also forwarded, and a second person opens it 0 to 39 ms after the recipient. A delete takes 1 to 10 ms to reach the database after a reader has been shown the text. It compares read-show-delete, an atomic get-and-delete, and a page that only shows a Reveal button, where pressing it does the atomic delete.

Output

100000 burn-after-reading pastes, 3 in 10 fetched first by a link-preview bot.

how the page burns the paste         shown to both    recipient finds  consumed by
                                     people           nothing          a preview
read, show, then delete              9678             30055            30109
atomic get-and-delete                0                30109            30109
reveal button, then atomic delete    0                0                0
  • Read, show, then delete: 9,678 pastes were shown to both people, and 30,055 recipients found nothing, because the bot had already read it (30,109 pastes were consumed by a preview).

  • Atomic get-and-delete: none shown twice, but the bot still took 30,109 pastes and the recipient lost them.

  • Reveal button, then atomic delete: none shown twice and none lost. Bots do not press the button.

The atomic operation can be a GETDEL in Redis, a delete that returns the row, or a conditional update that sets a viewed flag. The reveal step must be a POST, because GET requests are made by prefetchers and scanners. Mark one-time pages with noindex and a no-cache header, so that nothing keeps a copy.

10. Sharding

One database holds the metadata for a long time (200 MB a day), but at some point the writes or the size need more than one server. The shard key decides everything. If ids come from a counter and you shard by id range, the newest range receives all the new writes, and the newest pastes are also the most read. A hash of the id spreads both. The remaining question is what happens when a shard is added.

The sixth program has 200,000 pastes with sequential ids on 8 shards. It measures the busiest shard's share of the last 10,000 creates and of 400,000 reads, 8 in 10 of which go to the newest 10,000 pastes. It also measures how many ids change shard when a 9th shard is added. It compares id ranges, a hash of the id modulo the number of shards, and a hash into 64 slots that are assigned to shards (a 9th shard takes over 7 of the 64).

Output

200000 pastes with sequential ids on 8 shards, 8 in 10 reads go to the newest 10,000 pastes.

shard key                  busiest shard  busiest shard  ids moved by
                           (new writes)   (reads)        a 9th shard
id range                   100.0 %        82.3 %         0.0 %
hash of id mod shards      13.0 %         12.9 %         88.9 %
hash into 64 slots         13.0 %         12.9 %         10.9 %
  • Id range: the busiest shard took 100.0% of the new writes and 82.3% of the reads, so 7 shards were nearly idle. A new shard moves no data (new ids go to it).

  • Hash modulo 8: 13.0% of the writes and 12.9% of the reads on the busiest shard, close to the even 12.5%. A 9th shard moved 88.9% of the ids.

  • Hash into 64 slots: the same balance (13.0% and 12.9%) and only 10.9% of the ids moved.

Slots (or consistent hashing, as in Consistent Hashing) are a standard way to add a shard without moving most of the data. Alternatively, keep the random id as the shard key from the start, so that the id itself is evenly spread.

11. Limits and Abuse

A service that stores text for anyone invites misuse: spam, malware links, leaked passwords and personal data. The design needs limits: a size cap for each paste, a rate limit for each account and IP address (see Design a Rate Limiter), a delete key for the author, no search engine indexing for unlisted pastes, a report button and a quick takedown path. Scanning new pastes for secrets such as API keys is a useful extra.

12. Choosing the Design

ConcernChoiceWatch for
Paste idLong random id, or a scrambled counterShort ids and sequential counters
ReadsLRU cache sized to the hot set, coalesced loadsStampedes on a popular paste
ExpiryCheck on read, drop partitions or use an expiry indexFull scans and stale reads
StorageText in a blob store, shared by hash with a reference countDeleting shared text early
One-time pastesAtomic burn behind a reveal buttonLink previews and prefetchers
ScaleHash shard key with slotsId-range shards and hash modulo

13. Trade-offs to Mention

  • Random ids need a longer length or a check, and a scrambled counter is unique by construction and depends on a secret.

  • A bigger cache lowers the read time and gains less with every step.

  • Partitioned expiry is cheap and needs the lifetime when writing. An index is flexible and costs a scan.

  • Sharing text saves space and adds reference counting and privacy questions.

  • A reveal step protects one-time pastes and adds a click.

  • Hash sharding balances the load and loses range queries by id.

14. Common Mistakes

  • Sequential or very short paste ids for unlisted pastes.

  • Trusting cleanup alone to hide expired pastes, with no check on read.

  • Scanning the whole table to find expired pastes.

  • Deleting shared text without a reference count.

  • Burning a one-time paste on a GET request.

  • Sharding by id range when ids are sequential.

  • No size cap, rate limit or takedown path.

15. Interview Questions

  • How do you make the id? Random and long enough that collisions are rare and guessing fails, or a scrambled counter that is unique by construction.

  • Where is the text stored? In a blob store, with the metadata in a database, and hot pastes in a cache.

  • How do you handle a very popular paste? Cache it, coalesce the loads, and put a CDN in front of the raw text.

  • How do pastes expire? The read checks the expiry time, and cleanup drops partitions or deletes by an expiry index.

  • How do you stop duplicates from filling the disk? Store text by its hash with a reference count.

  • How do you build a one-time paste? An atomic get-and-delete behind a POST reveal button, because previews use GET.

  • How do you shard? By a hash of the id into slots, not by id range.

16. Practice Problems

  • You use 6 random characters from 62 symbols and expect 1 billion pastes. About how many collisions will there be? Answer: the space is 56.8 billion, so about n squared over twice the space, which is 1018 divided by 1.14 times 1011, around 8.8 million. Use 8 characters (2.2 times 1014 ids, about 2,300 collisions) or a KGS.

  • A cache holds 20,000 pastes and the hot and warm sets together are 50,000. Will a bigger cache help? Answer: yes, up to the point where both sets fit, because until then the warm pastes push each other out.

  • Why not delete the text when the first paste that points to it expires? Answer: other pastes still need it, so keep a reference count and delete at zero.

  • A chat app shows previews for your links. How do you keep one-time pastes working? Answer: serve a page with a Reveal button for GET, and burn the paste only on POST.

Summary

  • Unguessable ids, long or scrambled, with no sequential counters.

  • Text in a blob store, metadata in a database, hot pastes in a cache with coalesced loads.

  • Check expiry on every read, and clean up by partition or an expiry index.

  • Share duplicate text by hash with a reference count.

  • Burn one-time pastes atomically, behind a reveal button.

  • Shard by a hash with slots, and add limits and a takedown path.

Conclusion

Pastebin looks like storing a string under a key, and the interesting questions are around the edges: the id that is also a secret, the cache that must be sized to the hot set, the deletion that must be exact and cheap, the shared text that needs a count, the one-time paste that a chat app can burn, and the shard key that decides how growth feels. In an interview, say the read rate and the paste size, then show how each choice follows from them.

Previous topic: Design a Rate Limiter. Next topic: Design WhatsApp.

References and further reading

  • The birthday problem, for the expected number of collisions among random ids. OWASP guidance on insecure direct object references and unguessable identifiers.

  • GitHub documentation on secret gists, which are reachable by anyone who has the URL, as an example of a link that is the only protection.

  • Redis documentation on GETDEL, key expiry and eviction policies (LRU and LFU).

  • Amazon S3 documentation on object lifecycle rules, and PostgreSQL documentation on table partitioning, for cleaning up by expiry.

  • Design Object Storage, Design a Distributed Cache and Design a Rate Limiter on this site, for the storage, cache and limit ideas used here.