Course contents

17. Real-World System Design Lesson 2 of 20

Pastebin

Design a Pastebin end to end: estimates, metadata DB plus object storage, a CDN for immutable bodies, expiry, size limits, abuse and an origin outage.

20 minAdvanced12 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Bodies are most of the bytes and never change: store them in object storage, keep a small metadata row in a database.
  • Write the body first and the metadata second, so a crash leaves an orphan, never a dangling link.
  • Immutable content is ideal for a CDN; cap max-age at the remaining lifetime so expiry still holds.
  • Expiry is a read-path check; deletion of rows and objects can be lazy.
  • Reject oversized input at the gateway and rate-limit creates per client.
  • A CDN limits an origin outage to the cache-miss traffic.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A paste service lets anyone store a block of text and share it by link: POST some text, get back /p/9fK2xQ, and anyone with the link can read it until it expires. It looks like a toy, but it is a compact version of a common shape: write-once content, read many times, sometimes by a huge crowd at once. The same design carries over to file sharing, gists, build logs and image hosting.

This lesson builds the design step by step in the 3D scene. The read path and the abuse and failure scenarios run in the simulation; the create, expiry and upload sequences are scripted illustrations.

Why it exists

Requirements shape the design, so pin them down first:

  • Functional: create a paste (text, up to 512 KB in this design), read it by id, optional expiry from 10 minutes to "never" (default 30 days), optional owner account; pastes are immutable.
  • Non-functional: reads should feel instant worldwide; links must not be guessable; a viral paste must not take the service down; expired pastes must not be readable.

Illustrative estimates (not measurements of any real service):

Quantity Arithmetic Result
Creates 5M per day ÷ 86,400 s ≈ 60 /s average
Reads 10 reads per create ≈ 600 /s average, several times that at peak
Body bytes 5M × 10 KB average ≈ 50 GB/day, ≈ 18 TB/year before replication
Metadata 5M × ~200 B ≈ 1 GB/day

Two facts fall out: reads dominate requests, and immutable bodies dominate bytes (about 98%). Both point away from "one database holds everything".

How it works

Data split. A metadata row per paste (id, owner_id, size, content_type, created_at, expires_at, object_key, status) lives in a database keyed by id; a key-value or relational store both work at this size. The body lives in object storage under its id. Object storage is cheap per GB, durable through provider-side replication, and serves large immutable objects well; it is a poor fit for queries or small frequent updates, which is what the metadata database is for.

Ids. Random ids of 8 or more base62 characters (62^8 ≈ 2.2 × 10^14) make guessing impractical at this scale; generate them from a cryptographically secure RNG and insert conditionally so a collision is retried. A counter would let anyone enumerate every paste.

Create path. The gateway checks the size, the API generates an id, writes the body to object storage first, then inserts the metadata row, then returns 201. There is no transaction across the two stores, so the order decides the failure: body-first can leave an orphaned object (garbage, cleaned up later); metadata-first can publish a link with no body.

Read path. Readers hit a CDN. On a miss the CDN calls the API, which reads the metadata row (exists? expired? taken down?) and then fetches the body. The response carries Cache-Control: public, max-age=N with N capped at the time left until expires_at, so the edge never serves past expiry.

Expiry. Enforced on read by the metadata check. Cleanup is lazy: a sweeper deletes expired rows in batches using an index on expires_at, then bodies are deleted, either by the sweeper or by an object-storage lifecycle rule (expiry is known at creation, so objects can be tagged or prefixed by expiry date).

Limits and abuse. The gateway rejects bodies over the cap with 413 before reading them (and stops reading once the cap is passed, in case Content-Length lies). Creates are rate-limited per API key, account and IP with a token bucket. If large uploads are ever allowed, the API hands out a short-lived presigned URL and the client uploads straight to object storage.

When to use it

This shape (metadata store + object storage + CDN) fits any write-once, read-many content: pastes, gists, attachments, images, build artifacts, exported reports. The case study is also a standard interview warm-up, close to the URL shortener but with real payloads.

When not to

  • If content is edited collaboratively and often, immutable objects behind a long-lived CDN cache are the wrong model; you need versioning or a database designed for updates.
  • For tiny values (a URL, a counter), object storage adds a hop for nothing; keep the value in the key-value store, as the URL shortener does.
  • For private, per-user content a shared CDN cache is risky; use signed URLs with short lifetimes or skip the CDN for those reads.

Trade-offs

