Design Pastebin (Text Sharing Service)
Split paste metadata from object storage payloads, mint collision-free base62 keys, enforce TTL expiry, and throttle abuse.
In this lesson (4 bite-sized sections)
Why Pastebin is the classic intern starter
Pastebin looks like a URL shortener at first glance: a user submits text, gets back a short link, and anyone with that link reads the text later. The single twist that changes the architecture is payload size. A short URL points to a 500-byte string, whereas a paste can hold up to 10 MB of logs or source code.
Start with quick sizing. At 1M new pastes per day, writes average about 12 req/sec. At a 10:1 read-to-write ratio, reads sit around 120 req/sec on average, with sharp spikes whenever a link hits a forum front page. If an average paste is 10 KB, raw content grows by 10 GB/day, or roughly 3.6 TB/year before expiration. Throughput is modest, so the real interview signal is separating blobs from metadata and handling expiry and abuse cleanly.
Split metadata from blob storage
Storing multi-megabyte bodies directly inside relational table pages evicts hot index entries from memory, stretches autovacuum pauses, and saturates database storage bandwidth. Keep the database small and predictable by storing only lightweight metadata rows: paste_key, object_key, size_bytes, created_at, expires_at, visibility, and owner_id.
Write the raw UTF-8 paste payload to object storage (Amazon S3 or GCS), keyed by paste_key. On reads, serve small hot pastes (say under 1 MB) from a cache-aside Redis cluster and put a CDN in front of public object-storage blobs so viral traffic never melts origin servers.
Pastebin metadata and blob split: an architecture diagram of 7 components and 6 connections. Full description follows.
- Client: client.
- API Gateway + Rate Limit: load balancer.
- Paste Service: service.
- Redis Cache (hot < 1MB): cache.
- Metadata DB: database.
- Object Storage (S3): database.
- CDN Edge: CDN.
- Client calls synchronously API Gateway + Rate Limit (POST / GET).
- API Gateway + Rate Limit calls synchronously Paste Service.
- Paste Service calls synchronously Redis Cache (hot < 1MB) (cache-aside).
- Paste Service calls synchronously Metadata DB (TTL + key lookup).
- Paste Service calls synchronously Object Storage (S3) (put / get body).
- Object Storage (S3) sends asynchronously to CDN Edge (public viral reads).
Key generation and TTL expiration
An 8-character base62 key (62^8, over 218 trillion values) stops attackers from enumerating unlisted pastes while keeping URLs short. Three strategies work in practice: leasing pre-generated random key blocks from a Key Generation Service (zero collision checks on the hot path), generating 48-bit cryptographically random tokens with a conditional INSERT retry on rare collision, or hashing content (which deduplicates identical pastes, though it can leak whether a secret snippet already exists). Avoid exposing raw sequential counters on unlisted links because anyone can scrape id + 1.
Enforce expiration in two layers. First, perform lazy expiration on every read: check expires_at < now() in the Paste Service and immediately return 410 Gone (or 404) while evicting any cached entry, ensuring expired data is never served even one second late. Second, run asynchronous storage reclamation via a background sweeper over an index on expires_at plus object-storage lifecycle policies so dead blobs do not accumulate forever.
Abuse defense and viral read spikes
Anonymous write endpoints attract spam bots, malware payloads, and credential dumps within hours of launch. Enforce a strict payload size cap (such as 10 MB) at the API gateway before buffering the whole body, apply per-IP and per-account token-bucket rate limits, and require sign-in or challenge gates during bursty anonymous writes. Serve raw paste downloads with Content-Type: text/plain; charset=utf-8 and X-Content-Type-Options: nosniff so stored HTML or JavaScript snippets cannot trigger stored XSS in a reader's browser. Because pastes are immutable once created (or versioned on edit), viral reads are cheap: set immutable cache headers on public blobs, keep hot small pastes in Redis, and let the CDN absorb read spikes without scaling the metadata database.
Sort each Pastebin control by whether it mainly solves storage and read scaling or security, privacy, and expiry.
Sort 5 more items to check
Sources: Amazon S3 object lifecycle · Cloudflare CDN caching · OWASP API rate limiting
ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
def encode_base62(num: int, width: int = 7) -> str:
chars = []
while num > 0:
num, rem = divmod(num, 62)
chars.append(ALPHABET[rem])
return "".join(reversed(chars)).rjust(width, "0")
def safe_download_headers() -> dict[str, str]:
return {
"Content-Type": "text/plain; charset=utf-8",
"X-Content-Type-Options": "nosniff",
}
pastes_per_day, avg_kb, years = 1_000_000, 10, 5
keyspace = 62 ** 7
total_pastes = pastes_per_day * 365 * years
storage_tb = (total_pastes * avg_kb * 1024) / 1e12
keys = [encode_base62(100_000_000 + i * 7919) for i in range(5)]
assert len(keys) == len(set(keys)), "key collision detected"
headers = safe_download_headers()
assert headers["Content-Type"] == "text/plain; charset=utf-8"
assert headers["X-Content-Type-Options"] == "nosniff"
print(f"Sample keys (0 collisions): {keys[:3]}")
print(f"62^7 keyspace: {keyspace:,} ({total_pastes / keyspace:.4%} used over {years}y)")
print(f"5-year blob storage: {storage_tb:.2f} TB | Headers: {headers['Content-Type']} + nosniff")Apply
Your turn
The task this lesson builds to.
Architect a Pastebin-style text sharing service supporting pastes up to 10 MB, 1M new pastes per day, custom expiration TTLs, and read spikes on viral links.
Think about
- Why should multi-megabyte paste bodies live in object storage rather than relational rows?
- How do you generate short keys that resist collisions and URL enumeration?
- Why does expiration require both lazy read checks and background storage cleanup?
Draft your design answer here Save your draft, compare against the model answer, and track progress.
Practice
Make it stick
A second problem on the same idea, so it survives past today.
Propose the changes needed to turn Pastebin into a private-by-default code snippet host for an enterprise engineering org requiring burn-after-reading links, secret-leak scanning, and immediate deletion on takedown.
Think about
- How do you guarantee a burn-after-reading snippet is returned to at most one concurrent reader?
- Where should credential scanning run so leaked API keys never become visible?
- Why do CDN and Redis caches complicate immediate takedown deletion?
Draft your design answer here Save your draft, compare against the model answer, and track progress.