Skip to content

Design a Pastebin

Intermediate 65 min read Part 17 of 18

Design Pastebin: short unguessable links to stored text, object storage vs database, expiry, CDN-heavy reads, highlighting, analytics and abuse control.

The Problem#

A pastebin is a website where you paste a block of text, such as a stack trace, a config file, a snippet of code or a log, and get back a short link like paste.example/aZ3kQ9x. Anyone with the link can open it and read the text, usually with syntax highlighting for code. Pastes can be set to expire after ten minutes, a day, a month, or never. Pastebin.com, one of the oldest, has been running since the early 2000s; GitHub Gist, PrivateBin, Hastebin and dozens of company-internal tools do the same job.

It is a classic interview question because it is small enough to finish in 45 minutes yet touches most of the basics: generating unique keys, choosing where to store data, read-heavy caching with a CDN, expiring data, analytics over access logs, and protecting a public write endpoint from abuse. It is the close cousin of the URL shortener. A URL shortener maps a short key to a long URL (a few hundred bytes); a pastebin maps a short key to the content itself, which can be kilobytes or megabytes. That one difference changes the storage design: you no longer want the payload in the same table as the key.

The difficult parts are not where beginners expect them. Writes are rare (a few per second). Reads are more frequent but most are served by a CDN. The real design questions are:

  • How to make keys that are short, unique and unguessable, because for an "unlisted" paste the link is the only thing protecting the content.
  • Where the bytes live: in a database row, in object storage, or split between them, and how that interacts with caching and expiry.
  • How to expire and delete data reliably across a database, an object store, caches and CDN edges.
  • How to count views when most reads never reach your servers because the CDN answered them.
  • How to stop the service from becoming a host for malware, leaked passwords and spam, which is what happens to every public paste site that does not plan for it.

Analogy. A pastebin is like a cloakroom at a theatre. You hand over your coat (the text) and get a numbered ticket (the short link). Anyone holding the ticket can collect, or here look at, the coat. The cloakroom is small at the front (a counter with tickets: the database) and large at the back (racks of coats: the object store). Popular coats get copies hung right by the door (the cache and CDN) so the attendant does not walk to the back every time. Some tickets say "return by midnight" (expiry), and at closing time someone walks the racks and clears out the expired ones (cleanup). If ticket numbers were simply 1, 2, 3, anyone could guess other people's tickets, so the numbers are long and random. And the cloakroom has a rule against checking in stolen goods or anything dangerous (abuse control).

Background: a few terms used in this design#

  • Paste: a stored block of text, plus metadata such as creation time, expiry, language and visibility.
  • Key (short code, slug): the short identifier in the URL, such as aZ3kQ9x. Usually 7 to 10 characters from the 62-character alphabet a-z A-Z 0-9 (base62), which needs no escaping in URLs.
  • Visibility: public pastes appear in listings and search engines; unlisted pastes are reachable only by link; private pastes need the owner to be logged in. Unlisted is the common default, and its security rests entirely on the key being hard to guess.
  • Object storage: a service such as Amazon S3, Google Cloud Storage or Azure Blob Storage that stores files ("objects") by key, cheaply and durably, at any scale, accessed over HTTP. Good at big immutable blobs, not at tiny frequent updates or queries.
  • CDN (content delivery network): a network of caching servers close to users that serve copies of responses so the origin servers do not have to. Pastes never change after creation, which makes them ideal CDN content.
  • TTL (time to live): how long something is valid. Used for paste expiry and for cache lifetimes.
  • Origin: our own servers behind the CDN.
  • Syntax highlighting: colouring code by its grammar (keywords, strings, comments) so it is readable. Needs to know or detect the language.

Clarifying Questions#

QuestionAssumed answerWhy it matters
Who can create pastes?Anyone, anonymously; logged-in users get higher limits and can list and delete their pastesAnonymous writes make abuse control and rate limiting essential
What content?Text only (UTF-8), code and logs mostly; no images or binariesLets us compress well, highlight, and scan content; binary uploads would make it a file host
Maximum paste size?512 KB for anonymous users, 10 MB for logged-in usersDrives the choice between database and object storage and the upload path
Expiry options?Never (default), 10 minutes, 1 hour, 1 day, 1 week, 1 month, and "burn after reading"Needs a cleanup process and expiry-aware caching
Visibility?Public, unlisted (default), private for logged-in usersUnlisted links must be unguessable; public pastes need moderation before search indexing
Can users edit pastes?No. Pastes are immutable; "edit" creates a new pasteImmutability makes caching trivial and safe
Custom links?Out of scope for this design; easy to add with a uniqueness checkSame as in a URL shortener
Scale?10 million pastes written and 100 million paste views per month to start; design for 10 times thatSmall write load, read-heavy, spiky
Read latency?Under 100 ms p99 for cached pastes worldwide, under 300 ms for uncachedPushes us to a CDN and a memory cache
Analytics?Monthly view counts per paste, shown to the owner; not real-timeAllows batch processing of logs rather than counting every read synchronously
Availability?High: reading existing pastes should keep working even if creating new ones is briefly impairedRead path must survive database or region trouble
Abuse and legal?Must handle malware, leaked credentials, spam links and takedown requestsNeeds scanning, reporting, takedown and rate limits

Requirements#

Functional#

  1. Create a paste. A user submits text with optional title, language, expiry and visibility, and receives a short, unique link. Anonymous users also receive a secret delete token so they can remove their paste later.
  2. View a paste. Anyone with the link sees the text, rendered with syntax highlighting, or fetches it raw (/raw/{key}) as plain text.
  3. Expire pastes. Pastes with an expiry stop being readable at their expiry time and are deleted from storage afterwards. "Burn after reading" pastes are deleted after the first view.
  4. Analytics. The service records views and shows owners monthly view statistics per paste.
  5. Delete and report. Owners (or holders of the delete token) can delete pastes; anyone can report a paste for abuse; operators can take pastes down.

Out of scope: accounts and email verification beyond basic login, editing and version history, custom short links, comments, full-text search across pastes, and an admin moderation console beyond the APIs it needs.

Non-Functional#

  • Read-heavy and spiky. About 10 reads per write on average, but a paste linked from a popular forum can get hundreds of thousands of views in an hour. Reads must scale independently of writes.
  • Low latency for reads. p99 under 100 ms for cached pastes worldwide; first byte under 300 ms for uncached ones.
  • High availability for reads, 99.95% or better. Writes can tolerate slightly lower availability (99.9%).
  • Durability. A created paste is never lost before its expiry. Losing user content is the worst failure.
  • Unguessable keys. Knowing some keys must not help anyone find others; scanning the key space must be infeasible.
  • Expiry correctness. An expired paste must never be shown, even if it is still in a cache or not yet deleted.
  • Cost efficiency. Storage grows forever for never-expiring pastes, so cost per stored gigabyte matters.
  • Abuse resistance. Rate limits per client, content scanning, and quick takedown.

Which matter most? Durability and read availability first, then read latency, then key unguessability and abuse resistance. Writes are small in number, so the write path can afford a few extra milliseconds for safety checks. Consistency needs are mild: a newly created paste must be readable immediately by its creator (read-your-writes for the link they just received), and expiry and deletion must take effect within seconds, but nothing else needs strong guarantees.

Capacity Estimation#

Only the numbers that change the design. A useful conversion: a month has about 2.5 million seconds, so 1 request per second is about 2.5 million requests per month, and 40 per second is about 100 million per month.

Traffic at launch.

  • 10 million paste writes per month ÷ 2.5 million seconds ≈ 4 writes per second on average.
  • 100 million reads per month ≈ 40 reads per second on average, a 10:1 read-to-write ratio.
  • Traffic is uneven: daily peaks at 2 to 3 times the average, and viral pastes (a leaked document, a popular config snippet) can drive thousands of reads per second to a single key for an hour or two.

Traffic at 10 times growth (the scale we design for): 40 writes per second, 400 reads per second average, peaks of 1,000 to 2,000 reads per second overall and 5,000 or more on one hot paste. Both are small numbers for modern hardware. One PostgreSQL primary handles hundreds of small writes per second without effort; the read load is mostly absorbed by the CDN. This is not a throughput problem. It is a storage, caching, lifecycle and abuse problem.

Size per paste. The classic estimate assumes about 1 KB of content plus small metadata:

  • key: 7 to 8 bytes
  • expiry: 4 to 8 bytes
  • created time: 5 to 8 bytes
  • path or pointer to the content: up to 255 bytes
  • total about 1.27 KB with 1 KB of content.

Real pastes of code and logs are larger. Let us assume a median of 2 KB and a mean of 10 KB, with a long tail up to the 10 MB limit, plus about 300 bytes of metadata.

Storage at launch.

  • Content: 10 million × 10 KB = 100 GB per month, about 3.6 TB over three years.
  • Metadata: 10 million × 300 bytes = 3 GB per month, about 110 GB over three years. That fits in one database server's memory, so the metadata store is easy.
  • Keys: 10 million per month is 360 million keys in three years.

Storage at 10 times growth. About 1 TB of content per month, 36 TB over three years, and 3.6 billion keys. Content compressed with zstd or gzip (text compresses 3 to 5 times; logs often more) is closer to 10 TB. In object storage at roughly $0.02 per GB-month for standard tiers, 10 TB costs about $200 a month, small. In a replicated database on SSDs with three copies and indexes, the same data would cost an order of magnitude more and would make the database slow to back up, restore and replicate. That difference is the main argument for object storage.

Expiry share. Suppose 40% of pastes have an expiry, most of them a day or a week. Then 4 million pastes per month at launch (40 million at scale) must be deleted on schedule: about 1.5 deletions per second on average, 15 at scale. Cheap, but not free if deletion means scanning a large table.

Bandwidth. 400 reads per second × 10 KB ≈ 4 MB/s average at scale, perhaps 50 MB/s at peak. With a CDN hit rate of 90% or more, origin egress is a few megabytes per second.

Cache size. Paste popularity follows a power law: a small fraction of pastes receive most views. If the hottest 1% of the last month's pastes (100,000 to 1 million pastes) receive 80% of views, caching them takes 1 to 10 GB of memory. One Redis node holds that easily.

Key space.

  • 7 base62 characters give 62⁷ ≈ 3.5 × 10¹² keys. 360 million keys use 0.01% of the space; 3.6 billion use 0.1%.
  • 8 characters give 62⁸ ≈ 2.2 × 10¹⁴.
  • These numbers matter for both collision rate and guessability (Deep Dive 1).

What the numbers tell us.

  1. Writes are tiny; one relational primary is enough for years. No need for write sharding at the start.
  2. Reads are served mostly by the CDN; the origin needs a modest cache and a few servers.
  3. Content belongs in object storage, metadata in a database: content is 30 to 100 times larger than metadata.
  4. Expiry needs an efficient delete path, not a full-table scan.
  5. The key space is big enough, provided keys are random rather than sequential.

Core Entities#

  • Paste: key, owner (optional), title, language, visibility, size, content hash, content location, created time, expiry time, burn-after-read flag, status (active, expired, deleted, taken down).
  • Content blob: the paste text, compressed, stored in object storage (or inline in the database for very small pastes).
  • User: an optional account with a tier that sets limits.
  • Delete token: a secret issued to anonymous creators that authorises deletion. Stored only as a hash.
  • View event: a record that a paste was viewed: key, time, coarse location, referrer, whether it was a bot. Aggregated into monthly view counts.
  • Abuse report: a report against a paste, with reason and reporter, feeding moderation.