Choice You gain You pay
Bodies in object storage Cheap durable bytes, small fast database Two stores, orphans to clean up, one extra hop on misses
Long CDN max-age High hit ratio, tiny origin load Slower takedowns and deletes (purge needed)
Random ids Unguessable links No natural ordering; collisions must be retried
Expiry checked on read Correct even if cleanup lags A metadata read on every origin request
Presigned direct uploads API never handles big bytes Validation and scanning must happen after upload

Alternatives

  • Bodies inline in the database for a small service: simplest, fine until size, backup time or read load hurt (the lesson shows that point).
  • A key-value store with large values (several hundred KB): workable, but storage cost per GB is usually far higher than object storage.
  • Content-addressed storage (key = hash of the body): deduplicates identical pastes for free, but the hash leaks whether a known text exists, and deletion needs reference counting.
  • Serverless edge functions with object storage only (metadata in object tags or an edge KV store): very little to run, at the cost of weaker queries over metadata.

Failure modes

  • Viral paste without a CDN: every read goes to the origin, object storage fetches queue and requests fail.
  • Abuse on the write path: spam creates saturate storage writes and hurt reads that share the same backend.
  • Object storage outage: with a CDN, only cache misses fail; without one, everything fails. stale-if-error and cross-region replication reduce it further.
  • Metadata database outage: misses fail; CDN hits continue. Read replicas help the read path.
  • Orphans: crashes between body and metadata writes leave unreferenced objects; a periodic reconciliation (list objects older than a day with no metadata row) removes them.
  • Takedown lag: a malicious paste stays cached at the edge until purged; purge on takedown and keep anonymous max-age short.

In production

Scan new pastes for malware links and leaked secrets (API keys, tokens) asynchronously, and flag or block them; offer a report button and a takedown path that flips status and purges the CDN. Serve pastes from a separate domain from your main site so user content cannot read your cookies, and send Content-Type: text/plain with X-Content-Type-Options: nosniff so browsers never execute pasted HTML. Watch the CDN hit ratio, origin request rate, object-storage error rate, and creates per client.

Common misconceptions

  • "Object storage is just a slow database." It is a different tool: durable, cheap, immutable blobs addressed by key, with no queries or transactions.
  • "Deleting the row is enough for expiry." Only if the read path checks it and edge caches cannot outlive it.
  • "A CDN is only for speed." Here it is also capacity (origin load drops tenfold) and availability (hits survive origin outages).
  • "A size limit is a UI concern." It must be enforced at the gateway before the body is read, or one client can tie up your workers with huge uploads.

Interview angle

Lead with estimates that separate bytes from requests, then justify the metadata/object-storage split. Expect follow-ups on id generation, write ordering across two stores, how expiry interacts with caching, how you would handle a viral paste, and how you would stop abuse. Naming what fails and what keeps working during an object-storage outage ("CDN hits continue; misses and creates fail") shows you think in failure domains. The URL shortener interview is a good companion exercise.

Model assumptions

