SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
  • Design a URL Shortener
  • Design Pastebin
  • Design a Rate Limiter
  • Design a Unique ID Generator
  • Design a Key-Value Store
  • Design a Scalable Parking System (Smart Parking)
System Design/Case Studies/Easy
Interview case study

Design Pastebin

Let people paste text, get a link, and share it. Like the URL shortener, but with big content to store.

⏱ 28 min readEasy case studyBeginner23 cross-questionsHas visualizer
Prompt60-sec answer45-min plan1 Clarify2 Estimate3 API + Data4 Design5 Deep dives6 Scale7 Wrap upCross-questionsVariationsScoringMistakesCheat-sheet

StartThe prompt and what is really being tested

The interviewer says

“Design Pastebin.”

It is short on purpose. Your first job is to make it specific.

What they checkWhy it matters
Spotting the real difference from a URL shortenerThe code part is the same. The twist is big content. A strong candidate says so early and splits small hot metadata from large blobs.
Storage reasoningWhere do the bytes live, in what format, how many copies, and what does that cost? Numbers and a clear choice, not ‘put it in a database’.
Lifecycle: expiry and deletionMost pastes expire. Cleaning up billions of rows and blobs without scanning everything, and without half-deleted states, is the hard operational part.
Privacy and safety‘Unlisted’ is not ‘secret’. User text can contain scripts, passwords and illegal content. The interviewer wants to see you think about access control and abuse.
Read-path and failure thinkingA viral paste, a cache outage, a write that half-succeeds. Say what happens, and why the user does not lose data.

TL;DRThe whole design in 60 seconds

A create request stores the text in object storage and a small record (code, owner, expiry, visibility, pointer) in a metadata store. A read looks up the record, checks status, expiry and access, and returns the text. Pastes never change, so they cache extremely well.

  • Scale: 1M new pastes a day is only about 12 writes and 120 reads per second. The hard part is bytes: about 10 GB of text a day.
  • Storage split: small hot metadata in a key-value store, partitioned by code. Text, compressed, in object storage (under 3 TB on disk after 5 years, with compression and erasure coding). Blobs in the database would make backups, restores and caches painful.
  • Codes: the same as the URL shortener (ranges plus base62) for public pastes. Unlisted pastes get a long random code (128 bits) so they cannot be guessed.
  • Expiry: check expires_at on every read, sweep expired pastes in the background by time bucket, and use object-store lifecycle rules as a backstop.
  • Read path: CDN for public pastes, Redis for metadata, object storage for the text. Raw text is served from a separate domain with safe headers, so a paste can never run a script.
  • Write order: blob first, then metadata. If the second step fails, we are left with an orphan blob that a cleanup job removes. Never the reverse.
💡How to use this page
Read the 60-second answer first. Then work through steps 1 to 7 in order, and try each step yourself before reading the model answer. Finish with the cross-questions: say your answer out loud, then open the model one.

PlanA 45-minute plan

4
4
5
7
15
7
3
Minutes per step (total 45). A guide, not a rule: move time to the part the interviewer cares about.
StepMinutesWhat to get done
1. Clarify4Expiry, visibility, size limit, edit or not. Say what is out of scope.
2. Estimate4Writes and reads per second, then bytes: per day, per 5 years, metadata vs content.
3. API and data5Create, read, raw, delete. The metadata record with a pointer to the blob.
4. High-level design7Metadata store, object store, cache, CDN. One write path, one read path.
5. Deep dives15Where content lives, unguessable links and access, expiry at scale, safe fast reads.
6. Scale and failures7Half-failed writes, viral paste, cache down, abuse, monitoring.
7. Wrap up3Recap, trade-offs, what you would do next.

Step 1Clarify requirementsabout 4 min

🤔
Pause. Try it yourself first
You know the URL shortener. List what is different here. Hint: what is stored, how big it is, who may read it, and what happens to it over time.

Questions to ask, and why

AskWhy you ask itTypical answerHow it changes the design
What do users store: text only, or also files and images?Files change the problem (virus scanning, previews, much bigger sizes).Text and code only. A maximum of 10 MB per paste.Text compresses well and can be served as text. A hard size limit protects the system.
Do pastes expire? What choices do users get?Expiry drives storage size and a whole cleanup subsystem.Yes: 10 minutes, 1 day, 1 week, or never. Default 1 day for anonymous users.A fixed set of expiry classes. Most data is short-lived, so cleanup is a core job, not an extra.
Who can see a paste: public, unlisted, private?Decides access checks, caching rules and how long the code must be.Public (anyone, may be listed), unlisted (anyone with the link), private (owner only, needs login).Public can use the CDN. Unlisted needs an unguessable link. Private needs an auth check on every read and no shared caching.
Can people edit a paste after creating it?Edits break caching and need versions.No. A paste is immutable. To change it, make a new one.Immutable content can be cached for a long time and is easy to replicate. Say this out loud, it simplifies a lot.
Can users pick a custom name, and do we need accounts?Aliases need a uniqueness check. Accounts decide limits and ownership.Optional custom alias for signed-in users. Anonymous creation is allowed with tight limits.Conditional insert on the alias (as in the URL shortener). Owner field and per-user limits.
How many pastes a day, how big, and how many reads per paste?The numbers decide whether the content or the request rate is the hard part.1 million new pastes a day, average 10 KB, about 10 reads per paste.Tiny request rate, but about 10 GB of text a day. Storage is the main design question.
How durable must a paste be?Losing a paste is losing user data.Very durable. Availability of reads is important, but never losing data matters more.Replicated metadata, erasure-coded blobs, and write order that cannot lose data silently.
Do we need syntax highlighting, search, or view counts?Each adds services or write load.Highlighting in the browser. Basic view counts, a little late is fine. No full-text search.Highlighting costs the server nothing. Views go through a queue, not a counter on the paste row.
How long do we keep a paste that never expires?Unbounded growth.Forever, but we may move old data to cheaper storage.Plan storage tiers and a growth budget. Content must be cheap per GB.
What about abuse and takedowns (spam, malware, leaked passwords, illegal content)?Public paste sites are heavily abused, and the law may require removal.Yes. Report button, automated scanning, and fast removal.An async scanning pipeline, a block status, and a way to purge caches and the CDN quickly.

