"Design Pastebin" is the question interviewers pick when they want to see whether you can keep a design small. A user pastes some text, gets a link, and anyone with the link can read it.
It looks like the URL shortener with a bigger payload, and that is exactly the trap. The payload changes the answer. A URL is 100 bytes and a paste can be megabytes, so the question becomes: where do the bytes live, and how do you stop them from dragging your database down?
The interviewer is also listening for what you do with data that must disappear (expiry), data that must stay private (unlisted links) and data that someone will abuse (leaked credentials, malware, spam). A good answer is short on boxes and long on reasons.
Clarify the requirements
Functional requirements:
- A user submits text and receives a unique link.
- Opening the link shows the text. Anyone with the link can read it, no account needed.
- A paste can have an expiry: ten minutes, a day, a month or never.
- A paste can be public (listed on a recent-pastes page) or unlisted (link only).
- A signed-in user can delete their own pastes.
Out of scope, said aloud: editing a paste in place, syntax-highlighting details, comments, full-text search across pastes.
Non-functional requirements:
- Reads dominate and must be fast. A paste is read several times for every time it is written, and readers are often waiting on a teammate's link.
- Pastes are immutable. Nothing edits a paste after it is saved, which makes it very cacheable. This is the single most useful property in the whole design.
- Durable until expiry. A saved paste must not be lost, but it may be deleted exactly when it expires.
- Unlisted means unguessable. The link is the only access control, so keys must not be enumerable.
- Bounded size. Cap a paste at 512 KB so one request cannot occupy a server for long.
Estimate the scale
Assume 1 million new pastes a day, a read-to-write ratio of 5:1, an average paste of 10 KB and a retention of five years for pastes that never expire.
Writes: 1M ÷ 86,400 s ≈ 12 pastes per second, about 35 per second at 3× peak.
Reads: 5M ÷ 86,400 s ≈ 58 reads per second, about 175 per second at peak.
Body storage: 1M × 10 KB = 10 GB a day, 3.65 TB a year, about 18 TB over five years.
Metadata: 1M × 365 × 5 ≈ 1.8 billion rows. At about 200 bytes each (key, owner, size, expiry, created time, visibility, storage pointer), that is about 365 GB.
Read bandwidth: 58 reads per second × 10 KB ≈ 580 KB/s, about 1.7 MB/s at peak: a few megabits.
Key space: 62⁸ ≈ 2.18 × 10¹⁴ keys with eight base62 characters. Against 1.8 billion pastes, only about 0.0008% of that space is ever occupied.
"Twelve writes and fifty-eight reads per second is a small request rate, so this is not a throughput problem. The 18 TB of bodies is the real number: it is too big and too bulky for the database that holds the 365 GB of metadata. Split them, and let a cache or CDN serve the bytes."
You can change the assumptions in the capacity estimator and watch storage move.
API and data model
POST /v1/pastes { body, expiresIn?, visibility? } -> { key, url }
GET /p/{key} -> 200 text, or 404 / 410
DELETE /v1/pastes/{key} (owner only)
GET /v1/pastes/recent -> public pastes, newest firstpaste_meta (key PK, owner_id?, size_bytes, blob_ref, visibility, created_at, expires_at)
blob store object "pastes/{key}" -> the text, gzip-compressedMetadata and body are stored apart on purpose. The metadata row is small, indexed and queried (by key, by expiry, by owner). The body is a large, immutable blob that is only ever fetched whole.
High-level design
The slice to simulate is the read-heavy path: a CDN in front of a stateless paste API, which reads metadata from Postgres and the body from object storage.
- The CDN answers repeat reads of an immutable paste without touching the origin.
- The paste API checks the metadata row (exists, not expired, visible) and then fetches the body.
- Metadata lives in Postgres with replicas, and bodies live in object storage.
Describe this diagram
Components
- readers (Client)
- edge (Content delivery network)
- paste api (Service)
- paste metadata (PostgreSQL)
- paste bodies (Object storage (S3))
Connections
- readers sends to edge
- edge sends to paste api
- paste api sends to paste metadata
- paste api sends to paste bodies
Run it, then try shortening the CDN's ttl_s to a few seconds or cutting the API's connection pool, and watch where the pressure lands. The default connection pool to object storage is small enough to cap throughput quietly, which is a real production lesson.
The write path: the API validates size and content type, generates a key, writes the body to object storage, then inserts the metadata row. In that order, so a metadata row never points at a body that does not exist. A crash between the two steps leaves an orphan blob, which a cleanup job removes later.
The read path: the API looks up the metadata row, returns 404 if it is missing and 410 if expires_at has passed, then streams the body from object storage. The response carries a long Cache-Control header, so the CDN and the browser keep it.
The interesting problem: where the bytes live
Everything here follows from one question: do you put the paste body in the database row?
Approach A: the body in the database row
One table, one body TEXT column, one write per paste.
Good: a single transaction covers the body and the metadata. There is nothing to keep consistent, and a beginner can build it in an afternoon.
Bad: 18 TB of bodies inside a database makes backups, replicas and index maintenance slow and expensive. Every read of a 500 KB paste pulls it through the database's buffer pool and evicts hot metadata. A database is priced for small, queryable rows, not for blobs.
Approach B: metadata in the database, body in object storage
The row holds a blob_ref and the body goes to an object store such as S3 (the object store question covers how one is built).
Good: each system does what it is good at. Object storage is cheap per terabyte, durable and effectively unlimited. The database stays at 365 GB, comfortably on one primary with replicas.
Bad: two systems that must agree. You need the write ordering above, an orphan cleanup job, and a second network hop on every read.
Approach C: inline small pastes, spill large ones
Store bodies under about 4 KB in the row and larger ones in object storage.
Good: the common tiny paste costs one read instead of two.
Bad: two code paths forever, and the threshold is a guess. If your average is 10 KB, most pastes spill anyway.
The recommended answer is B. Say why in one sentence: bodies are big, immutable and fetched whole, which is the exact profile object storage is built for, while the metadata is small and queried. Then mention C as an optimization you would only add if measurements showed the second hop mattered.
Keys, privacy and expiry
The second decision is how to name pastes and when to remove them. The two are linked, because an unlisted paste is protected only by its key.
Keys. The URL shortener needs short keys and uses ranges plus a scramble. Pastebin has a different pressure: keys can be longer, and unguessability matters more than shortness. Generate eight random base62 characters from a cryptographically secure source and insert with a conditional write (INSERT ... ON CONFLICT DO NOTHING). With the space only 0.0008% full, a collision is rare enough that a single retry handles it. A random key also means a stranger guessing links hits a real paste with probability under one in a hundred thousand per try, and rate limiting makes even that slow.
Expiry has two layers. Never rely on a sweeper alone, because a sweeper runs every few minutes and a ten-minute paste must not live for twenty.
- Lazy check on read: compare
expires_atto the clock and return 410 if it has passed. This is exact. - Background sweep: a job deletes expired metadata rows in batches using an index on
expires_at, then deletes the matching blobs. This reclaims space and can lag safely, because the lazy check already hides the paste. - Bucket lifecycle rules can remove old blobs in whole-day steps, which is a good backstop for pastes that expire in days or months, but too coarse for minutes.
Deletion and caches. Because pastes are immutable and cached for a long time, an owner's delete or an abuse takedown must purge the CDN copy. Short-expiry pastes should get a short max-age equal to their remaining life, so a cache never serves one past its time.
Bottlenecks and failures
Hot pastes. A paste linked from a popular forum thread can take thousands of reads a second. Because it is immutable, the CDN absorbs it completely. The origin sees one request per edge location, not one per reader.
Metadata database. The lookup is always by key, so the table partitions cleanly by key if 365 GB ever becomes too much. Reads fall on replicas. The recent-pastes page is a different query, a sort by time, so serve it from a small cache refreshed every few seconds rather than querying the big table.
Abuse. Pastebin-style sites are used to share leaked passwords, malware and spam, so say this unprompted. Rate limit creation per IP and per account (rate limiting covers the mechanisms), scan new pastes for known credential and malware patterns, and keep a takedown path that deletes both the row and the CDN copy.
What if object storage is down? Reads of cached pastes keep working from the CDN. Uncached reads fail with a clear error and writes should be rejected rather than half-saved. Do not fall back to writing bodies into the database: you would create the 18 TB problem during an outage.
Trade-offs to name aloud
- Two stores over one: you accept a consistency chore (write order, orphan cleanup) in exchange for cheap, unbounded body storage.
- Immutable pastes: no edit feature, in exchange for caching that makes reads almost free.
- Random keys over counters: an existence check on write, in exchange for unguessable links.
- Lazy plus swept expiry: a little wasted storage for a few minutes, in exchange for exact visibility rules.
What interviewers listen for
- A working answer: an API, a key per paste, text stored somewhere retrievable by key, and an expiry field checked on read.
- A strong answer: separates metadata from bodies and justifies it with the 18 TB versus 365 GB numbers, uses the immutability of pastes to justify a CDN, and explains lazy plus background expiry.
- A standout answer: also thinks through privacy (random keys, rate limits on guessing), purge-on-delete for cached copies, the orphan-blob failure window between the two writes and the abuse of a text-sharing service.
Check your understanding
Common mistakes
Putting bodies in the database because it is simpler. It is simpler for a week and then it is the main cost and the main scaling problem. Do the size arithmetic before choosing.
Treating this as the URL shortener. The key service is the same idea, but the payload is a thousand times bigger. Candidates who spend the whole hour on key generation never discuss storage.
Ignoring the two-store consistency window. If you write the metadata first and the blob upload fails, readers get a row that points at nothing. Write the blob first, then the row, and clean orphans later.
Relying on a sweeper for expiry. It is a cleanup tool, not a correctness mechanism. The read path must enforce expiry itself.
Skipping abuse. A public text-sharing site attracts leaked secrets and malware quickly. Mention scanning, rate limits and takedown without being asked.
Practice
The product team adds 'burn after reading': a paste that is deleted the first time anyone opens it. What changes in your design?
Write your own answer first, on paper or in a note. Then compare.
Show a hint
Immutability and caching were doing a lot of work. Which of those assumptions does a one-time paste break?
Show a strong answer
It cannot be cached. The CDN would serve the second reader from its copy, so burn-after-reading pastes must be sent with Cache-Control: no-store and must skip the CDN entirely.
The first read must be an atomic claim. Two people opening the link in the same instant must not both succeed. Make the read a conditional update on the metadata row (UPDATE ... SET consumed = true WHERE key = ? AND consumed = false) and only the caller whose update changed a row gets the body.
Delete after serving, but tolerate failure. Return the body, mark the row consumed and queue the blob for deletion. If the response is lost in transit, the reader cannot retry, so show a confirmation page first ("this paste self-destructs, view it?") and claim only when they click.
The pattern worth keeping: a feature that breaks an invariant (immutable, cacheable) should be isolated onto its own path, not threaded through the common one.
Traffic doubles every month. At 10× today's volume, which part of the design reaches its limit first, and what do you do?
Write your own answer first, on paper or in a note. Then compare.
Show a hint
Compute the metadata size and the request rates at 10×, and compare them with what one Postgres primary and the object store handle.
Show a strong answer
The request rate is still small. Ten times the load is about 120 writes and 580 reads per second, which a few API instances and the CDN handle without strain.
The metadata table is the first real limit. Ten times the pastes is about 3.65 TB of metadata over five years. One primary struggles with that table's index maintenance and backups. Partition by key (hash of the key to a shard), which is easy because every lookup is by key.
The recent-pastes query does not partition. A global sort by time across shards is expensive, so build the recent page from a separate small store or cache that each write also updates, trimmed to the latest few thousand entries.
The blob store needs nothing. Object storage scales on its own. Spread keys with a hashed prefix so one prefix does not become a hot spot.
The pattern worth keeping: scale the thing the arithmetic shows is growing fastest, and notice which queries stop working once you shard.
Key takeaways
- Do the size arithmetic first: 12 writes per second is trivial, 18 TB of bodies is the design driver.
- Split metadata from bodies: a small queryable store plus cheap object storage for immutable blobs.
- Immutability is a gift: it makes pastes cacheable by a CDN for almost their whole lifetime.
- Enforce expiry on read: use the sweeper and lifecycle rules only to reclaim space.
- Random, secure keys are the only access control for unlisted pastes, so make them unguessable and rate limit guessing.
- Plan for abuse and purges: scanning, rate limits and a delete path that reaches the CDN.
Further reading
- R. Fielding, M. Nottingham and J. Reschke, RFC 9111 "HTTP Caching" (2022): the rules behind
Cache-Control,max-ageand immutable responses. - Amazon Web Services, Amazon S3 User Guide, "Managing your storage lifecycle": how lifecycle expiration rules work and their granularity.
- Flickr engineering blog, "Ticket Servers: Distributed Unique Primary Keys on the Cheap" (2010): an alternative way to hand out unique identifiers.