The simulation is a simplified, scaled-down model, not a benchmark; one simulated request stands for many real ones. Version 1 keeps bodies in one database with 8 connections and 35 ms per read. The split design has a metadata database (16 connections, 3 ms reads, 8 ms writes) and object storage modelled as a store with 24 concurrent fetches, 30 ms per GET and 60 ms per PUT (about 800 GETs per second; an illustrative budget, not a provider limit). Readers ask for 10,000 pastes with Zipf(1.3) popularity. The CDN's edge cache is an LRU of 1,000 bodies that stores every answer from the origin, so its hit ratio emerges from the skew (about 90%); the challenge's 60-second max-age is a short TTL that brings it down to about half. A failed or restarted edge cache comes back empty. Misses take a 30 ms hop to the origin. The Paste API has 64 workers and 4 ms of own work. Simulated requests (including the bot's creates) visit the metadata database before object storage; the body-first write order, the expiry sweeper, the 413 rejection and the presigned upload are scripted illustrations. The token bucket in the abuse step stands for the bot's per-key bucket. stale-if-error and cross-region replication are described, not modelled. Arrivals are Poisson, service times lognormal.

The lesson as textEvery step of the simulation, written out.
  1. 1. Requirements: paste text, share a link, read it

    A user pastes text, up to 512 KB, and gets a short link such as /p/9fK2xQ. Anyone with the link can read it until it expires (10 minutes to "never", default 30 days). No editing: a paste is immutable once created.

    The first version is the obvious one: one API and one database that stores everything, body included. At today’s 80 reads per second (scaled down in the simulation) it works fine.

    Scene: Readers call the Paste API, which reads each paste, body included, from a single database. Traffic is low and every request succeeds.

    Key idea: Start from the requirements that shape the design: immutable content, a size cap, expiry, and far more reads than writes.

  2. 2. Back-of-the-envelope: bodies dominate

    Illustrative numbers: 5 million new pastes a day (about 60 per second) and 10 reads per write (about 600 per second on average, several times that at peak).

    Storage is where it gets interesting. A median paste is a few KB, but the average is pulled up by large logs to roughly 10 KB: 5M × 10 KB = 50 GB of bodies a day, about 18 TB a year before replication. The metadata row (id, owner, size, created, expires, a pointer) is about 200 bytes: 1 GB a day. Bodies are 98% of the bytes and never change.

    In the simulation traffic doubles to 150 reads per second. The database, reading big rows, is already well over half busy.

    Scene: Traffic rises to 150 reads per second. Annotations show the estimates: 5 million pastes a day, 50 GB of bodies versus 1 GB of metadata. The database is more than half busy.

    Key idea: Estimate bytes as well as requests: here the blobs are 50× the metadata and immutable, which points to a different store.

  3. 3. Big rows make the database the bottleneck

    At 260 reads per second the single database gives up. Each read drags a large body through the buffer pool and the network, about 35 ms, so 8 connections manage only about 230 reads per second.

    Reads queue for a connection, the API’s workers sit waiting on them, its own queue fills and new requests are rejected (503). Backups, replicas and failover all get slower too, because they copy terabytes of text that never changes.

    Scene: At 260 reads per second all database connections are busy, reads wait, the API fills up and some requests are rejected.

    Key idea: Large immutable blobs in a transactional database cost connections, memory and backup time for no benefit.

  4. 4. Metadata in a database, bodies in object storage

    We split the data by shape. A small metadata database holds one ~200-byte row per paste and answers a primary-key read in about 3 ms. The bodies go to object storage, keyed by paste id: cheap per GB, replicated by the provider, built for large immutable objects.

    Each read is now two lookups: metadata first (does it exist, has it expired?), then the body. The extra hop costs a little latency, but the database is no longer the bottleneck and the failures stop at the same 260 reads per second.

    Scene: The Paste API reads a small metadata row from the Metadata DB, then fetches the body from object storage. Nothing fails at 260 reads per second.

    Key idea: Put each kind of data where its access pattern is cheap: small mutable rows in a database, large immutable bytes in object storage.

  5. 5. Creating a paste: body first, then metadata

    This step is a scripted illustration of one create; live reads are turned down to 20 per second so it stands out.

    The API generates the id (random, 8+ base62 characters, so links cannot be guessed by counting), writes the body to object storage first, and only after that acknowledgement inserts the metadata row. Then it returns 201 with the link.

    The order matters. If the API crashes between the two writes, the worst case is an orphaned object that nothing points to, which a cleanup job can delete. The reverse order could publish a link whose body does not exist.

    Scene: Scripted: a create request reaches the API, which writes the body to object storage, waits for the acknowledgement, then inserts the metadata row, and finally answers the user with the new link.

    Key idea: Across two stores there is no transaction: order the writes so a crash leaves garbage, never a dangling pointer.

  6. 6. A paste goes viral

    A leaked config file is posted on a busy forum and reads jump to 1,000 per second. Every one of them travels the full path: 30 ms each way to the origin, a metadata read and a body fetch.

    The object storage budget in this model is about 800 fetches per second. Fetches queue, the API’s workers sit waiting on them, and requests fail. We would be paying for a thousand identical GETs per second of the same immutable bytes.

    Scene: At 1,000 reads per second object storage runs out of fetch capacity; the API fills with waiting requests and some reads fail.

    Key idea: Popular immutable content read straight from the origin wastes latency, money and origin capacity.

  7. 7. Serve bodies from a CDN

    Pastes never change, so they are ideal CDN content. Readers now hit a CDN a few milliseconds away. Its edge cache keeps the 1,000 most recently read pastes, a tenth of those being read, and stores every body the origin sends back. Because a few pastes get most of the reads, it answers about 90% of them; only misses travel to the origin API.

    The origin sees about 100 reads per second instead of 1,000, the failures stop, and median latency falls to roughly the user↔edge round trip. The API sets Cache-Control: public, max-age=… capped at the paste’s remaining lifetime, so the CDN never serves a paste past its expiry.

    Scene: Readers go to a nearby CDN. About 90% of reads are answered by the edge cache; the rest go to the origin API, metadata DB and object storage. Nothing fails and median latency drops.

    Key idea: Immutable content plus a CDN turns a read-scaling problem into a cache-hit-ratio problem.

  8. 8. Expiry in three places

    Expiry has to hold everywhere a paste lives. This sequence is a scripted illustration on top of the live traffic.

    On read, the API checks expires_at in the metadata row and answers 404/410 for an expired paste, even if the body still exists. In the background, a sweeper deletes expired metadata rows in small batches (an index on expires_at keeps that cheap), purges any long-lived CDN entry, and deletes the bodies. Many teams let an object-storage lifecycle rule delete bodies instead, since expiry is known at creation time.

    Delete metadata first: from that moment the paste is gone for readers, and a body that outlives it is just garbage.

    Scene: Scripted: the expiry sweeper deletes expired metadata rows, then asks the CDN to purge them, then deletes the bodies from object storage. Live reads continue through the CDN.

    Key idea: Enforce expiry on the read path; clean up storage lazily. Correctness comes from the check, not from the sweeper being on time.

  9. 9. Size limits at the front door

    Creates now enter through a write gateway. This step is a scripted illustration.

    First, a 2 MB paste: the gateway sees Content-Length above 512 KB and answers 413 Payload Too Large before reading the body or touching storage. A client that lies about the length is cut off once 512 KB have been read.

    Second, the pattern for large uploads if you ever allow them: the gateway returns a short-lived presigned URL and the client uploads straight to object storage, so big bodies never pass through the API’s workers.

    Scene: Scripted: an oversized paste is rejected by the write gateway with 413 without reaching the API. Then a client gets a presigned URL from the gateway and uploads directly to object storage.

    Key idea: Reject oversized input at the edge, as early and as cheaply as possible; route big bytes around your servers.

  10. 10. A spam bot floods the write path

    A bot starts creating 500 pastes per second, each a body PUT plus a metadata insert. Body writes are slower than reads, so object storage runs out of capacity and the readers’ cache misses start failing too: abuse on the write path hurts the read path.

    Three seconds in, the gateway turns on a token bucket for the bot’s key: 10 creates per second, burst 20. Almost all its requests are now answered 429 at the gateway, storage recovers and the readers’ errors stop. In production you also want per-IP and per-account limits, CAPTCHAs for anonymous bursts, and content scanning for malware and leaked secrets.

    Scene: A spam bot sends 500 create requests per second through the write gateway. Object storage saturates and some reader requests fail. After three seconds the gateway rate-limits the bot, its requests are rejected with 429, and readers recover.

    Key idea: Any free write endpoint will be abused; rate-limit creates per client before they reach storage.

  11. 11. Object storage goes down

    The bot has given up. One second in, object storage becomes unreachable.

    Without the CDN every read would fail. With it, the 90% of reads served at the edge keep working; only cache misses fail, so readers see roughly a 10% error rate instead of 100%. Creates fail too, because the body cannot be stored, and the API should say so clearly rather than write metadata that points nowhere.

    Two mitigations go further: CDN stale-if-error, so edges keep serving expired copies for a while, and cross-region replication of the bucket with a fallback read path. Neither is modelled here.

    Scene: Object storage goes offline. Reads answered by the CDN edge cache still succeed; reads that miss fail at the origin. About one read in ten fails.

    Key idea: A cache in front of an origin is also an availability layer: it bounds the blast radius of an origin outage to the miss traffic.

  12. 12. The design and its trade-offs

    Object storage is back. The final design: a CDN for immutable bodies, a stateless Paste API, a small metadata database, object storage for bodies, a write gateway with size and rate limits, and an expiry check on read plus lazy cleanup.

    Trade-offs to name: CDN caching makes deletion and takedowns slower (you need purges, and short max-age for anonymous pastes); two stores mean orphans to clean up; random ids are unguessable but give no ordering. Compare the URL shortener (/system-design/interviews/url-shortener), which has the same read-heavy shape but tiny values.

    Scene: All components are healthy: readers go through the CDN, creates through the write gateway, and the Paste API uses the metadata database and object storage. Nothing fails.

    Key idea: Split by data shape, cache what never changes, enforce limits at the edge, and make expiry a read-path check.