Write the scope on the board

Functional (must do)
  • •Create a paste with text, optional title and language
  • •Choose expiry: 10 minutes, 1 day, 1 week or never
  • •Choose visibility: public, unlisted or private
  • •View a paste by URL, and fetch it as raw text
  • •Owners can delete their pastes and list their own
  • •Optional custom alias and basic view counts
Non-functional (how well)
  • •Durable: a saved paste is never lost before it expires
  • •Reads: 99.9% available, under 200 ms for the first byte
  • •Read-heavy: about 10 reads per new paste
  • •Size limit: 10 MB per paste, enforced early
  • •Scale: 1M new pastes a day, kept up to 5 years
  • •Safe: pasted text must never be able to run code in a visitor's browser
Out of scope (say it)
  • •Editing and version history
  • •File and image uploads
  • •Full-text search across all pastes
  • •Real-time collaboration
🎤
Say it out loud
“Let me confirm the scope. Users paste text up to 10 megabytes, choose an expiry of 10 minutes, 1 day, 1 week or never, and choose public, unlisted or private. Pastes are immutable, so there is no editing. I will design for about a million new pastes a day, averaging 10 kilobytes, with about 10 reads per paste, and I will put durability ahead of everything else, because a lost paste is lost user data. I will leave search, file uploads and collaboration out. Does that match?”

Step 2Estimate the scaleabout 4 min

🤔
Pause. Try it yourself first
Do the request rates first (they will be small), then the bytes. Compare content size with metadata size. Which one drives the design?

Assumptions (say them first)

AssumptionValue
New pastes per day1 million
Average paste size10 KB of text
Read to write ratio10 : 1
Peak traffic vs average3 times the average
Expiry mix of new pastes40% one day, 30% one week, 30% never
Metadata per paste (code, owner, dates, pointer)about 300 bytes
Text compression (gzip or zstd)about 3 times smaller
Retention5 years for pastes that never expire
Cache hit rate we aim for90% or better
One app server can handleabout 1,000 requests per second

The arithmetic, line by line

WhatMathsResult
New pastes per second (average)1,000,000 ÷ 86,400 sabout 12 per second
New pastes per second (peak)12 × 3about 35 per second
Reads per second (average)12 × 10about 120 per second
Reads per second (peak)120 × 3about 350 per second
Text added per day1,000,000 × 10 KB10 GB per day
Text per year if we kept everything10 GB × 3653.65 TB per year
Pastes that never expire, after 5 years30% × 1M × 365 × 5about 550 million
Their text, before compression550M × 10 KBabout 5.5 TB (short-lived pastes add only about 25 GB alive at any moment)
After 3 times compression5.5 TB ÷ 3about 1.8 TB
On disk with durability1.8 TB × 1.5 (erasure coding), or × 3 (three full copies)about 2.7 TB, or 5.5 TB
Metadata after 5 years550M × 300 bytesabout 165 GB (about 490 GB with 3 copies)
Content to metadata ratio5.5 TB ÷ 165 GBabout 33 to 1 before compression
Hot cache (80/20 of a day of reads)0.2 × (1M × 10 reads) × 10 KBabout 20 GB
Reads that reach the origin (90% hits)120 × 10%, then 350 × 10%about 12 per second, 35 at peak
Bandwidth at peak350 × 10 KB3.5 MB per second, about 28 Mbit/s
Pastes that expire per day(40% + 30%) × 1M700,000 per day, about 8 per second (7 GB of text)
What the numbers tell us about the design
  • •12 writes and 120 reads per second is tiny. Request rate is not the problem. Bytes are.
  • •The text is about 33 times bigger than the metadata, and it is the part nobody queries by field. That is the case for splitting them.
  • •165 GB of metadata is easy to keep in a fast store and fits the hot part in memory. 1.8 TB of compressed text is cheap in object storage but heavy as database rows.
  • •Most pastes are short-lived: 70% expire within a week. Cleanup of about 700,000 pastes a day is a first-class job.
  • •Erasure coding stores the same data in about half the space of three full copies, with equal or better durability. This is why object storage is the right home for blobs.
🎤
Say it out loud
“Let me do the maths. A million pastes a day is about 12 writes a second, 35 at peak, and with 10 reads per paste about 120 reads a second, 350 at peak. That is tiny. The numbers that matter are bytes: 10 gigabytes of text a day, and after 5 years about 550 million pastes that never expire, which is about 5.5 terabytes raw, or under 2 terabytes after compression. The metadata is only about 165 gigabytes. So the content is over 30 times bigger than the metadata. That tells me to keep the small hot records in a fast store and put the text in object storage.”