API Design#

A public REST API over HTTPS, used by the website and by command-line tools (many developers paste from the terminal, as in cat error.log | paste-cli). Internal services talk over RPC (gRPC or plain HTTP with JSON); the external API stays simple and cacheable.

# Create a paste
POST /api/v1/pastes
Content-Type: application/json
Idempotency-Key: 1c9e...            (optional, safe retries)
{ "content": "Traceback (most recent call last): ...",
  "title": "worker crash", "language": "python",
  "expiresIn": "1d", "visibility": "unlisted", "burnAfterRead": false }
 
-> 201 Created
{ "key": "aZ3kQ9xR", "url": "https://paste.example/aZ3kQ9xR",
  "rawUrl": "https://raw.pasteusercontent.example/aZ3kQ9xR",
  "expiresAt": "2026-12-04T10:15:00Z", "deleteToken": "dt_5Yk..." }
 
# View a paste (HTML page with highlighting) and raw text
GET /{key}                         -> 200 HTML, or 404 / 410 Gone
GET /api/v1/pastes/{key}           -> 200 { "content": "...", "language": "python",
                                             "createdAt": "...", "expiresAt": "..." }
GET raw host /{key}                -> 200 text/plain; charset=utf-8
 
# Delete (owner session or delete token)
DELETE /api/v1/pastes/{key}
X-Delete-Token: dt_5Yk...          -> 204
 
# Analytics for the owner
GET /api/v1/pastes/{key}/stats?month=2026-11 -> { "views": 1840, "uniqueVisitors": 912 }
 
# Report abuse
POST /api/v1/pastes/{key}/reports  { "reason": "malware" } -> 202

Design notes:

  • 201 with the full URL. The client never constructs URLs itself, so we can change domains or key formats later.
  • 410 Gone for expired or deleted pastes, 404 for keys that never existed. The distinction helps users ("this paste expired") but reveals that a key once existed; for unlisted pastes some services return 404 for both to leak nothing. We return 410 only to the creator's session and 404 to everyone else.
  • Raw text from a separate domain. Serving user content as text/plain from a different registrable domain (the way GitHub serves raw files from githubusercontent.com) means that even if a browser were tricked into interpreting a paste as HTML, it would run on a domain with no cookies or session to steal (Deep Dive 5).
  • Idempotency key on create so a retried request (flaky mobile network, CLI retry) does not create two pastes. See Idempotency and Safe Retries.
  • Rate limit responses are 429 Too Many Requests with Retry-After and X-RateLimit-* headers (Deep Dive 8).
  • Why REST. The external API is consumed by browsers, scripts and curl; REST over HTTP is universal and plays well with CDNs (GET responses are cacheable by URL). Internally, RPC frameworks give typed contracts and lower overhead, but at our scale the choice barely matters. API Styles: REST, gRPC, GraphQL and More compares the options.

High-Level Design#

We build the design one requirement at a time, starting with the simplest thing that works.

1) Create a paste#

Simplest version. A web server receives the text, generates a key, and inserts one row into a relational database: (key, content, created_at, expires_at). It returns the URL. At 4 writes per second this works on day one.

The problem is the content column. Over three years the table grows to terabytes, most of it text that is written once and read rarely. Every backup, replica rebuild and schema change drags those terabytes along; the database's memory cache fills with paste bodies instead of the index; and storage on replicated database SSDs costs far more than it needs to.

Better: split metadata from content. The database holds a small metadata row per paste; the text goes to object storage under a path derived from the key. The database acts as a large hash table from key to "where the content is, and what rules apply to it". The object store is built for exactly this: cheap, durable (Amazon S3 is designed for eleven nines of durability), and unlimited in size. Very small pastes (under, say, 4 KB) can stay inline in the metadata row to save an object-store round trip; Deep Dive 2 weighs this.

The write flow:

  1. The client sends the paste to a web server (a reverse proxy such as nginx or a managed load balancer) that forwards it to the Write API.
  2. The Write API checks the rate limit for the client, validates size and encoding, and runs a quick abuse check.
  3. It generates a random key (Deep Dive 1) and uploads the compressed content to the object store at pastes/{key}.
  4. It inserts the metadata row. The primary key on key enforces uniqueness: if the insert fails because the key exists (extremely rare), it generates a new key and retries.
  5. It returns the URL and, for anonymous users, a delete token.

Writing the content before the metadata matters: if the server crashes between the two steps, we are left with an orphan object (harmless, cleaned up later) rather than a metadata row pointing at nothing (a broken paste).

2) View a paste#

Simplest version. The Read API looks up the key in the database; if found and not expired, it fetches the content from the object store and returns it. Two lookups: a database index lookup (about 1 ms) and an object-store GET (10 to 50 ms within a region for small objects).

At 40 reads per second this is fine. At 400 per second, with spikes of thousands on one paste, we do not want every view to hit the database and object store, and we want users on other continents to get fast responses. Two layers of caching solve it:

  • A memory cache (Redis or Memcached) in front of the database and object store, holding metadata and content of popular pastes. Pastes are immutable, so there is nothing to keep in sync except expiry and deletion. A cache hit costs well under a millisecond.
  • A CDN in front of everything. Because a paste never changes, its rendered page and raw text can be cached at CDN edges worldwide, for a time bounded by its expiry. A popular paste is then served from an edge near each reader and our origin sees one request per edge per cache lifetime.

Database read replicas take the cache misses, so the primary is left for writes.

3) Expire pastes and clean up#

Expiry has two parts that should not be confused:

  1. Stop serving the paste at its expiry time. This must be exact. The Read API checks expires_at on every read, including reads served from the memory cache, and the CDN cache lifetime is never longer than the time left before expiry. An expired paste is never shown, even if its bytes still exist.
  2. Delete the data some time after expiry. This can be lazy: a background cleanup worker periodically finds expired pastes using an index on expires_at, deletes their content objects and metadata in batches, and purges any CDN copies. Object-store lifecycle rules can act as a safety net.

"Burn after reading" pastes are deleted (atomically marked consumed) at the first successful view and are never cached anywhere. Deep Dive 3 covers all of this.

4) Track analytics#

Owners want monthly view counts. Real-time counts are not required, which opens the cheapest option: process logs in batches. Each view produces a log line (from the CDN's access logs and from our Read API). Logs land in object storage; an hourly or daily batch job (MapReduce-style, for example Spark or a SQL query in a warehouse) groups lines by (month, key), counts them, and writes the results into an analytics store that the stats API reads.

The crucial subtlety: with a CDN in front, most views never reach our servers. Counting only Read API requests would undercount popular pastes by 90% or more. Analytics must come from CDN logs (all major CDNs export them), or from a small, uncacheable beacon request fired by the page. Deep Dive 7 discusses both, plus unique visitors and bot filtering.

5) Protect the service: rate limits and abuse control#

A public, anonymous write endpoint will be abused: spam links, malware payloads, phishing pages, stolen credential dumps. The design needs:

  • Rate limits per IP and per account at the edge and in the Write API, with stricter limits for anonymous users.
  • Content scanning on write (fast checks) and asynchronously (slower checks), with the ability to block or hide pastes.
  • Reporting and takedown, with operators able to remove a paste everywhere within minutes, including CDN copies.

Deep Dive 8 covers this.

The full high-level design#

Components:

  • CDN. Caches paste pages and raw text at edges worldwide, bounded by each paste's remaining lifetime; can be purged by key on delete or takedown. Also exports access logs for analytics.
  • Load balancer and WAF. Terminates TLS, spreads requests over stateless servers, applies coarse per-IP rate limits and blocks known bad clients.
  • Write API. Validates and rate-limits creates, generates keys, writes content then metadata, returns the URL and delete token.
  • Read API. Looks up metadata (cache, then replica), enforces expiry, visibility and status, fetches content (cache, then object store), renders or returns raw text, and sets cache headers.
  • Highlighter. Produces syntax-highlighted HTML for a paste and caches it; can run in the Read API process or as a separate service.
  • Memory cache. Metadata and content of hot pastes, and rendered HTML.
  • Metadata database. One primary for writes, read replicas for reads; small rows, indexed by key and by expiry.
  • Object store. Durable, cheap storage of compressed content, with lifecycle rules as a safety net for expiry.
  • Cleanup worker. Deletes expired and burned pastes, purges caches, removes orphans.
  • Abuse scanner. Asynchronous scanning, report handling and takedowns.
  • Analytics batch. Turns CDN and API logs into monthly view counts.

Key Flows#