Step 3Define the API and the data modelabout 5 min

🤔
Pause. Try it yourself first
Write the endpoints: create, view, raw, delete. Then the record. What does the record store about the text, instead of the text itself?

Endpoints

MethodPathRequestResponseNotes
POST/v1/pastes{ content, title?, language?, expiresIn?, visibility?, customAlias? }201 { code, url, rawUrl, expiresAt }Limit body to 1 MB here, bigger pastes (up to 10 MB) use a signed upload. 413 if too large, 429 over the limit, 409 alias taken. Idempotency-Key header so a retry does not make a second paste.
GET/{code}none200 HTML page with the text, escapedPublic and unlisted. 404 unknown, 410 expired or removed. Cache-Control: public for public pastes, private for private ones.
GET/raw/{code}none200 text/plain; charset=utf-8Served from a separate domain. X-Content-Type-Options: nosniff. Supports Range requests for large pastes.
GET/v1/users/me/pastes?cursor=none200 { items, nextCursor }Owner only. Newest first, keyset pagination by (created_at, code).
DELETE/v1/pastes/{code}none204Owner only. Soft delete, then a background job removes the blob. Purges cache and CDN.

Data model

Field (pastes table)TypeNotes
code (key)stringShort random code for public, long random code for unlisted. Partition key. Unique.
owner_idid, optionalNull for anonymous pastes.
title, languageshort stringsLanguage is a hint for highlighting.
visibilitypublic | unlisted | privateDecides caching and access checks.
created_at, expires_attimestampsexpires_at null means never. Also stored as an expiry bucket (the hour).
size_bytes, sha256number, hexSize for limits and bandwidth. Hash to detect corruption (and for dedup, if used).
content_keystringWhere the text is in object storage. For tiny pastes this can be inline_text instead.
statusactive | deleted | expired | blockedLets us hide a paste at once, before data is physically deleted.
Other storesHoldsKey
Object storageThe compressed text, one object per pasteblobs/{code} (or the content hash)
owner_pastes (secondary index)A user's pastes, newest firstowner_id, then created_at
expiry_indexWhich pastes expire in which hourbucket (hour), then code
view events (queue, then aggregates)One event per viewcode, time
code ranges (small counter store)The next unused range of the counterone row, as in the URL shortener
One metadata record (example)
code         : "k3Fz9aQ"
owner_id     : 48213
title        : "nginx config"
language     : "nginx"
visibility   : "public"
created_at   : 2026-03-02T09:14:00Z
expires_at   : 2026-03-03T09:14:00Z   (bucket: 2026-03-03T09)
size_bytes   : 8421
sha256       : "9f2c...e1"
content_key  : "blobs/k3Fz9aQ"
status       : "active"
📝Which store, and why
Metadata is tiny and always read by one key, so a key-value store partitioned by code fits (or a relational database with a unique index, sharded). The text is large, immutable and read whole, which is exactly what object storage is built for: cheap, durable, and it scales without effort. The record holds a pointer to the blob. Very small pastes can be stored inline in the record as an optimisation, but that is a tuning choice, not the first thing to say.
🎤
Say it out loud
“Five endpoints: create, view, raw, list mine, delete. The key point is the record. It does not hold the text. It holds the code, owner, visibility, expiry, size, a hash, and a pointer to where the text lives in object storage. Metadata goes in a key-value store partitioned by code. The text goes in object storage, compressed.”

Step 4Draw the high-level designabout 7 min

🤔
Pause. Try it yourself first
Draw it. Which parts are on the read path? Where does the text live? What runs in the background?
Pastebin: high-level design
👤Clientbrowser or API
→↓HTTPS
🌍CDNpublic pastes
→↓
⚖️Load balancerhealth checks
→↓
Stateless app servers (3 zones)
✍️Paste servicecreate, view, delete
📄Raw serviceseparate domain
Small and hot
⚡Redismetadata cache
↓miss
🗄️Metadata storekey-value, sharded by code
Big and cheap
🪣Object storagecompressed text, erasure coded
one object per paste
Background
🧹Expiry sweeperby hour bucket
🔍Scannerspam, malware, secrets
📨Queueviews, events
Solid path = read (hot). The text comes from object storage or the CDN. Cleanup and scanning run in the background.
ComponentWhat it does
CDNCaches public pastes close to users. Pastes never change, so the cache is simple. Not used for private pastes.
Paste serviceValidates, compresses, writes the blob and the record, applies limits, enforces visibility.
Raw serviceServes the plain text from a separate domain with safe headers, so pasted content cannot touch the main site's cookies.
RedisCaches metadata (and small or hot pastes). Cache-aside with a TTL never longer than the paste's life.
Metadata storeSource of truth for the records. Partitioned by hash of code, three copies in different zones.
Object storageHolds the compressed text. Very durable, cheap per GB, scales without work.
Expiry sweeperFinds pastes whose time has come using the hour bucket index, hides them, deletes the text, then the record.
Scanner and queueAfter a create, checks the text asynchronously for spam, malware and leaked secrets, and counts views off the hot path.
Write path (follow one request)
  1. Client sends POST /v1/pastes. The server checks the API key or applies the anonymous limit, rejects bodies over the size limit, and checks the language and expiry values.
  2. It picks a code: from its range (public, same as the URL shortener) or 128 random bits (unlisted and private).
  3. It compresses the text and uploads it to object storage as blobs/{code}, with a checksum.
  4. Only after the upload succeeds, it writes the metadata record with a conditional write (insert only if the code is free).
  5. It puts an event on the queue for scanning and returns 201 with the URL.
  6. If step 4 fails, the blob is an orphan. A cleanup job removes blobs with no record after a day.