Flow 1: create a paste#

  1. The load balancer forwards the request with the real client IP (via a header such as X-Forwarded-For that it sets itself, never trusting the client's copy).
  2. The Write API checks the rate limit for the IP and, if logged in, the account. Over the limit returns 429 at once.
  3. It validates: size within the tier's limit, valid UTF-8, not binary. A quick scan rejects obvious abuse (known malware signatures, blocked URL domains).
  4. It compresses the content (zstd at a moderate level takes well under a millisecond for 10 KB) and generates a random key.
  5. It writes the content to the object store, then inserts the metadata row. If the insert fails with a duplicate key, it picks a new key and retries; the orphaned object is removed by the cleanup worker, or the retry overwrites a new path.
  6. It returns 201 with the URL. Slower work (deep abuse scan, pre-rendering highlighted HTML) goes onto a task queue and runs asynchronously, so the user does not wait for it.

Latency: rate limit 1 ms, validation and compression 1 ms, object-store PUT 20 to 80 ms, database insert 2 to 5 ms. Total typically 30 to 100 ms.

Flow 2: view a paste#

  1. The CDN serves most views directly. Its copy can never outlive the paste because the origin set max-age no longer than the remaining lifetime.
  2. On a miss, the Read API tries the memory cache for both metadata and content.
  3. On a cache miss, it reads the metadata row from a replica and the content from the object store, then populates the cache (cache-aside).
  4. It always checks expiry and status before responding, even on a cache hit, so a paste that expired a second ago or was taken down a minute ago is not served from the memory cache.
  5. It renders the HTML (or returns raw text) and sets Cache-Control so the CDN caches it for at most the time left.

Latency: CDN hit 10 to 50 ms worldwide; origin with memory-cache hit 5 to 20 ms plus network; full miss 30 to 100 ms.

Read-your-writes. A creator who opens their new link immediately might hit a replica that has not yet received the insert (replication lag is usually milliseconds, occasionally seconds). Two cheap fixes: the Write API puts the new paste into the memory cache as it is created (write-through for new pastes), and a Read API that finds nothing on a replica retries once against the primary before returning 404. Database Replication discusses replication lag and these patterns.

Flow 3: upload a large paste directly to object storage#

Pastes up to 512 KB go through the Write API in one request. For logged-in users' pastes up to 10 MB, streaming megabytes through our API servers wastes their memory and bandwidth; the client uploads straight to the object store with a presigned URL.

  1. The client asks to create a large paste, declaring its size. The Write API checks the user's limits and creates a metadata row in status pending (not readable yet).
  2. It returns a presigned URL: a time-limited, signed permission to PUT exactly one object at pastes/{key}, with a maximum content length.
  3. The client uploads directly. The object store emits an "object created" event (S3 event notifications, for example).
  4. A worker verifies the object (size, checksum, encoding) and marks the paste active. Pending pastes that never complete are cleaned up after an hour.

This is the standard pattern from Pattern: Handling Large Files and Blobs. For a pastebin it is an optimisation for the tail; most pastes are a few kilobytes.

Data Model#

CREATE TABLE pastes (
  paste_key         CHAR(8)      PRIMARY KEY,        -- base62, random
  owner_id          BIGINT       NULL,               -- NULL for anonymous
  title             VARCHAR(200),
  language          VARCHAR(32),                     -- e.g. 'python', or NULL = detect
  visibility        VARCHAR(10)  NOT NULL DEFAULT 'unlisted',
  status            VARCHAR(12)  NOT NULL DEFAULT 'active',
  size_bytes        INT          NOT NULL,
  content_ref       VARCHAR(255) NOT NULL,           -- object path, or 'inline'
  inline_content    BYTEA        NULL,               -- small pastes only, compressed
  created_at        TIMESTAMPTZ  NOT NULL DEFAULT now(),
  expires_at        TIMESTAMPTZ  NULL,               -- NULL = never
  burn_after_read   BOOLEAN      NOT NULL DEFAULT false,
  delete_token_hash BYTEA        NULL                -- SHA-256 of the token
);
-- Cleanup worker: find expired pastes quickly; partial index skips never-expiring rows
CREATE INDEX pastes_expiry ON pastes (expires_at) WHERE expires_at IS NOT NULL;
-- "My pastes" for logged-in users, newest first
CREATE INDEX pastes_owner ON pastes (owner_id, created_at DESC) WHERE owner_id IS NOT NULL;
DataStoreWhy
Paste metadataPostgreSQL or MySQL, primary plus read replicas; or a key-value store such as DynamoDBSmall rows, lookups by primary key, an index on expiry, modest write rate; SQL gives easy secondary indexes
Paste contentObject store (S3, GCS, Azure Blob), compressed; tiny pastes inlineCheap, durable, unlimited, immutable objects; keeps the database small
Hot pastes and rendered HTMLRedis or MemcachedSub-millisecond reads for popular keys; absorbs spikes
Rate-limit countersRedisAtomic increments with expiry
Access logsObject store, then warehouseRaw input for batch analytics
Monthly statsSmall SQL table, or a warehouse such as BigQuery, Redshift or ClickHousePre-aggregated rows read by the stats API
Abuse reports and takedownsMetadata databaseLow volume, needs transactions and an audit trail

Index notes. The primary key on paste_key is a B-tree index that enforces uniqueness and gives logarithmic lookups; it is what makes "insert and let the database reject duplicates" safe. The expires_at index lets the cleanup worker find expired rows without scanning the whole table; the partial index excludes the majority of pastes that never expire, so it stays small. The creation-time index serves "my pastes" listings. Keeping these indexes in memory is the goal: reading 1 MB sequentially from memory takes on the order of hundreds of microseconds, several times faster than from SSD and nearly a hundred times faster than from a spinning disk, and random index lookups magnify the difference. See Database Indexing and Numbers Every Engineer Should Know.

SQL or NoSQL? Both work. A relational database used as a big hash table is simple, familiar, and gives secondary indexes (expiry, owner) for free. A key-value store such as DynamoDB scales without operational effort and has a built-in TTL feature that deletes expired items automatically (within a window that can be a day or two, so reads must still check expiry). A document store could keep metadata and small content together. At our write rate, scale does not force the choice; operational familiarity and the expiry index do. We choose PostgreSQL to start, and note that sharding by key hash is the path if it ever outgrows one primary. SQL vs NoSQL: How to Choose and Choosing a Database: A Decision Guide cover the reasoning.

Deep Dives#

1. Generating unique, short, unguessable keys#

The key must be unique (two pastes never share one), short (easy to share, fits in a chat message), and for unlisted pastes unguessable (knowing your key does not help find anyone else's). Uniqueness and shortness pull in the same direction as in a URL shortener; unguessability is what makes the pastebin different, and it rules out some popular answers.

Option A: hash something about the request, then base62-encode and truncate. For example, take the MD5 hash of the client's IP address plus a timestamp, encode it in base62, and keep the first 7 characters.

  • MD5 produces 128 bits and its output is uniformly distributed, so truncated output is spread evenly over the key space.
  • Base62 (a-z, A-Z, 0-9) is safe in URLs. Base64 adds + and /, which need escaping in URLs (the URL-safe variant swaps them for - and _, which also works).
  • Encoding is a short loop: repeatedly take the number modulo 62 as the next digit and divide by 62, in O(k) for k digits.

The weaknesses: the inputs are guessable (IP and time are not secret), so an attacker who knows roughly when someone created a paste and from which network can compute candidate keys; two requests from the same IP in the same timestamp tick (a busy NAT gateway, a script) produce the same key; and truncation to 7 characters discards most of the hash, so collisions must still be checked. Hashing the content instead gives deduplication (the same text always gets the same key), but it makes keys predictable from content: anyone could check whether a particular secret text was ever pasted by computing its key. Hashing random data is fine, but at that point the hash adds nothing over using the random bytes directly.

Option B: a counter, base62-encoded. A database sequence or a distributed ID generator gives 1, 2, 3 ...; base62 turns 3.6 billion into 6 characters. Unique by construction, no collision checks, and very short keys. But sequential keys are enumerable: someone who receives aZ3kQ9 can fetch aZ3kQ8, aZ3kQA and so on, and read every unlisted paste. Counters can be obfuscated with a reversible scramble (a keyed permutation such as a small block cipher over the 40-bit number space), which keeps uniqueness and hides order, but it is easy to get wrong. Counters suit URL shorteners, where links are not secret; they suit pastebins only with that scrambling layer. Unique ID Generation covers counters, Snowflake-style IDs and key-generation services.

Option C: random keys from a cryptographically secure generator, with a uniqueness check. Draw 8 random base62 characters from the operating system's secure random source (about 47.6 bits of entropy: 8 × log2(62) ≈ 8 × 5.95). Insert with the key as primary key; if the insert hits a duplicate, draw again. This is our choice.

function newPasteKey():
    for attempt in 1..5:
        key = ""
        repeat 8 times:
            key += ALPHABET[secureRandomInt(0, 61)]   # uniform, no modulo bias
        if insertMetadata(key) succeeds:             # PRIMARY KEY rejects duplicates
            return key
    raise "key space too full, lengthen keys"        # should never happen

Note secureRandomInt must be uniform. Taking a random byte modulo 62 gives modulo bias: 256 is not a multiple of 62, so the first 8 characters (256 − 4 × 62 = 8) appear slightly more often. Use rejection sampling (discard bytes of 248 and above) or a library function that does it.

Collision maths. With n keys already used out of N possible, a new random key collides with probability n ÷ N. With N = 62⁸ ≈ 2.2 × 10¹⁴ and n = 3.6 billion (three years at 10 times growth), that is about 1.6 × 10⁻⁵: one retry per 60,000 inserts, negligible. With 7 characters (N ≈ 3.5 × 10¹²) it is about 0.1%: still fine. The often-quoted birthday paradox (with about √N keys, some pair has probably collided) matters only if we did not check for duplicates; since the primary key check catches every collision, what matters is the per-insert retry rate.

Guessability maths. Unguessability depends on the density of used keys. With 3.6 billion used keys in an 8-character space, a random guess hits a real paste with probability about 1.6 × 10⁻⁵, or once per 60,000 guesses. An attacker with a botnet making 1,000 guesses per second finds about one paste a minute, which is a real leak for a service whose users paste secrets. Defences:

  • Longer keys for unlisted pastes. 10 characters (about 59.5 bits) make the density about 4 × 10⁻⁹: one hit per 250 million guesses, which takes 3 days at 1,000 per second, and rate limiting makes 1,000 per second hard to sustain. 12 characters push it beyond any practical scanning. A little extra length is cheap.
  • Rate-limit 404s. Normal users rarely request keys that do not exist. A client producing many 404s is scanning; throttle or block it at the edge (Deep Dive 8).
  • Do not leak existence. Return the same 404 for "never existed", "expired" and "deleted" to anonymous readers.
  • Treat unlisted as not private. The UI should say that anyone with the link can read the paste and offer password protection or client-side encryption for secrets (Deep Dive 10).

Option D: a key generation service (KGS). Pre-generate random unused keys offline, store them in a table, and hand out batches to API servers, which then need no collision check. This was popular in URL-shortener designs. For a pastebin at a few dozen writes per second, the retry-on-duplicate approach is simpler and has no extra component to keep running; a KGS becomes interesting only at very high write rates or when keys must be short enough that the space is crowded.

Custom keys and reserved words. If custom keys are added later, check them against the same primary key, reserve paths used by the application (api, raw, login, static), and filter offensive words. Random keys can also accidentally spell offensive words; excluding vowels from the alphabet (as some services do) avoids most of that at the cost of a slightly smaller alphabet.

2. Where to store the text: database, object storage, or both#

Option A: everything in the database. One table, one lookup per read, transactions over metadata and content together. Simple, and correct for small services. Problems at scale:

  • Size and cost. 36 TB of content over three years at 10 times growth, replicated three times, on database-grade SSD storage, plus backups. Object storage costs an order of magnitude less per gigabyte.
  • Operational drag. Backups, restores, new replicas and major-version upgrades all copy the whole dataset. A 100 GB database restores in minutes; a 30 TB one in many hours, which makes recovery objectives much worse.
  • Memory pollution. The database's buffer cache fills with large, rarely read rows instead of hot index pages. (PostgreSQL moves large values out of line into TOAST storage automatically, which helps, but the data still lives in the database's files and backups.)

Option B: everything in object storage. Store each paste as an object with metadata in object tags or headers. No database at all. Durable and cheap, but object stores are poor at queries: there is no efficient "find all pastes expiring before now" or "list my pastes newest first", listing is slow and paged, and per-request latency (10 to 50 ms) is higher than a database index lookup. Uniqueness checks need conditional writes (S3 added conditional PUTs with If-None-Match in 2024, which helps). Workable for a minimal service; awkward once features grow.

Option C: metadata in the database, content in object storage (our choice). The database is a compact index: about 300 bytes per paste, 110 GB over three years at launch scale, all fitting in memory. The object store holds the bulk. Each read costs a database lookup plus an object GET, but caching removes both for popular pastes. This is the split described in Object Storage and Blob Storage.

Refinement: inline tiny pastes. The median paste is about 2 KB. For pastes under a threshold (say 4 KB compressed), storing the content inline in the metadata row saves an object-store round trip (10 to 50 ms) on every uncached read, and saves per-request object-store charges, which for tiny objects can exceed their storage cost. Above the threshold, the object store wins. Many systems use exactly this hybrid. The cost is two code paths; keep the read logic in one function that hides which one applies.

ApproachRead cost (uncached)Storage costQueries and expiryOperational load
All in database1 index lookup, about 1 to 5 msHigh (SSD, replicated, backups)EasyHeavy backups and restores
All in object store1 object GET, about 10 to 50 msLowHard (no secondary indexes)Light
Metadata DB plus object storeLookup plus GET, about 15 to 60 msLowEasyLight
Hybrid with inline small pastesLookup only for most pastesLowEasyTwo paths to maintain

Object layout. Use the key as the object name, pastes/aZ3kQ9xR. Random keys spread naturally across the object store's internal partitions; older advice to add random prefixes for S3 performance came from sequential names and is largely obsolete since S3 scaled request rates per prefix in 2018, but random keys never hurt.

Compression. Compress before storing (zstd or gzip). Text compresses 3 to 5 times; repetitive logs compress 10 times or more. Store the codec in metadata. Serve with Content-Encoding: gzip when the client accepts it, so CDN and browser receive compressed bytes and the server never decompresses (if stored as gzip) or decompresses only once into a cached form.

Deduplication by content hash. The same text is often pasted many times (a common error message, a popular config). Store objects under their SHA-256 hash instead of the paste key (content-addressed storage), with the paste row pointing to the hash and a reference count on the blob. Identical pastes share one object. Savings depend on the workload; for a pastebin dominated by unique logs and code they may be modest (perhaps 10 to 20%), while for systems storing many identical files they are large. The cost: deleting a paste must decrement a reference count and delete the object only at zero, which needs care to avoid races (a new paste referencing a blob just as its last old reference is deleted). A simpler safe approach is to never delete shared blobs synchronously and let a periodic garbage collector remove blobs with no references for more than a day. Also note the privacy angle from Deep Dive 1: never expose the content hash in URLs, or people could test whether specific content exists.

Durability. S3 and its peers replicate objects across several facilities in a region and are designed for very high durability; versioning or cross-region replication protects against accidental deletes and regional disasters. The metadata database needs standard backups with point-in-time recovery. Losing metadata while keeping content makes pastes unreachable, so metadata backups are the more critical ones.

3. Expiry and cleanup#

Expiry looks simple ("delete it when it expires") but touches every layer: database, object store, memory cache, CDN and analytics. The key insight is to separate correctness (never serve an expired paste) from reclamation (eventually free the storage). Correctness must be exact and cheap; reclamation can be lazy and batched.

Correctness: check on every read. The Read API compares expires_at with the current time on every request, whether the metadata came from the memory cache, a replica or the primary. An expired paste returns 404 (or 410 to its creator) immediately, even though its bytes still exist. This is called lazy expiry, and Redis itself uses it for keys with TTLs: a key is checked when accessed, plus a background sampler removes expired keys that nobody touches.

Bounding caches by expiry. Caches must never outlive the paste:

  • Memory cache: set the entry's TTL to min(default TTL, expires_at − now).
  • CDN: set Cache-Control: public, max-age=N where N is at most the seconds remaining until expiry (and at most the default, such as one day). A paste expiring in 10 minutes is cached for at most 10 minutes. Use s-maxage for the CDN and a shorter max-age for browsers if you want to be able to purge CDNs quickly while browsers revalidate often.
  • Never cache burn-after-read pastes at all (Cache-Control: no-store).

Clock skew. Servers' clocks differ by milliseconds with NTP, occasionally more. A paste might be served a fraction of a second after expiry on a server whose clock is behind. That is acceptable; expiry times are user-facing approximations, not security boundaries (if they were, we would encrypt and destroy keys instead). Time, Clocks and Ordering explains why exact simultaneity is impossible anyway.

Reclamation options.

  1. Scan the table periodically for expires_at < now and delete matches. With no index this scans everything and gets slower as the table grows; at millions of rows it is wasteful but survivable once a day, and at billions it is not.
  2. Indexed sweep (our choice). A partial index on expires_at (only rows that have an expiry) lets the cleanup worker fetch the oldest expired rows cheaply: SELECT paste_key FROM pastes WHERE expires_at < now() ORDER BY expires_at LIMIT 1000. It deletes their objects, then their rows, then purges caches, and repeats until none remain. Running every minute keeps the backlog small. At 15 deletions per second on average this is trivial work.
  3. Database TTL features. DynamoDB, Cassandra and MongoDB can expire items automatically. DynamoDB deletes expired items in the background, typically within a few days of expiry, so reads must still filter expired items; Cassandra writes tombstones that must be compacted away, which can hurt read performance if many items expire in the same partitions. Convenient, but they do not delete the corresponding object-store content, so a stream of deletion events (DynamoDB Streams, for example) must trigger object deletion.
  4. Time-bucketed partitions. Put pastes with expiry in tables or partitions by expiry day (pastes_exp_2026_12_04) and drop a whole partition when its day has passed. Dropping a partition is almost free compared with deleting millions of rows, and avoids table bloat. This shines when expiries are many and clustered; PostgreSQL declarative partitioning or time-partitioned tables in other databases support it. The cost: lookups by key must check several partitions or use a global index, so many designs keep the key table separate and partition only the "expiry queue".
  5. Object-store lifecycle rules as a safety net. Lifecycle rules can expire objects after a number of days, matched by prefix or tag. Writing pastes with expiry to prefixes like exp/1d/, exp/7d/ and exp/30d/ with matching lifecycle rules means the object store deletes content even if our worker fails. Rules have day granularity and run asynchronously, so they complement, not replace, the read-time check.

Order of deletion. Delete the content first, then the metadata row? Or the other way round? If metadata is deleted first and the worker crashes, the object becomes an orphan: harmless (unreachable), cleaned up by a periodic orphan sweep that lists objects without metadata. If content is deleted first and the worker crashes, the row points to missing content: also harmless because the paste is already expired and the read-time check refuses it. Either order works because the read path checks expiry first. Pick one, make each step idempotent (deleting something already deleted succeeds), and retry.

Burn after reading. The paste must be shown exactly once. Two readers racing (a link preview bot and the real recipient, for example) must not both see it, so the transition must be atomic:

-- Atomically claim the single read; only one request can succeed
UPDATE pastes
   SET status = 'consumed'
 WHERE paste_key = 'aZ3kQ9xR'
   AND status = 'active'
   AND burn_after_read = true
RETURNING content_ref, inline_content;

The request that gets a row back shows the content; any other gets 404. The content is then deleted by the cleanup worker. Two practical problems: link previews in chat apps fetch URLs automatically and would "burn" the paste before the human sees it, so the page shows a "click to reveal" button and burns only on the explicit reveal request (a POST, which previewers do not send). And burn-after-read pastes must never be cached by CDNs or browsers.

Purging CDN copies. On explicit delete or takedown, the paste must disappear from edges within seconds, not when its TTL ends. CDNs offer purge-by-URL APIs (and purge by cache tag or surrogate key, which lets one call purge the page, raw text and API JSON for one paste). Purges propagate across edges in seconds on modern CDNs. Expired pastes need no purge because their CDN TTL was bounded by expiry.

Monitoring. Track the age of the oldest expired-but-not-deleted paste (backlog age) and the delete rate. If the worker stops, the read path still refuses expired pastes, so users notice nothing, but storage grows; an alert on backlog age catches it within hours. Data Lifecycle, Tiering and Retention covers retention and deletion pipelines generally.

4. Read-heavy caching and the CDN#

Pastes are immutable: once written, the content never changes. That is the best possible property for caching, because the classic hard problem, cache invalidation on update, disappears. Only expiry, deletion and takedown remove entries, and those are bounded or explicit.

When to bring up caching. With numbers: "At 400 reads per second, each uncached read costs a replica lookup and a 20 to 50 ms object GET. A memory cache cuts that to under a millisecond for the hot set, and a CDN takes 90% or more of reads off the origin entirely and serves readers worldwide in tens of milliseconds." Also: "A single paste linked from a popular news site can get 5,000 reads per second; we cannot send those to the object store."

Where to cache, from the client inward.

  • Client (browser) cache. Cache-Control: max-age lets a browser reuse a paste it already loaded. Short (a few minutes) so takedowns reach browsers reasonably quickly.
  • CDN cache. The biggest win for a public, read-heavy, immutable site. Page HTML, raw text and API JSON can all be cached by URL. s-maxage up to a day, bounded by the paste's expiry. Purge by URL or tag on delete. Configure stale-if-error so edges keep serving cached pastes if the origin is down, which gives read availability during origin incidents. See Content Delivery Networks (CDN).
  • Web server cache. A reverse proxy such as nginx or Varnish in front of the Read API can cache rendered pages for a few seconds to absorb bursts when the CDN's many edges all miss at once.
  • Application cache (Redis or Memcached). Holds metadata, compressed content and rendered HTML for hot pastes. The Read API checks it before the database and object store.
  • Database cache. The database's own buffer cache keeps hot index pages and rows in memory; with only metadata in the database, almost the whole working set fits.

What to cache: query level or object level. Caching at the query level stores the result of a query string (SELECT ... WHERE paste_key = 'aZ3k...') as the cache key. It is easy to bolt on, but any change to the query invalidates it and it is hard to delete everything related to one paste. Caching at the object level stores assembled objects (paste:aZ3kQ9xR:meta, paste:aZ3kQ9xR:content, paste:aZ3kQ9xR:html:theme-light), which maps directly to how the application thinks and makes targeted deletes easy. We cache at the object level.

Cache key design. The key must include every parameter that changes the response. A rendered page depends on the paste, the highlighting theme and possibly line-number settings; the raw text depends only on the paste. So html:{key}:{theme}:{lineNumbers} and raw:{key}. Forgetting a parameter serves the wrong variant to someone; including volatile ones (a session id) destroys the hit rate. The same rule governs CDN cache keys: make sure the CDN ignores irrelevant query parameters and cookies so ?utm_source=... does not fragment the cache.

When to update the cache.

  • Cache-aside (our default): read from cache; on a miss, read from the source, write to the cache. Simple and resilient.
  • Write-through for new pastes: the Write API also writes the new paste into the cache, which gives the creator a fast first view and sidesteps replica lag.
  • Write-behind (write-back): writing to the cache first and the database later would risk losing pastes if the cache node fails before flushing. Pastes must be durable, so we do not use it.
  • Refresh-ahead: proactively refresh entries that are about to expire if they are popular. For immutable pastes the only reason an entry expires is its cache TTL, so refresh-ahead keeps a viral paste continuously warm instead of letting it miss and stampede. Useful for the top few hundred keys.

Caching Strategies: Cache-Aside, Read-Through, Write-Through, Write-Behind explains each pattern in depth.

Eviction. LRU with a size limit is the safe default: recent, popular pastes stay. Redis's approximated LRU or LFU (allkeys-lfu) both work; LFU protects a steady popular set from being flushed by a burst of one-off reads. TTLs bound staleness and expiry. FIFO would evict a viral paste just because it was cached early. See Cache Eviction and Invalidation.

Hot keys and stampedes. A paste going viral is the classic hot key. Thousands of requests per second for one key all land on one Redis shard; and if the entry expires, hundreds of concurrent misses all go to the object store at once (a cache stampede). Defences:

  • The CDN absorbs most of it; a hot key at the origin means the CDN is missing, so check CDN cache keys first.
  • Request coalescing: the Read API (and the CDN, which most support as "collapsed forwarding" or "request coalescing") lets one request fetch a missing key while the others wait for its result.
  • In-process cache for the hottest few keys, with a TTL of seconds, so a Redis shard is not hammered.
  • Probabilistic early refresh: refresh a hot entry slightly before its TTL, at a random moment, so not every server refreshes at once.

Negative caching. Scanners and broken links request keys that do not exist. Each such request costs a database lookup. Caching "not found" for a short time (30 to 60 seconds) protects the database. Be careful with new pastes: a negative entry cached just before a key is created would hide it; with random keys that collision is essentially impossible, and the write-through of new pastes also overwrites any negative entry. Cache Failure Modes: Stampedes, Hot Keys and Penetration covers this and Bloom-filter alternatives.

If the cache fails. Reads fall back to replicas and the object store. With the CDN taking most traffic, the origin can survive a cache outage at normal load, but a viral paste plus a cache outage could overload the object-store path. Circuit breakers and request coalescing keep that bounded.

Hit-rate arithmetic. With 1,000 reads per second at peak, a 92% CDN hit rate leaves 80 per second at the origin; a 90% memory-cache hit rate there leaves 8 per second reaching the database and object store. The origin fleet is two or three small servers for redundancy, not capacity.

5. Syntax highlighting, rendering and serving user content safely#

Highlighting turns a wall of monospace text into readable code. It has three design questions: where to do it, how to know the language, and how to serve untrusted text without creating a security hole.

Where to highlight.

  • In the browser. Send raw text plus a language hint; a JavaScript library (highlight.js, Prism, or Shiki, which uses the same TextMate grammars as VS Code) colours it. The server does no work and pages are cacheable as plain text. But the user downloads a library (tens to hundreds of kilobytes, cacheable), large pastes highlight slowly on weak phones, and the page flashes uncoloured text first.
  • On the server, at read time. The Read API renders HTML with a server-side library (Pygments in Python, Chroma in Go, Shiki in Node.js, and so on). The browser gets ready-to-show HTML. Rendering a 10 KB file takes a few milliseconds; a 1 MB file can take hundreds of milliseconds to seconds, so rendering on every read would be wasteful. Cache the result.
  • On the server, at write time (pre-rendering). A background job renders the HTML right after creation and stores it (in the cache, or as a second object). Reads never pay for rendering. The cost: storage for both forms and re-rendering everything when the theme or library changes (which can be done lazily with versioned cache keys like html:v3:{key}:{theme}).

Our choice: render on the server on first read, cache the HTML in the memory cache and let the CDN cache the page; pre-render asynchronously for large pastes so the first reader does not wait; fall back to client-side highlighting for pastes over a size threshold (say 1 MB) or show them as plain text with a "highlight anyway" button. Use CSS classes rather than inline styles so themes change without re-rendering.

Knowing the language. The creator can choose it; most do not. Detection options: file-name hints (.py, Dockerfile), shebang lines (#!/usr/bin/env python3), and statistical classifiers. GitHub's Linguist uses a mix of extensions, heuristics and a Bayesian classifier; other projects use small trained models. Detection is cheap at write time, so run it then and store the result; the user can override.

Size limits. Every layer enforces limits, so no single misconfiguration lets a 2 GB body through:

  • The load balancer or reverse proxy caps request body size (for example 1 MB for the plain create endpoint; nginx's client_max_body_size).
  • The Write API checks the declared and actual size against the tier (512 KB anonymous, 10 MB logged in) and rejects with 413 Payload Too Large and a clear message.
  • Presigned upload URLs include a maximum content length, so direct uploads cannot exceed it.
  • Line count and line length limits protect the renderer: a 10 MB single-line minified file can make highlighters pathological. Over a threshold, skip highlighting.

Why limits at all, given cheap storage? They bound memory use per request (a server holding several 100 MB bodies runs out of memory), bound rendering cost, discourage use as a file-sharing or exfiltration service, and keep abuse scanning fast.

Validating encoding. Accept only valid UTF-8 and normalise line endings on display (not in storage). Reject content that is clearly binary (a high share of NUL or control bytes); a "text" pastebin that accepts binaries becomes a malware host.

Serving untrusted content safely. A paste can contain HTML and JavaScript. If the site ever renders it as HTML on the main domain, an attacker can make a paste that runs script in the reader's browser with the site's cookies: a stored cross-site scripting (XSS) attack. Defences, all of them:

  1. Escape everything. The highlighter must HTML-escape every character of the text before wrapping tokens in <span> tags. Use well-tested libraries; never build HTML by concatenating raw content.
  2. Raw text from a separate domain. /raw/{key} is served from a different registrable domain (such as pasteusercontent.example), with Content-Type: text/plain; charset=utf-8 and X-Content-Type-Options: nosniff, so the browser never sniffs it as HTML, and even if it did, there are no session cookies on that domain to steal. This is why many sites host user content on separate domains.
  3. Content Security Policy. The main site sends a strict Content-Security-Policy header (no inline scripts, scripts only from our own origin), so injected script would not run even if escaping failed somewhere.
  4. Download for risky types. For content that looks like HTML or SVG, the raw endpoint can add Content-Disposition: attachment so it downloads instead of rendering.

See Security Fundamentals for System Design for XSS and CSP in general.

6. Database choices and scaling the metadata tier#

Start: one PostgreSQL primary with read replicas. At 4 to 40 writes per second, a single primary is idle most of the time. Replicas take cache misses and analytics queries, and provide failover. With synchronous replication to one standby (or a managed service with multi-zone storage), failover loses no acknowledged pastes. This lasts a long time: a modest primary handles thousands of single-row inserts per second.

Failover. If the primary fails, a standby is promoted (managed services do this in tens of seconds). During failover, writes fail and the Write API returns 503 with Retry-After; reads keep working from replicas and caches, and pastes in the CDN are unaffected. This is why the read path does not depend on the primary. Database Replication covers primary-replica (formerly called master-slave) replication and failover.

When one primary is not enough, the classic scaling patterns apply in roughly this order:

  • SQL tuning first. Check the expiry index is used, avoid long transactions that block vacuum, batch the cleanup deletes, and keep table bloat under control. Most "the database is slow" problems are fixed here.
  • Federation (functional partitioning). Split by function: accounts and billing in one database, paste metadata in another, abuse reports in a third. Each is smaller and can be scaled independently. Cross-database joins become application work, but this system rarely needs them.
  • Sharding by key. Hash the paste key to pick a shard. Random keys spread evenly; every read and write touches one shard. The expiry sweep runs per shard; "my pastes" needs either a per-owner index table or scatter-gather across shards, so many designs keep owner listings in a separate table sharded by owner. Partitioning and Sharding covers the trade-offs.
  • Denormalisation. Store what the read path needs in one row (visibility, language, size, content reference, expiry, owner display name), so a read is one lookup with no joins. Already the case in our schema.

Or move metadata to NoSQL. A key-value store fits the dominant access pattern (get by key) perfectly. A key-value store (DynamoDB, Redis with persistence, Riak historically) gives single-digit-millisecond lookups at any scale with little operations work. A document store (MongoDB, Couchbase) lets metadata and small content live in one document with secondary indexes. A wide-column store (Cassandra, ScyllaDB, Bigtable) excels at write-heavy, time-ordered data, which fits the view-event log better than paste metadata. A graph database has no role here; there are no relationships worth traversing. The main loss moving to NoSQL is flexible secondary indexes and ad hoc queries for moderation and support. Amazon DynamoDB in Practice and PostgreSQL in Practice describe each side.

A sketch of the same model in DynamoDB. Partition key paste_key; attributes as in the SQL table; the built-in TTL attribute set to expires_at as epoch seconds; a global secondary index on owner_id and created_at for "my pastes". Expired items disappear within days by themselves, and a stream of deletion events triggers object deletion. Reads still check expiry. It is a credible choice, especially for a team already on AWS.

Choosing. At this scale the honest answer is that both work and the deciding factors are familiarity, the expiry index, ad hoc queries for moderation, and cost. We start relational because moderation and support want SQL, and because a single primary will last for years.

7. Analytics: counting views when the CDN serves most of them#

The requirement is modest: monthly view counts per paste, shown to owners, not real-time. The interesting part is getting the inputs right and choosing the cheapest processing that meets the freshness need.

Where views are observed. If the CDN serves 90% of reads, the Read API sees only 10%. Three ways to see all views:

  1. CDN access logs. Every major CDN can ship access logs (request URL, time, status, client IP or a hashed form, user agent, referrer, cache status) to object storage or a log stream, typically within minutes. Combined with the Read API's own logs, they capture every view. Our choice.
  2. A beacon. The paste page fires a small uncacheable request (POST /v/aZ3kQ9xR) after loading. It counts views by real browsers that run JavaScript, which naturally excludes many bots, but misses raw-text fetches by tools and curl, and is blocked by some privacy extensions.
  3. Make pages uncacheable. Defeats the purpose of the CDN. No.

Batch processing (our choice). Logs land in object storage in hourly folders. A batch job runs hourly (or daily) and computes counts. This is a textbook MapReduce: the map step parses each line, drops non-paste URLs, error responses and known bots, and emits ((month, key), 1); the reduce step sums the values per key. The output goes into an analytics table that the stats API reads.

# MapReduce view counter (mrjob-style). Input: one access-log line per view.
class MonthlyPasteViews(MRJob):
    def mapper(self, _, line):
        rec = parse_log_line(line)           # url, time, status, ua, client hash
        if rec is None or rec.status != 200 or is_bot(rec.ua):
            return
        key = paste_key_from_url(rec.url)    # None for static assets, API, etc.
        if key:
            yield (rec.time.strftime("%Y-%m"), key), 1
 
    def combiner(self, month_key, counts):   # pre-sum on each mapper
        yield month_key, sum(counts)
 
    def reducer(self, month_key, counts):
        yield month_key, sum(counts)         # e.g. ("2026-11", "aZ3kQ9xR"), 1840

In practice the same job is often a SQL query in a warehouse (BigQuery, Redshift, Snowflake, ClickHouse) over external tables pointing at the log files:

SELECT date_trunc('month', ts)         AS month,
       paste_key,
       count(*)                        AS views,
       approx_count_distinct(client_hash) AS unique_visitors
FROM   access_logs
WHERE  status = 200 AND NOT is_bot AND paste_key IS NOT NULL
  AND  ts >= '2026-11-01' AND ts < '2026-12-01'
GROUP  BY 1, 2;

How much data? At 1 billion reads a month at scale and about 300 bytes per log line, that is 300 GB of logs a month, about 400 MB an hour. An hourly job over 400 MB is small: one machine could do it; a warehouse does it in seconds. Spark or a warehouse is still a sensible choice for growth and familiarity, not necessity.

Unique visitors. Counting distinct visitors exactly needs a set of all visitor ids per paste per month, which is wasteful for popular pastes. HyperLogLog estimates distinct counts with about 1 to 2% error using a few kilobytes per counter regardless of cardinality, and counters merge (the union of hourly sketches is the monthly sketch). Warehouses expose it as approx_count_distinct; Redis has PFADD and PFCOUNT. Visitor identity is a hash of IP and user agent with a monthly rotating salt, so we can count uniques without storing raw IPs. See Probabilistic Data Structures for Big Data.

Bots. A large share of traffic to a public paste site is automated: search crawlers, link-preview fetchers in chat apps, security researchers' scrapers, and scanners. Counting them inflates numbers. Filter by user agent (known crawlers identify themselves), by behaviour (many keys per minute from one client), by whether the page's beacon fired, and by known data-centre IP ranges. Record both raw and filtered counts.

Deduplication. Reloads and retries should not count as many views. Option: count at most one view per visitor per paste per hour. A more robust variant, borrowed from ad-click counting, issues each rendered page a view token (a random id signed with an HMAC by the server so it cannot be forged) that the beacon returns; the counter accepts each token once. HMAC verification takes microseconds. For monthly stats on a pastebin, per-visitor-per-hour dedup is usually enough; signed tokens matter when counts have money attached.

Store and serve. The batch writes rows (paste_key, month, views, unique_visitors) into a small table (or the warehouse itself). The stats API reads one row. Because stats are pre-aggregated, owner queries are instant; this is the general pattern of a separate analytics store fed by batch processing, so that heavy aggregation never touches the serving database. If owners later want daily or all-time numbers, keep daily rows and roll them up into monthly and yearly tables with a nightly job.

Streaming, if requirements change. If owners wanted live counters, the logs would go to Kafka and a stream processor (Flink, or a simple consumer) would increment counters per key per minute in Redis or an OLAP store, with the batch job kept as the correct, reconciled source. That is the classic "speed layer plus batch layer" design. Not needed here, and much more machinery. Batch vs Stream Processing and Data Pipelines, Warehouses and Lakes compare the approaches.

Privacy. Access logs contain IP addresses and user agents, which are personal data in many jurisdictions. Keep raw logs for a short period (30 to 90 days), hash or truncate IPs early, and keep only aggregates long term.

8. Abuse, rate limits and takedowns#

Every public paste site is used for things its builders did not intend. Security researchers have long documented paste sites being used to publish stolen credentials and database dumps, to host malware payloads and command lists fetched by infected machines, to share phishing kits, and to post spam links for search engines. Abuse control is therefore a core requirement, not an extra.

Rate limits. The cheapest defence, applied in layers:

  • At the edge (CDN or WAF): coarse per-IP limits on creates (for example 10 per minute) and on 404s (scanning), plus blocks of known bad networks.
  • In the Write API: per-identity token buckets. Anonymous users keyed by IP (and by a device cookie), with low limits; logged-in users keyed by account, with higher limits; API keys for automation with their own quotas. Counters live in Redis and are updated atomically.
  • On reads: generous limits per IP for normal reads, strict limits for clients generating many 404s or fetching thousands of distinct keys per hour (scrapers and scanners).

When a limit is hit, respond fast with 429 Too Many Requests, Retry-After, and X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset, so honest scripts back off correctly. IP-based limits misfire behind large NATs (a university or mobile carrier shares one IP among thousands), so combine IP with other signals and give logged-in users their own budget. Rate Limiting and Throttling covers the algorithms (token bucket, sliding window); a dedicated limiter service is designed in the rate limiter case study.

Friction for anonymous creation. A CAPTCHA or a proof-of-work challenge shown only when a client looks suspicious (new IP, high rate, content similar to recent spam) stops most scripts without bothering normal users.

Content scanning. Two stages:

  1. Synchronous, fast (milliseconds), on create. Size and encoding checks; blocklists of URLs and domains (spam and phishing); signatures of known malware encodings (long base64 blobs of executables, known script droppers); rate of near-identical pastes from one source. Clear hits are rejected.
  2. Asynchronous, slower, after create. Deeper malware analysis, secret detection (patterns for API keys, private keys and passwords, which can trigger warnings to the creator or notifications to the issuer: GitHub's secret scanning partner programme notifies providers such as cloud vendors when their tokens appear in public repositories), credential-dump detection (many lines of email:password), and machine-learned spam classifiers. Hits are hidden pending review or taken down.

Reporting and takedown. Anyone can report a paste. Reports go into a moderation queue, prioritised by reason and by the paste's traffic. Takedown sets status = taken_down (so the read path returns 451 or 404), purges CDN and memory caches, and keeps the content under legal hold for a period if required (for law-enforcement requests) before deletion. Copyright notices (such as DMCA notices in the United States) follow a documented process. An audit log records every moderation action.

Search engines. Public pastes may be indexed; unlisted ones must not be. Send X-Robots-Tag: noindex on unlisted pages and never list them in sitemaps or "recent pastes" pages. Even public pastes are often worth noindex until they have been scanned, so spam does not gain search ranking.

Scanning versus privacy. Scanning content conflicts with users' expectation that unlisted pastes are private. Be transparent in the terms of service, scan automatically rather than with humans where possible, and offer client-side encrypted pastes (Deep Dive 10), which the service cannot scan and therefore treats with stricter rate limits and size caps.

9. Asynchronous work, services and communication#

Several jobs in this design should not happen while the user waits: deep abuse scans, pre-rendering highlighted HTML for large pastes, language detection for big files, deleting expired content, purging CDNs, and computing analytics. Doing them inline would add seconds to creates and couple the user experience to slow, failure-prone steps.

Task queue. The Write API publishes a small message per job ({"type": "scan", "key": "aZ3kQ9xR"}) to a queue: Amazon SQS, RabbitMQ, a Redis-backed queue (Sidekiq, Celery, BullMQ), or Kafka if the team already runs it. Workers consume jobs, do the work, and acknowledge. Properties that matter:

  • At-least-once delivery. A worker may crash after doing the work but before acknowledging, so the job runs again. Every job must be idempotent: scanning twice is harmless; "delete object" on an already-deleted object succeeds; "increment view count" is not idempotent, which is one reason analytics are computed in batch from logs instead.
  • Retries with backoff and a dead-letter queue. A job that fails repeatedly (a malformed paste that crashes the highlighter) moves to a dead-letter queue for inspection instead of blocking others.
  • Back pressure. If workers fall behind (a spam wave triples creates), the queue grows. The queue absorbs the burst; monitoring alerts on queue age; and if it keeps growing, the Write API can slow down or reject anonymous creates (429) rather than accept work the system cannot process, which is the essence of back pressure. Bounded queues and admission control are better than unbounded growth that eventually exhausts memory or delays scans by hours.

Asynchronous Processing and Message Queues covers queue semantics, delivery guarantees and back pressure in depth.

Message queue versus task queue. A message queue (or log) moves events between services ("paste created"); a task queue schedules units of work for workers ("scan paste X"), often with retries, delays and priorities built in. Here a task queue fits: jobs are independent, and we want retries and dead-letter handling. If several consumers want the same "paste created" event (scanner, search indexer, analytics), a publish/subscribe topic with one subscription per consumer is cleaner.

Monolith or microservices? The whole application (Write API, Read API, highlighter) could be one deployable service with background workers, and for a small team that is the right start: one codebase, one deploy, simple debugging. Reasons to split later are concrete: the Read API needs to scale and deploy independently of the Write API; the highlighter is CPU-heavy and benefits from its own pool; the abuse scanner has different owners and release cycles. Splitting adds network calls, versioned APIs between services, distributed tracing needs and more operations. Monolith vs Microservices discusses when the split pays.

Communication. External clients use REST over HTTPS: universal, cacheable by URL, easy for curl and scripts. Internal calls (Read API to highlighter, workers to a metadata service) can use RPC such as gRPC: typed schemas, efficient binary encoding, streaming and deadlines built in. Internal REST is also fine; the important choices are timeouts, retries with backoff and idempotency, whichever protocol is used.

Service discovery. With several services and autoscaled instances, callers need to find healthy instances: DNS-based discovery, a load balancer per service, a registry such as Consul or etcd, or the platform's built-in discovery (Kubernetes services). Health checks remove failed instances automatically. Microservices Infrastructure Patterns covers discovery, gateways and service meshes.

10. Privacy and security: visibility, deletion tokens and client-side encryption#

Visibility levels.

  • Public: listed in "recent pastes" and indexable (after scanning). Anyone can find it.
  • Unlisted: reachable only by link. Protected only by key unguessability (Deep Dive 1). Must be marked noindex, excluded from listings, and served with a referrer policy so the URL does not leak to third-party sites through the Referer header when a reader clicks an outbound link (Referrer-Policy: no-referrer or same-origin).
  • Private: visible only to the logged-in owner (and people they share with). The Read API checks the session; CDN caching must be disabled or keyed per user (simplest: Cache-Control: private, no-store).

Delete tokens for anonymous users. An anonymous creator gets a random 128-bit token in the create response. We store only its SHA-256 hash; deletion requires presenting the token, which we hash and compare in constant time. A database leak then does not reveal tokens. The same idea protects any bearer secret: store hashes, not secrets.

Password-protected pastes. The creator sets a password; the server stores a slow hash (Argon2 or bcrypt) and requires the password to view. Better than nothing, but the server still sees and stores plaintext content.

Client-side (end-to-end) encryption. The strongest option, used by PrivateBin and similar "zero-knowledge" pastebins: the browser generates a random key, encrypts the text with AES-GCM in JavaScript, uploads only the ciphertext, and puts the key in the URL fragment (paste.example/aZ3k...#key). Browsers never send the fragment to the server, so the server stores data it cannot read. Readers' browsers take the key from the fragment and decrypt locally.

Trade-offs:

  • The server cannot scan, highlight server-side, detect language or deduplicate encrypted pastes; all rendering is client-side.
  • Security depends on the JavaScript served by the site; a compromised server could serve code that leaks keys. Subresource integrity and a published, auditable client help.
  • Losing the link means losing the paste; there is no recovery.
  • Abuse handling is harder, so encrypted pastes get stricter rate limits, size caps and shorter maximum expiry.
create (browser):
    key        = randomBytes(32)                  # AES-256 key, never sent to server
    iv         = randomBytes(12)
    ciphertext = AES_GCM_encrypt(key, iv, utf8(text))
    id         = POST /api/v1/pastes { content: base64(iv + ciphertext), encrypted: true }
    url        = "https://paste.example/" + id + "#" + base64url(key)
 
view (browser):
    key  = base64url_decode(location.hash[1:])    # fragment stays in the browser
    blob = GET /api/v1/pastes/{id}
    text = AES_GCM_decrypt(key, blob.iv, blob.ciphertext)   # fails if tampered

Transport and headers. HTTPS everywhere with HSTS; secure, HTTP-only, same-site cookies for logged-in sessions; CSRF protection on state-changing endpoints (delete, report); strict CSP on the main domain. Logged-in accounts use standard authentication with optional multi-factor; see Authentication and Authorization.

Secrets pasted by mistake. Developers often paste logs containing API keys or passwords. Warn on create when patterns look like secrets ("this looks like an AWS access key; consider removing it"), default to short expiry for such pastes, and for public pastes consider notifying token issuers where programmes exist.

11. Availability, multi-region and disaster recovery#

The availability target was 99.9 % for reads and creates, with reads mattering more: a link posted in a chat that returns an error is the visible failure. The read path has several layers of protection.

CDN serve-stale. Configure stale-if-error and stale-while-revalidate so the CDN keeps serving its cached copy when the origin returns 5xx or times out. Popular pastes stay readable even during a full origin outage. For an immutable paste (content never changes, only expiry or takedown), serving stale is nearly always safe; the one risk is serving a paste that was taken down during the outage, which we accept and fix with a purge on recovery.

Read-only degraded mode. If the metadata primary fails, replicas still serve reads. The Write API returns 503 with Retry-After and a clear message while failover completes, rather than queueing writes it cannot guarantee. Reads keep working. Which features can be turned off under stress (analytics beacons, highlighting of large pastes, recent-pastes listing) should be decided in advance and controlled by feature flags.

Database failover. A managed relational database with a synchronous standby in a second availability zone (Amazon RDS Multi-AZ, Cloud SQL HA, or Patroni for self-managed PostgreSQL) fails over in roughly 30 seconds to two minutes, depending on the product and on DNS or proxy updates. Applications must reconnect and retry idempotently. Active-passive failover with a synchronous standby loses no committed data. Active-active (two writable primaries) is unnecessary for a pastebin and adds conflict handling we do not need.

Object storage durability and replication. S3 and similar services are designed for very high durability within a region (AWS states eleven nines of designed durability for S3 Standard). Cross-region replication protects against a regional disaster and lets a second region serve reads. Replication is asynchronous, typically completing within seconds to minutes, so a paste created moments before a regional failure might be missing in the other region; we accept that small window.

Multi-region. A sensible progression:

  1. Single region, multi-AZ. Enough for 99.9 %. Cheapest.
  2. Warm standby region. Replicated database (asynchronous replica) and object storage in a second region; infrastructure defined as code so the stack can be brought up quickly. Recovery time objective (RTO, how long until service returns) of tens of minutes; recovery point objective (RPO, how much recent data can be lost) of seconds to minutes.
  3. Active-active reads. Both regions serve reads from local replicas and replicated objects; writes go to one primary region. Readers anywhere get local latency, though the CDN already gives most of that.

Because creates are rare and reads are cacheable, step 2 is usually the right stopping point. Multi-Region and Global Data covers the active-active options.

Backups. Replication is not a backup: an accidental DELETE or a bad migration replicates instantly. Keep point-in-time recovery for the database (continuous WAL archiving, 7–35 days), versioning or object lock on the bucket for a short window so deletes can be undone, and periodic restore drills to prove backups work. Backups of deleted pastes must expire too, or "deleted" is not really deleted; document the backup retention window in the privacy policy. See Disaster Recovery and Backups.

Availability maths. With a CDN (say 99.99 %), a load balancer (99.99 %), the Read API fleet (99.95 %), metadata database (99.95 %) and object storage (99.99 %) in series, the uncached read path is about 0.9999 × 0.9999 × 0.9995 × 0.9995 × 0.9999 ≈ 99.87 %. That is below 99.9 % on paper, which shows why the cache layers matter: a CDN hit depends only on the CDN, and serve-stale turns many origin failures into successes. Redundancy within each layer (several API instances, a standby database) is what makes the component numbers high in the first place. Designing for High Availability works through these calculations.

Timeouts, retries and circuit breakers. The Read API calls the database, cache and object store. Each call needs a timeout (for example 50 ms for cache, 200 ms for database, 500 ms for object storage), a bounded retry with jitter for idempotent reads, and a circuit breaker so that a slow object store does not tie up every thread. If the cache is down, fall back to the database but protect it with a concurrency limit; otherwise a cache outage becomes a database outage. See Resilience Patterns: Timeouts, Retries and Circuit Breakers.

12. Scaling iteratively: from one server to the final design#

Interviewers often ask how you would get from day one to the final design. The answer is a loop, not a leap: benchmark and load test, profile to find the bottleneck, fix it, and repeat.

Stage 0: one server. A single VM runs the web app and PostgreSQL, and stores content in the database. At 4 writes/s and 40 reads/s this is plenty; a modest server handles hundreds of simple queries per second. Problems: no redundancy, and the database grows with content.

Stage 1: separate concerns. Move content to object storage, metadata to a managed database with a standby, and put the app behind a load balancer with two or more stateless instances. Sessions live in a cookie or in Redis, not in instance memory. Now any instance can fail without losing state.

Stage 2: cache the reads. Add a CDN in front of rendered pages and raw content, and Redis for metadata and small contents. Most reads no longer reach the origin. Measure: if the hit rate is 90 %, origin traffic drops tenfold.

Stage 3: read replicas and async workers. If metadata reads that miss the cache still load the primary, add read replicas. Move scanning, highlighting of large pastes and cleanup onto queues and workers so creates stay fast.

Stage 4: split and shard only when measured. Separate Read and Write APIs if their scaling or deploy needs diverge. Shard the metadata database (by hashing the paste key) only when one primary cannot handle the write rate or the dataset, which for this workload is years away; 360 million rows of metadata at a few hundred bytes each is about 100–200 GB, comfortably on one well-provisioned PostgreSQL instance.

How to find the next bottleneck.

  • Load test with realistic traffic: a mix of creates and reads that follows the expected distribution, with a long tail of cold pastes and a few hot ones. Tools such as k6, Locust, Gatling or JMeter can generate it. Ramp until latency or error rate breaks the target, and note which resource saturated first. Capacity Planning and Load Testing explains methodology.
  • Profile what is slow: database slow-query logs and EXPLAIN ANALYZE, CPU profiles of the highlighter, connection pool saturation, cache hit ratio, object store latency percentiles.
  • Observe in production with metrics (request rate, error rate, latency percentiles per endpoint), logs and traces so a slow request can be followed from CDN to database. See Observability: Logs, Metrics and Traces.

Latency numbers to keep in mind (order of magnitude): reading from memory is about 100 ns; a Redis round trip within a data centre is about 0.2–1 ms; a simple indexed PostgreSQL query is about 1–5 ms; a small object GET from S3 is often 10–50 ms for the first byte; a round trip between continents is 100–200 ms. That is why the CDN matters: a reader in Sydney fetching from a US origin pays about 200 ms per round trip, but a CDN edge in Sydney answers in a few milliseconds. Numbers Every Engineer Should Know has the full table.

Worked example. A load test at 1,000 reads/s with a cold cache shows p99 latency of 180 ms, and traces show 150 ms waiting on object storage. Fixes in order of cost: inline pastes under 4 KB in the metadata row (most pastes, so most object GETs vanish); cache contents up to 64 KB in Redis; raise the CDN TTL for pastes without expiry. Re-run: p99 drops to about 30 ms for cache hits, and object storage requests fall by about 80 %. The next bottleneck becomes database connections at higher load, which a connection pooler such as PgBouncer fixes. Each step was chosen from data, not guessed.

Bottlenecks and Failure Modes#

Failure / hotspotImpactMitigation
A paste goes viral (linked from a big news site or forum)Thousands of reads per second for one key; cache shard and origin overloaded on missesCDN caching with long TTL for immutable content; request coalescing at the CDN and in the Read API; local in-process cache for the hottest keys; serve-stale on origin errors
Cache cluster outageEvery read falls through to the database and object store; possible cascadeConcurrency limits and circuit breakers on database calls; CDN still absorbs most traffic; replicated Redis with automatic failover; warm the cache gradually after recovery
Metadata primary failureCreates and deletes fail; reads continue from replicas and cachesSynchronous standby in another zone with automatic failover; read-only degraded mode with 503 and Retry-After for writes; idempotency keys make client retries safe
Object store latency spike or regional incidentSlow or failed reads for uncached large pastesInline small pastes in the metadata row; Redis cache for medium sizes; timeouts and circuit breakers; cross-region replica to fail reads over
Key collision or exhaustionA create overwrites another paste or keeps retryingRandom 8-character keys with an insert-if-absent constraint and retry; monitor retry rate; lengthen keys when the space fills beyond a few percent
Enumeration and scraping of unlisted pastesPrivate-by-link content leaksUnguessable random keys (no counters); rate limits per IP on 404s; no listing of unlisted pastes; noindex; client-side encryption option for sensitive data
Spam and malware wavesStorage grows, domain gets blocklisted by browsers and email filtersLayered rate limits; CAPTCHA or proof of work for anonymous creates; sync and async scanning; fast takedown with CDN purge; separate raw-content domain
Expiry backlog (cleanup job falls behind)Expired pastes still occupy storage; possible privacy complaintsLazy expiry check on every read so expired pastes are never served; partitioned or indexed cleanup in small batches; bucket lifecycle rules as a backstop; alert on backlog age
Large uploads saturating API serversMemory and bandwidth exhaustion on the Write APISize cap (for example 10 MB) with 413; presigned direct upload to object storage for large pastes; streaming bodies instead of buffering
Syntax highlighting of huge or pathological inputCPU spikes; slow page loads; regex catastrophic backtrackingClient-side highlighting by default; server-side size limit and timeout; skip highlighting above a threshold; separate worker pool for pre-rendering
Analytics writes on the read pathHot rows on view_count; read latency coupled to analyticsCount from CDN and access logs in batch, or from an asynchronous event stream; never update a counter row synchronously per view
Burn-after-read race (two readers at once)Content shown twice, or never shownSingle atomic UPDATE ... WHERE burned = false RETURNING claims the paste; never cache burn-after-read pastes at the CDN

What Interviewers Expect#

Mid-level. A clear set of functional requirements (create, view, expiry, optional accounts) and the read-heavy nature of the workload. A sensible API with correct status codes. Generating random keys with a uniqueness check, and explaining why sequential IDs are guessable. Storing content in object storage and metadata in a relational database, with a cache in front of reads. A basic expiry approach (check on read plus a cleanup job). The candidate should do simple capacity maths: writes per second, reads per second, storage per year, and conclude the system is small enough that a single database works for a long time.

Senior. Everything above with sharper trade-offs. Key-space and collision maths (birthday bound) to justify key length; inline tiny pastes versus object storage with measured thresholds; deduplication and its privacy implications. A complete caching story: CDN with immutable content, cache TTLs bounded by expiry, negative caching, hot-key and stampede handling. Expiry that is correct (never serve expired) and efficient (batched deletes, lifecycle rules, CDN purge ordering). Burn-after-read done atomically. XSS defences for user content (escaping, raw domain, CSP, nosniff). Analytics kept off the read path. Abuse controls: rate limits, scanning and takedown with appropriate status codes. Database scaling options described with the reasons not to shard yet.

Staff and above. The ability to reason about the system as a product with real risks. Abuse and legal obligations (takedowns, secrets pasted by mistake, malware hosting) as first-class design drivers, including domain reputation. Privacy architecture: client-side encryption and its effect on scanning, dedup and support; backup retention that honours deletion. Availability engineering: serve-stale, degraded modes, the availability maths that shows why caches matter, a warm-standby region with stated RTO and RPO. Cost thinking: CDN egress versus origin, object storage classes for cold pastes, lifecycle tiering. A staged evolution plan driven by load tests and profiling instead of building for imagined scale on day one, with clear signals for each next step (replica lag, CPU, connection saturation, storage growth). Comfort saying "we do not need microservices or sharding here yet, and here is what would change my mind."

Deep Dive: How real paste services differShow

Several well-known services solve the same problem with very different priorities. These descriptions stay at the level of publicly documented behaviour; internal details of commercial services are not public.

Pastebin.com. One of the oldest and best-known paste sites, it offers public, unlisted and private pastes, expiry options, syntax highlighting for many languages, accounts and an API for scripts. Its scale and long history mean abuse handling (leaked credentials, spam, malicious content) is a large part of running it, which is why the abuse layer in this design is not optional.

GitHub Gist. Every gist is a git repository. That gives version history, forks, comments, multiple files per gist and cloning with ordinary git commands. The design choice is different from ours: content is versioned and mutable, not write-once. Storage is git objects (content-addressed by hash, so identical files deduplicate naturally) rather than one blob per paste. Gists can be public or "secret"; secret gists are unlisted, not private, so anyone with the URL can read them. That is exactly the unlisted-by-link model and its limitation.

PrivateBin (a fork of ZeroBin). An open-source, self-hostable, "zero-knowledge" pastebin. The browser encrypts the content with AES-256-GCM before upload and puts the key in the URL fragment, as described in Deep Dive 10. The server stores only ciphertext and can use simple backends (filesystem, a relational database, or object storage). Features such as burn-after-reading, expiry and discussion threads all work without the server seeing plaintext. The trade-off is that server-side scanning, search and highlighting are impossible.

Hastebin (haste-server). An open-source, minimal pastebin written in Node.js. It focuses on speed and keyboard-driven use, uses short random or phonetic keys (easier to read aloud), and supports pluggable storage backends such as the filesystem, Redis and others. It shows how small the core of a pastebin can be: a key generator, a key-value store and a static front end.

What to take from the comparison.

Design choiceOur designGistPrivateBinHastebin
MutabilityWrite-once (delete allowed)Versioned, editableWrite-onceWrite-once
StorageMetadata DB + object storeGit repositoriesPluggable, ciphertext onlyPluggable key-value
Server can read contentYesYesNoYes
Abuse scanningYesYesNot possible on contentMinimal
Best forPublic sharing at scaleCode with historySensitive snippetsQuick self-hosted sharing

In an interview, naming one or two of these and the trade-off they represent (versioning versus write-once, server-readable versus end-to-end encrypted) shows you understand that the "right" pastebin depends on the product.

Deep Dive: Pastebin versus URL shortenerShow

The two problems are usually taught together because both map a short key to stored data. The differences change the design.

AspectURL shortenerPastebin
Value sizeAbout 100 bytes to 2 KB (a URL)Bytes to megabytes (text)
Where the value livesAlways in the database rowSmall values inline; large values in object storage
Read responseA 301 or 302 redirect, tinyA full page or raw file, can be large
CachingRedirects cache well; 301 is cached by browsers foreverRendered pages and raw bytes cache at the CDN; content is immutable
AnalyticsClick tracking is often the business (302 to count clicks)Views are a nice-to-have, computed in batch
Security riskPhishing redirects to malicious sitesHosting malicious content, leaked secrets, XSS through rendered text
Key choiceSometimes custom aliases; short keys matter for typingUnguessability matters more, because unlisted pastes rely on it
ExpiryOptional, rareCommon and central (10 minutes, 1 day, burn-after-read)
Storage growthSmall: billions of rows fit in a few TBDominated by content size; lifecycle and tiering matter

So the shared core (key generation, a key-value lookup, read-heavy caching) is the same, but a pastebin adds blob storage, rendering safety, expiry machinery and a bigger abuse surface. If an interviewer asks you to "do Pastebin" after a URL shortener, reuse the key generation and caching and spend the time on content storage, expiry and XSS.

Deep Dive: What changes at 100 times the scaleShow

Suppose the service becomes a major platform: 400 creates per second on average (peaks of 2,000), 40,000 reads per second (peaks of 200,000), and a mean paste of 10 KB.

Storage. 400 × 86,400 ≈ 35 million pastes per day, about 345 GB of content per day before compression, or roughly 125 TB per year. Compression at about 3–4× for text brings it to about 35–40 TB per year. Object storage handles this easily, but cost now matters: moving pastes not read in 90 days to an infrequent-access class can cut storage cost substantially, at the price of a per-GB retrieval fee. Lifecycle rules do this automatically.

Metadata. About 12.6 billion rows per year. At around 200 bytes per row plus indexes, that is several TB per year. Now a single primary becomes uncomfortable for writes and storage, and sharding by hash of the paste key is justified. Hash-based sharding spreads writes evenly, every read is a single-shard lookup by key, and the only cross-shard query is "list my pastes", which can use a secondary table keyed by owner (or a global secondary index in DynamoDB). Alternatively, move metadata to a key-value store designed for this access pattern, such as DynamoDB or Cassandra, with TTL support for expiry.

Reads. 200,000 peak reads per second at a 95 % CDN hit rate still sends 10,000 requests per second to origin. A Redis cluster with a few shards and replicas handles that; the database sees only cache misses. Hot keys need explicit handling (local caches and request coalescing), because a single viral paste can exceed one Redis shard's capacity of roughly 100,000 simple operations per second.

Key length. 12.6 billion keys per year rules out 7 characters (62^7 ≈ 3.5 trillion, but unguessability suffers as it fills) and makes 8 characters (about 218 trillion) the minimum. Many designs move to 10 or more characters at this scale for a large safety margin against scanning.

Abuse. Abuse scales faster than legitimate use. Dedicated trust-and-safety tooling, machine-learning classifiers on content, reputation scores for IP ranges and accounts, and a review queue staffed by people become necessary.

Analytics. Billions of view events per day call for a stream processor and a columnar warehouse; batch jobs over CDN logs still work but may run hourly instead of daily.

The point of the exercise: the architecture shape barely changes (CDN, cache, metadata store, object storage, async workers). What changes is sharding, storage tiering, key length and the size of the abuse operation.

Deep Dive: Running the service: SLOs, dashboards and alertsShow

A design is only finished when you can tell whether it is working. For a pastebin, a handful of service level objectives (SLOs, targets for what users experience) cover almost everything:

SLOTargetMeasured where
View availability99.9 % of GET /{key} return a non-5xx response per 30 daysCDN logs (what users actually saw)
View latencyp99 under 200 ms at the edge, p99 under 100 ms at originCDN and Read API metrics
Create availability99.9 % of valid creates succeedWrite API metrics
Expiry correctness0 expired pastes served after their expires_atSynthetic probe that creates 10-minute pastes and checks them at 11 minutes
Takedown speed95 % of confirmed takedowns unreachable within 15 minutesAbuse tooling timestamps plus probe

The 99.9 % target leaves an error budget of about 43 minutes of failure per 30 days. If a bad deploy burns half of it, the team slows releases and fixes reliability first; if the budget is healthy, they ship faster. This makes the availability target a tool for decisions, not just a number.

Dashboards should follow the request path: CDN hit ratio and origin request rate; Read API rate, errors and latency percentiles; cache hit ratio, memory and evictions; database queries per second, replica lag and connection pool use; object store latency and errors; queue depth and oldest message age for scan and cleanup jobs; storage growth per day.

Alerts should fire on user-visible symptoms, not on every internal metric: the SLO burn rate (errors consuming budget too fast), p99 latency over target for 10 minutes, cleanup backlog older than a few hours, scan queue age over 15 minutes (abuse could go unchecked), and a sudden spike in creates from a small number of IP ranges. Causes such as high CPU on one instance belong on dashboards, because autoscaling and redundancy usually absorb them.

Synthetic probes close the gaps that logs cannot: every minute, from several regions, create a paste, read it through the CDN, read the raw URL, delete it, and confirm 404. A probe that creates a burn-after-read paste and reads it twice checks the atomic claim. These probes catch broken deploys before users do.

Runbooks for the common incidents (viral paste, cache outage, database failover, spam wave, takedown request) make on-call faster and safer. After each incident, a blameless postmortem records what happened and which change prevents it next time; see Incident Management and Postmortems.

Deep Dive: A 45-minute interview planShow

Minutes 0–5: clarify. Who uses it (anonymous and logged-in), maximum paste size, expiry options, visibility levels, analytics needs, whether edits are allowed. Agree that pastes are write-once and the system is read-heavy.

Minutes 5–10: estimate. Writes and reads per second, average and maximum sizes, storage per year, key space needed. Conclude: small write load, moderate read load, storage dominated by content, key length of 8 characters.

Minutes 10–15: API and entities. POST /pastes, GET /pastes/{key}, GET /raw/{key}, DELETE /pastes/{key} with a delete token. Paste metadata and content as separate concepts. Status codes: 201, 404, 410, 413, 429.

Minutes 15–25: high-level design. Client, CDN, load balancer, Write API and Read API, metadata database, object storage, cache, async workers for scanning and cleanup. Walk through create and view flows.

Minutes 25–40: deep dives (pick two or three). Key generation and collision maths; storage choice and inlining; expiry correctness and cleanup; caching with CDN and hot keys; XSS and the raw domain; abuse controls; analytics off the read path. Let the interviewer steer.

Minutes 40–45: wrap up. Failure modes (cache outage, database failover, viral paste), monitoring, and how the design would evolve with scale.

Common mistakes: storing large blobs in the database without discussing it; sequential IDs; forgetting expiry correctness; caching without bounding TTL by expiry; rendering user text without escaping; synchronous view counters; over-engineering with sharding and microservices at 4 writes per second.

Deep Dive: Follow-up questions and strong answersShow

"How would you support editing pastes?" Make content versioned: each edit writes a new content blob and a new version row; the paste key points to the latest version. Old versions can be kept (like Gist) or garbage-collected. CDN caching must switch from "immutable forever" to versioned URLs (/raw/{key}/{version}) or short TTLs with purges on edit.

"How do you search public pastes?" Index public, scanned pastes asynchronously in a search engine such as Elasticsearch or OpenSearch, fed from a "paste created" event. Never index unlisted or private pastes. Expired or deleted pastes must be removed from the index too, as part of the same cleanup flow.

"Can users choose custom keys?" Yes, with a uniqueness check, a reserved-word list, profanity and impersonation filters, and a longer minimum length for anonymous users. Custom keys are guessable by design, so they must not be offered for unlisted pastes, or the user must be warned.

"How would you guarantee a paste is really gone after deletion?" Delete the metadata row first (so reads return 404 or 410 immediately), purge the CDN, delete cached copies, then delete or dereference the content blob. Backups expire on a documented schedule. With deduplication, only delete the blob when its reference count reaches zero.

"What if the cleanup job deletes the wrong things?" Make the job idempotent and conservative: select by expires_at < now() - grace_period, delete in small batches, log every key deleted, and keep object versioning for a few days so mistakes can be reversed. Run it against a dry-run mode first after any change.

"How would you rate-limit fairly behind NATs and proxies?" Combine signals: per-IP limits with higher thresholds for known shared ranges, per-account limits for logged-in users, proof of work or CAPTCHA when limits approach, and reputation scores. Use the client IP from a trusted proxy header only when it is set by your own edge.

"Why not put everything in DynamoDB?" You can: metadata keyed by paste key, small content inline (items are limited to 400 KB), large content in S3, native TTL for expiry. It removes database operations work and scales without manual sharding. The trade-offs are less flexible querying ("my pastes" needs a GSI), TTL deletion that is eventual (typically within a few days, so lazy expiry checks are still required), and cost at high read rates without caching.

"How do you handle a takedown request for content that is cached at the CDN?" Mark the paste as removed in metadata (reads return 451 or 410), invalidate caches, issue a CDN purge, and confirm with a probe request. Record the request and action for legal audit.

Key Takeaways#

  • A pastebin maps a short, unguessable key to stored text. The workload is small for writes and read-heavy, so the design is about cheap storage and very good caching.
  • Use random keys of 8 or more base62 characters with an insert-if-absent check; sequential or hash-derived keys are guessable or collide. Do the birthday maths to justify the length.
  • Store metadata in a relational database and content in object storage; inline tiny pastes in the row. Compression and content-hash deduplication cut storage further.
  • Expiry must be correct on every read (lazy check) and efficient in the background (batched cleanup, lifecycle rules). Cache TTLs must never outlive the paste.
  • Write-once content caches beautifully at the CDN; handle hot keys with coalescing and local caches, and serve stale during origin failures.
  • User content is an attack surface: escape output, serve raw content from a separate domain with nosniff and a strict CSP, and offer client-side encryption for sensitive data.
  • Keep analytics and scanning off the request path with logs, queues and batch jobs; make every background job idempotent.
  • Abuse control (rate limits, scanning, takedowns) and privacy (delete tokens hashed, backup retention) are core requirements, not extras.
  • Start simple and scale by measurement: load test, profile, fix the bottleneck, repeat. Sharding and microservices come only when the numbers demand them.