Read path (follow one request)
  1. Browser opens the paste URL. A public paste may be served straight from the CDN.
  2. On a CDN miss, the request reaches an app server, which reads the metadata from Redis, then from the metadata store on a miss.
  3. It checks status and expiry (410 if gone, 404 if unknown) and the access rule (private needs the owner's login).
  4. It gets the text: from the cache, or from object storage (a nearby read).
  5. It returns the page. The text is escaped (never trusted as HTML). The raw URL is served from a separate domain as text/plain.
  6. It sends a view event to the queue without waiting.
🎤
Say it out loud
“Here is the picture. Metadata in a key-value store, partitioned by code, with Redis in front. The text in object storage, compressed. A CDN in front for public pastes. A create uploads the blob first, then writes the record, so we can never have a record that points to nothing. A read checks the record, then fetches the text. In the background, a sweeper removes expired pastes by hour bucket, and a scanner checks content for abuse.”

Step 5Deep dive into the hard partsabout 15 min

🧠The pattern for every deep dive
Problem → options → pick one → say why → say what it costs. Interviewers score the reasoning more than the choice.
5.1

Where the text lives

The problem: Each paste is up to 10 MB of text. Over 5 years that is terabytes. We need it durable, cheap, fast to read, and not in the way of the small, hot records.

OptionHow it worksGoodBad
Text inside the database rowA TEXT or BLOB column in the pastes table.One place, one transaction, simplest code.The database grows to terabytes. Backups, restores and new replicas move all of it. Big rows push hot metadata out of memory. Costs the most per GB.
Text on local disk or a shared file systemWrite files to a disk or network file system, keep the path in the record.Cheap and simple at first.You must build replication, durability and growth yourself. A disk failure is data loss.
Text in object storage, pointer in the recordUpload the compressed text as an object. Store only the key in the metadata record.Built for large, immutable blobs. Very durable (erasure coding). Cheap per GB. Scales without work.Two systems to write to, so the order and failure cases need care. An extra hop on a read.
Hybrid: small inline, large in object storageUnder a few KB, keep the text in the record. Above that, use object storage.Saves a round trip for the many tiny pastes.Two code paths and a threshold to tune. Only worth it once measurements say so.
Pick
Metadata in the key-value store, compressed text in object storage

The two kinds of data behave differently. The metadata is small, read by key, and hot. The text is large, written once, and read whole. Putting them in one store makes both worse. After 5 years the metadata is about 165 GB and the compressed text about 1.8 TB (about 2.7 TB on disk with erasure coding).

The cost of the split is a write that touches two systems. We handle that by writing the blob first, then the record. A failure after the blob leaves an orphan blob, which is harmless and cleaned up later. The other order could leave a record that points to nothing, and a user who sees ‘paste not found’ for data they just saved.

FailureWhat the user seesHow we fix it
Blob upload failsThe create returns an error. Nothing was saved.Client retries with the same Idempotency-Key. Same code, same blob key, safe to repeat.
Blob saved, record write failsThe create returns an error. An orphan blob exists.A reconciliation job lists blobs older than a day with no record, and deletes them.
Record saved, blob missing (should never happen)A 500 on view.Prevented by the write order. Monitor and alert on any such read. Checksums catch corruption.
Delete: record removed, blob remainsNothing: the paste is gone.Delete is two steps (hide the record, then delete the blob), and the job is safe to repeat.
Create, in the right order (sketch)
code = nextCode(visibility)                 // range or 128-bit random
raw  = zstd.compress(text)
store.put("blobs/" + code, raw, { sha256 })     // 1. blob first (idempotent: same key)
ok   = meta.putIfAbsent(code, { ..., content_key, status: "active" }) // 2. then the record
if (!ok) return 409                          // only a custom alias can clash
queue.send({ type: "scan", code })           // 3. async, off the request path
return 201
📝Compression and de-duplication
Text compresses about 3 times, so compress before storing. It is worth it. Content de-duplication (use the SHA-256 of the text as the blob key) can store identical pastes once, but it needs a reference count to delete safely, it breaks per-paste encryption, and it leaks whether some text already exists. For a first design, skip it, and say why.
🎤
Say it out loud
“I will split the data by how it behaves. The record is small and hot, so it goes in a key-value store partitioned by code. The text is big, immutable and read whole, so it goes in object storage, compressed. After five years that is about 165 gigabytes of metadata and under 2 terabytes of text. The cost is a write to two systems. I write the blob first and the record second, so a failure leaves an orphan blob that a cleanup job removes, never a record pointing to nothing.”
5.2

Links that cannot be guessed, and access control

The problem: An unlisted paste is protected only by its link. A private paste must be readable by its owner only. If an attacker can guess codes, ‘unlisted’ means ‘public’.

OptionHow it worksGoodBad
Short sequential code (like the URL shortener)Counter ranges, scrambled, base62, 7 characters.Short, easy to type and share.Easy to enumerate or guess: with 550 million live pastes in 3.5 trillion codes, a guess hits about 1 in 6,400.
Longer random code8 to 10 random base62 characters.Still short. Harder to guess.At 8 characters one guess in about 400,000 still hits a live paste. At 1,000 guesses a second that is a hit every 7 minutes. Rate limits help but do not solve it.
128-bit random code16 random bytes from a secure random source, written in base62 or base64url (22 characters).Cannot be guessed or enumerated. No coordination needed. Collisions are impossible in practice.Long URL. Not typeable. Fine for pastes people send as links.
Short code plus a secret keyShort public code, and a separate random key in the URL fragment (after #) or a signed link.Can be combined with end-to-end encryption. The server never sees the key.More complex. The server cannot scan the content. Losing the key loses the paste.
Pick
Short codes for public pastes, 128-bit random codes for unlisted, login for private

Public pastes are meant to be found, so a short code from the same range scheme as the URL shortener is fine. Unlisted pastes depend on secrecy of the link, so the code must have enough random bits that guessing is hopeless: 22 base62 characters carry about 131 bits, while there are only about 2^29 live pastes. A guess lands on a real paste about once in 6 × 10^29 tries.

Private pastes do not rely on the link at all. Every read checks the login and the owner. Their responses are marked Cache-Control: private, no-store, they never go into the shared CDN cache, and the blob is fetched with a short-lived signed URL (or streamed through the app server), so a leaked link stops working in a minute.

VisibilityCodeWho may readCaching
Public7 to 8 characters (ranges, as in the URL shortener)Anyone. May appear in a public ‘recent’ list.CDN and Redis. Long TTL up to the expiry.
Unlisted128-bit random (22 characters)Anyone who has the link. Not listed, and marked noindex.CDN is fine because the URL is secret. TTL up to the expiry.
PrivateAny codeOwner only (login checked on every read)No shared cache. Short-lived signed URL for the blob.
⚠️Unlisted is not secret
Anyone with the link can read it, and links get pasted into chats, logs and browser history. Say that unlisted is for convenience, and that anything truly sensitive should be private (or encrypted before it is sent). Also add X-Robots-Tag: noindex so search engines skip it.
💡Do not re-teach code generation
For the public short codes, say in one sentence: ‘same as the URL shortener: a counter handed out in ranges, scrambled, written in base62’. Spend your time on the new part.
🎤
Say it out loud
“Public pastes use the short ranged codes from the URL shortener. For unlisted pastes the link is the only protection, so I use 128 random bits from a secure source, 22 characters, which cannot be guessed or enumerated. Private pastes do not rely on the link at all: every read checks the login and the owner, the response is never cached publicly, and the blob is fetched with a short-lived signed URL. And I would say plainly that unlisted is not secret.”
5.3

Expiry and cleanup at scale

The problem: 70% of pastes expire. That is about 700,000 deletions a day, against hundreds of millions of rows over the years. We must stop serving expired pastes on time, free the space, and never leave half-deleted data.

OptionHow it worksGoodBad
Check expires_at on every readIf the time has passed, answer 410 and do not return the text.Exact. Always on time. No background work needed for correctness.Does nothing for pastes nobody reads. Space is not freed.
Scan the whole table for expired rowsA nightly job runs a query on expires_at over all rows.Simple to write.A full scan of hundreds of millions of rows. Slow, heavy, and it competes with real traffic.
Expiry index by time bucketA second table keyed by hour: expiry_index(bucket, code). The sweeper reads one bucket at a time.Reads only what is due. Easy to pace and to resume. Easy to split across workers.A second write on create. The index must stay in step with the record.
Object-store lifecycle rulesTag each blob with its expiry class (1 day, 7 days) and let the store delete after N days.No code to run. The store does it at scale.Coarse (days), and it deletes only the blob, not the record or the cache. Good as a safety net, not the main tool.
Pick
Check on every read, sweep by hour bucket, lifecycle rules as a backstop

Correctness comes from the read check: an expired paste is never served, even if cleanup is late. Space comes from the sweeper. It reads the bucket for each past hour, and for every code does the same three steps in the same order: hide (set status to expired and remove from cache), delete the blob, then delete the record (or keep a tiny tombstone for a while). Every step is safe to repeat, so a crash in the middle just means the next run finishes the job.

About 8 expirations a second is a light load, so the sweeper can be slow and paced, which protects live traffic. Lifecycle rules on blob tags catch anything the sweeper missed. A reconciliation job compares blobs and records to find leaks.

The sweeper (sketch)
for hour in dueBuckets(now - 5 minutes):          // oldest first, resumable
  for code in expiryIndex.scan(hour, pageSize = 500):
    meta.update(code, status = "expired")            // 1. stop serving at once
    cache.delete(code); cdn.purge(code) (if public)  //    best effort
    store.delete("blobs/" + code)                    // 2. free the space (idempotent)
    meta.delete(code)                                // 3. drop the record (or keep a tombstone)
    expiryIndex.delete(hour, code)
  markBucketDone(hour)                               // pace the loop: do not hurt live traffic
QuestionAnswer
What if the 10-minute expiry matters?The read check handles it exactly. The sweeper uses the hour bucket, so a 10-minute paste can sit for up to an hour before its space is freed. That is fine.
Can a deleted code be reused?Not soon. Old links live in emails and chats. Public codes come from an ever-growing counter, so they are simply never reused. Random codes will not clash.
Owner deletes by handSame three steps, but done right away, with a CDN purge. Soft delete first, then a short grace period for undo and for legal holds.
Moving old ‘never expire’ pastes to cold storageA separate job, based on last access. Cheaper per GB, slower to read, and the record notes which tier holds the text.
🎤
Say it out loud
“Expiry has two jobs. Correctness: on every read I check expires_at, so an expired paste is never served, even if cleanup is late. Space: a sweeper reads an index keyed by hour, so it only touches what is due, never the whole table. For each paste it hides it, deletes the blob, then deletes the record, and every step is safe to repeat. Object-store lifecycle rules sit behind it as a safety net, and a reconciliation job finds orphans.”
5.4

Fast, safe reads

The problem: Reads are mostly cache-friendly, but a viral paste can still be thousands of requests a second. And the text comes from strangers: it may contain scripts, giant lines, or things that should never run in a visitor's browser.

OptionHow it worksGoodBad
Serve everything from the app server and storageEach request reads the record and the blob.Simple.The origin and storage take every read. A viral paste hits one object hard.
CDN for public and unlisted pastesCache the page and raw text at the edge, with a TTL up to the expiry.Pastes are immutable, so there is nothing to invalidate except deletes. Takes most reads off the origin.A deleted or blocked paste can stay at the edge until purged or the TTL ends.
Redis for metadata and small pastesCache-aside in front of the metadata store, and for hot small text.Fast. Cuts metadata reads by about 90%.Needs stampede protection. More memory.
Serve raw text from the main domainReturn user text from the same site as the login pages.Simplest.A single bug lets a paste run script with access to the site's cookies (XSS). Dangerous.
Pick
CDN plus Redis plus object storage, and raw text from a separate domain with strict headers

Because a paste never changes, the CDN can hold it until it expires: set the TTL to the smaller of the time left and, say, a day. The only thing that can invalidate it is a delete or a takedown, which we handle with a CDN purge. Redis keeps metadata hot. Together they take about 90% of reads off the origin, leaving about 12 reads a second on average.

The security rule is simple: never let a paste be treated as a web page. Show the text escaped inside a page we control, and serve the raw text as text/plain from a different domain, so even a mistake cannot reach the main site's cookies.

Header or ruleWhy
Content-Type: text/plain; charset=utf-8The browser shows text, and does not run it as HTML or script.
X-Content-Type-Options: nosniffStops the browser guessing a different type from the content.
Separate domain for raw text (for example usercontent.example)Cookies and storage of the main site are not sent there. A bug cannot steal sessions.
Content-Security-Policy: sandbox; default-src 'none'Even if opened as a page, nothing can run.
Escape text in the HTML view, highlight in the browser with a safe libraryNever insert user text as markup.
Range requests and streaming for large pastesA 10 MB paste starts to show at once and a retry can resume. Never load the whole text into app server memory.
Cache-Control: public, max-age up to the expiry (public and unlisted), private, no-store (private)Correct caching per visibility.
🧠Why immutable pastes matter
Because pastes cannot be edited, there is no stale-cache problem and no version logic. The only invalidations are delete, expiry and takedown. Say this in the interview. It is a great example of a requirement that makes the design simpler.
🎤
Say it out loud
“Pastes never change, so I cache hard: a CDN for public and unlisted pastes, Redis for metadata, with the TTL never longer than the paste's life. That takes about 90% of reads off the origin. For safety, I never serve user text as a page. The HTML view shows it escaped, and the raw text comes as text/plain with nosniff from a separate domain, so a mistake cannot reach the site's cookies. Large pastes are streamed with range requests.”
VisualizerBlobs in the database, or in object storage?Pick where the text lives, then raise pastes per day and paste size. Watch the database size, the restore time, the daily sweep and the cost.
Where does the paste text live?
How long do pastes live? (share that expire after 1 day / 7 days / never)
Stored data at the end of each month (one copy, text compressed 3 times)
1
2
3
4
5
6
7
8
9
10
11
12
DatabaseObject storageBars use the same scale in both designs, so switch the choice above to compare.
Live pastes at month 12
111 million
1.10 TB of text before compression
Database size (one copy)
401 GB
restore takes about 33 min
Sweeper deletes per day
700 thousand
7.0 GB of text, about 8.1 per second
Cost per month (illustrative units)
12.0k
split design: 1.5k
It still works at this size, but the database is already 401 GB per copy and a restore takes about 33 min. Most of those bytes are text that nobody queries by field. Move the pastes up (more pastes a day, or a larger average size) and watch it grow into trouble.

Deleting many large rows from a database also leaves dead space that must be reclaimed later (vacuum or compaction), on top of the normal load. A simplified model with fixed numbers and no random values. Text compresses 3 times in both designs, so the comparison is about where the bytes live. Metadata is 300 bytes per paste. The database keeps 3 copies; object storage uses erasure coding (about 1.5 times). One GB in the database costs 10 units and in object storage 1 unit. Units are illustrative, not prices.

Step 6Scale, bottlenecks and failuresabout 7 min

🤔
Pause. Try it yourself first
Imagine 10 times the traffic and a bad day: a viral paste, an outage in the middle of a write, a flood of spam. What breaks first, and how do you cope?

What breaks first, and the fix

BottleneckFix
Database size: text kept in rowsKeep only metadata in the database. Text goes to object storage. Backups and restores shrink by about 12 times (compressed text plus metadata, against metadata alone).
One viral paste read thousands of times a secondCDN for public and unlisted pastes, a short in-process cache, and Redis. Spread one hot key across copies if needed (see Hot Keys).
Metadata store too big or too busy for one machinePartition by hash of code (consistent hashing). 165 GB is small, so shard for headroom and failure isolation, not for size.
Many large uploads at onceCap the size, stream the body, and for big pastes use a signed upload straight to object storage, so app servers never hold 10 MB bodies.
Cleanup competing with live trafficPace the sweeper, work bucket by bucket, run it in off-peak hours, and give it lower priority than user requests.
Storage growing forever for pastes that never expireTier old, unread pastes to cold storage. Compress. Keep a growth forecast and review the ‘never’ option.
‘Recent pastes’ or ‘my pastes’ lists scanning too muchSecondary index by (owner_id, created_at) with keyset pagination, and a precomputed public ‘recent’ stream.

What if a part fails?

FailureHow the design copes
Object storage is slow or downReads of cached pastes keep working. Writes return a clear error and the client retries with the same Idempotency-Key. Do not accept a paste we cannot store.
Metadata store loses a node or zoneThree copies in different zones. Reads and writes continue on the others. Rebuild the missing copy in the background.
Redis is down or coldFall back to the metadata store, with request coalescing so one lookup per code. Rate limit, so a cold cache does not flatten the database.
A create dies between blob and recordAn orphan blob remains. The reconciliation job removes blobs with no record after a day. The user simply retries.
The sweeper crashes halfwayEvery step is idempotent and each bucket has a done marker. The next run finishes the work.
A bad paste must disappear now (legal, malware)Set status to blocked (read check stops it at once), delete from Redis, purge the CDN, then delete the blob. Keep an audit record.
What to monitor
  • •Create and read success rate, latency (p50, p99), and error rate by status code
  • •Cache hit rates (CDN, Redis) and origin reads per second
  • •Object-store errors, latency, and the count of orphan blobs found by reconciliation
  • •Sweeper lag: how far behind the current hour it is, and deletions per minute
  • •Total stored bytes and growth per day, per tier
  • •Abuse signals: scan hits, reports, creates per IP, blocked pastes
Security and abuse
  • •Never serve user text as HTML. Escape it, and serve raw text from a separate domain with nosniff
  • •Rate limit creates by IP and by user, with stricter limits for anonymous users (see Rate Limiting)
  • •Size limit enforced at the edge and in the app (413), before reading the whole body
  • •Scan new pastes asynchronously for malware links, spam and leaked secrets (API keys, passwords), and block or flag them
  • •A report button, a takedown process, and a fast way to purge cache and CDN

Step 7Wrap upabout 3 min

Pastebin looks like the URL shortener, but the content changes the design. I split the data: small hot metadata in a key-value store, partitioned by code, and compressed text in object storage. Writes put the blob first and the record second, so a failure leaves harmless orphans. Pastes are immutable, so a CDN and Redis carry almost all reads. Expiry is checked on every read and swept by hour bucket. Unlisted pastes use 128-bit codes, private pastes need a login, and raw text is served safely from a separate domain.

Trade-offs you made

DecisionWhat we gainWhat it costs
Metadata and text in separate storesSmall fast database, cheap durable blobs, quick restoresTwo systems to write to, and a reconciliation job for orphans
Blob first, record secondNo record can point to missing textOrphan blobs to clean up
Immutable pastesSimple caching, no versions, easy replicationNo editing: changes mean a new paste and a new link
128-bit codes for unlisted pastesCannot be guessedLong URLs that are hard to type
Hour-bucket expiry indexCleanup reads only what is dueA second write on create, and freeing space up to an hour late
Skip content de-duplicationSimple deletes, no privacy leak, works with encryptionIdentical pastes are stored more than once
If we had more time, we would…
  • •Move cold, unread pastes to cheaper storage with automatic tiering
  • •Multi-region: replicate blobs and metadata, with regional code ranges, so reads are local
  • •Client-side encryption for private pastes (the key stays in the link fragment)
  • •A smarter abuse pipeline: reputation scores, secret scanning and human review
  • •Search over public pastes with a separate index (not on the main path)
🎤
Say it out loud
“To recap: metadata in a key-value store, compressed text in object storage, blob written before record. Pastes are immutable, so the CDN and Redis carry nearly all reads. Expiry is checked on read and swept by hour bucket. Unlisted pastes get 128-bit codes, private pastes need a login, and raw text is served from a separate domain so it can never run. The main trade-off is two stores in exchange for a small, fast database and cheap, durable text. With more time I would add cold storage tiering and multi-region replication.”

Q&ACross-questions (23)

💡How to practise
Cover the answer. Say yours out loud in 30 to 60 seconds. Then open the model answer, the follow-up, and the weak answer to see what to avoid. Use Open all at the top for a quick read.
Warm-upProbingCurveballWarm-up = basics. Probing = tests depth. Curveball = changes the problem.

Storage and size

The part that makes this different from the URL shortener.

Links, privacy and abuse

Where ‘unlisted’ and ‘private’ get tested, and where user text meets a browser.

Scale, reads and cleanup

Viral pastes, deletion at volume, lists and counters.

Curveballs

Changes to the problem. They test whether you know why your design looks as it does.

What ifIf the interviewer changes the problem

A change in requirements is a test of whether you understand why your design looks the way it does.

New requirementWhat changes in the design
Pastes must be editableImmutable becomes versioned: new content per version, a small mutable pointer to the latest. The pointer needs invalidation, the blobs stay cacheable forever.
Allow file and image uploads up to 1 GBDirect signed uploads to object storage, multipart and resumable. Virus scanning, content-type checks, thumbnails, and a CDN for large objects with range requests.
Everything must be end-to-end encryptedThe client encrypts, the key stays in the URL fragment. We store ciphertext only: no server-side scanning or highlighting, and a lost link means lost data.
100 times more pastes (100M a day)Request rate is still moderate (about 1,200 writes a second), but bytes explode (1 TB a day). Aggressive tiering, shorter default expiry, per-user quotas, and a larger sharded metadata store.
Global users with strict latencyMulti-region replication of blobs and metadata, regional code ranges, CDN everywhere, and deletes that fan out to all regions.
Pastes must be deleted within one hour of expiry, with proofHour buckets become minute buckets, the sweeper gets a deadline and monitoring, deletions are logged to an audit trail, and cold copies and backups need their own deadline.
Private team workspaces with sharing and rolesA permissions model (owner, team, roles) on every read, signed URLs for blobs, no shared cache for private data, and audit logs of access.
Add public search and trending pastesA separate search index fed from a queue, plus view-count aggregation into a top-K for ‘trending’. Both are eventually consistent and off the main path.

ScoreHow answers are judged

AreaWeakGoodGreat
RequirementsStarts drawing. Never asks about expiry, visibility or size.Asks about expiry, visibility, limits and scale, and writes both lists.Asks what makes it different from a shortener (size, expiry, trust). Confirms pastes are immutable, and says what that buys.
EstimationOnly requests per second. No storage numbers.Writes, reads, daily and 5-year storage, with correct maths.Compares content and metadata sizes, accounts for expiry mix, compression and erasure coding, and uses the result to decide the storage design.
DesignOne box called ‘database’ holding the text.Metadata store, object store, cache, and a clear read and write path.Explains the write order and orphan handling, puts the CDN where immutability allows it, and keeps background work off the request path.
Deep-dive depthSays ‘use S3’ with no reasoning.Compares storage options, explains expiry cleanup and unguessable links.Gives numbers (33 to 1, 131 bits vs 1 in 6,400), names failure cases, and makes every cleanup step idempotent.
Trade-offs and failuresCannot say what happens if one of the two writes fails.Covers cache down, object store down, viral paste, and abuse.States the cost of each choice (two stores, orphans, no dedup, long URLs) and what they would monitor and add next.
Safety and privacyDoes not mention that pasted text can be malicious.Mentions escaping, rate limits and private access control.Separate raw domain, nosniff, CSP, signed URLs, scanning pipeline, takedown across CDN and backups, and the honest ‘unlisted is not secret’.

AvoidCommon mistakes on this question

MistakeDo this instead
Treating Pastebin as the URL shortener and re-doing code generation for ten minutesSay ‘same ranges and base62 as the shortener’ once, then spend the time on storage, expiry, privacy and safe serving.
Storing the text in the database without any numbersCompare sizes (33 to 1), backup and restore time, and cost, and then split metadata from blobs.
Writing the record before the blobBlob first, record second. A failure leaves an orphan blob, not a broken link.
Cleaning up expired pastes with a full-table scanCheck expires_at on read for correctness, and sweep by hour bucket for space.
Calling unlisted pastes ‘private’ or ‘secure’Say unlisted means unguessable, not secret. Use 128 random bits, and offer private (login) for anything sensitive.
Serving user text as HTML from the main domainEscape in the page, serve raw as text/plain with nosniff, from a separate domain.
Updating a view counter on the paste row for every readSend view events to a queue and aggregate. Never create a hot row, and never break caching.
Forgetting caches and backups when deletingOrder the delete (hide, purge cache and CDN, delete blob, delete record), and say how backups age out.

Revise60-second revision sheet

  • ✔Difference from the shortener: big content, most items expire, and the text comes from strangers.
  • ✔Scale: 1M pastes a day = 12 writes and 120 reads a second, but 10 GB of text a day. Bytes are the problem.
  • ✔Sizes: 5 years of ‘never expire’ is about 550M pastes, 5.5 TB raw, 1.8 TB compressed. Metadata is only about 165 GB.
  • ✔Split: metadata in a key-value store by code, compressed text in object storage (erasure coded, about 1.5 times, not 3).
  • ✔Write order: blob first, record second. A failure leaves an orphan blob. A reconciliation job cleans it.
  • ✔Codes: public = short ranged codes (as in the shortener). Unlisted = 128-bit random. Private = login on every read.
  • ✔Expiry: check on read, sweep by hour bucket (hide, delete blob, delete record), lifecycle rules as a backstop.
  • ✔Reads: immutable, so CDN plus Redis, TTL up to the expiry. Purge only on delete or takedown.
  • ✔Safe serving: escape in the page, raw text as text/plain with nosniff from a separate domain, CSP sandbox.
  • ✔Views and lists: events to a queue, never a counter on the row. Keyset pagination on a secondary index.

Read these topics next

Design a URL Shortener→

The code generation and redirect ideas that this design reuses.

Object Storage→

Where the compressed text lives: buckets, objects, erasure coding and lifecycle rules.

CDN→

Why immutable pastes are ideal for edge caching, and how purges work.

Data Archiving and TTL→

Expiry, tiering and cleaning up old data.

Compression and Deduplication→

Why text compresses about 3 times, and the trade-offs of dedup.

Input Validation→

Escaping and safe handling of untrusted text.

Hot Keys→

What to do when one paste gets most of the traffic.

Rate Limiting→

Limiting creates per user and per IP to stop spam.

← Previous
Design a URL Shortener
Next →
Design a Rate Limiter