Pastebin
A dead-simple 'paste text, get a link' service — worked through the TOGAF ADM so the split between a tiny metadata row and a big blob becomes an obvious consequence, not a hunch.
Pastebin, the ADM way, in 30 seconds
- Why TOGAF here: it keeps you honest about what the data actually looks like before you pick storage — and here the data has two very different shapes.
- A (Vision): paste text, get a shareable link, read it back fast; principles — read-optimized, cheap-per-paste, durable.
- B (Business): two capabilities — create a paste (rare) and view a paste (common); viewing dominates.
- C (Data/App): a tiny metadata record (
key → owner, created, expiry, size) plus a potentially large paste body; a stateless app tier. - D (Technology): the meat — short-key generation, a metadata DB, the body in object/blob storage, a cache on hot pastes, optional expiry, edge delivery.
- E–H: ship the core read/write, add cache and expiry, then govern with size limits and retention SLOs.
- The lesson: the one insight that makes or breaks this design — don't stuff a megabyte of text into a database row — falls straight out of looking at the data in Phase C.
Like a coat-check that hands you a ticket, not the coat
Walk into a theater and hand over your coat. The attendant doesn't follow you to your seat carrying it — they hang it on a numbered hook and give you a small paper ticket with that number. The ticket is tiny and lives in your pocket; the bulky coat lives on the rack. When you leave, you show the ticket and they fetch the coat. Pastebin works exactly this way: your big chunk of text is the coat, and the short link is the ticket.
The whole trick — the one idea this page exists to teach — is that the ticket and the coat go in different places. You keep a small, fast list of tickets (which hook, who dropped it off, when) so you can look things up instantly, and you keep the bulky coats on a cheap, roomy rack. Nobody would staple a wool coat to the ticket register. Yet the equivalent mistake — stuffing a megabyte of text into a database row — is exactly what people do when they skip the step of looking at the data first.
What makes it hard — the problem before the solution
Pastebin is deliberately the simplest system on this site, which is the point: the one hard decision isn't buried under a dozen others, so you can see it cleanly.
- The 'paste' is secretly two things. A short handful of metadata (who, when, how big, when it expires) and a potentially huge body of text. They have opposite cost profiles and want opposite homes.
- Views crush creates. A paste is written once and read many times, so the read path must be fast and cheap even if that makes the write path do a bit more work.
- Bodies are big and immutable. Once pasted, the text never changes — which is a gift: it means you can cache it forever and store it write-once, but only if you didn't trap it inside a mutable database row.
- Storage grows forever. Pastes pile up and rarely get deleted, so the per-byte cost of the body store is the bill that eventually dominates everything.
Why the ADM fits
Pastebin looks identical to a URL shortener at a glance: generate a key, store something, hand back a link. The ADM is what surfaces the one real difference — a shortener maps a key to a short string, while Pastebin maps a key to a blob that can be megabytes. Walking Phase C before Phase D forces you to notice that the data has two shapes with two cost profiles, and that single observation drives the whole storage split. Skip the order and you end up with huge rows, a bloated database, and a cache full of giant values.
Phase A — Architecture Vision
Intent: agree what we're building and the principles that constrain every later choice.
- Vision: let anyone paste a chunk of text (code, logs, notes), get a short link, and have readers load it quickly and reliably — possibly with an expiry date.
- Stakeholders: readers (want the paste to load instantly), authors (want creation to be reliable and the link to keep working), the business (wants storage to stay cheap even as pastes pile up).
- Principles (the constraints that cascade): read-optimized first (views vastly outnumber creates); cheap per paste (storage cost must not balloon); durable (a shared link should not rot).
Phase B — Business Architecture
Intent: model the business capabilities before any technology talk.
- Value stream: author pastes text → receives a short link → shares it → reader opens the link → reader sees the text.
- Capability 1 — Create a paste: low volume, must be correct (unique key, body actually saved), can tolerate a few extra ms.
- Capability 2 — View a paste: high volume, must be fast, overwhelmingly repeated reads of a small set of hot pastes.
- Capability 3 — Expire a paste (optional): housekeeping that must never slow down create or view.
Impact: just like the URL shortener, the two capabilities are lopsided — view dominates and sets the latency targets, while create is where correctness lives. That asymmetry, found here in Phase B, is what justifies caching and the read path in Phase D.
Phase C — Information Systems Architecture (Data & Application)
Intent: define the data and application architecture — and this is where Pastebin earns its keep as a teaching example.
Data architecture
- Two very different entities hide in one 'paste': a small metadata record (
key, author, createdAt, expiresAt, size, contentType) and a potentially large body (the actual text). - Access pattern: look up by
key, read the metadata, then fetch the body — a pure key lookup, no joins. - Conclusion: metadata is a tiny key-value row; the body is a blob that can be kilobytes to megabytes. Treating them the same is the classic mistake — the body does not belong inside a database row. (See SQL vs NoSQL.)
Application architecture
- Stateless app tier for both create and view, so it scales horizontally per the Phase A principle.
- Separation of the two capabilities so the hot view path scales independently of the cold create path.
- An expiry worker that runs off the critical path, deleting bodies and metadata whose
expiresAthas passed.
Phase D — Technology Architecture (the core)
Intent: choose the concrete technologies that realize Phase C and justify each against the principles. This is where an interviewer spends the time, so we cover every step.
D1 — Estimate the load (sizing drives technology)
# 1M new pastes/day
create_per_sec = 1_000_000 / 86_400 # ~12 writes/sec (tiny)
# Read-heavy: ~10 views per paste on average
view_per_sec = create_per_sec * 10 # ~120 reads/sec
# Body size: avg 10 KB, but can be up to a few MB
# Storage: 1M/day * 10 KB * 365 * 5y ~ 18 TB of BODIES
# Metadata: 1M/day * ~200 B * 365 * 5y ~ 0.36 TB of rows
#
# Verdict: writes are trivial; the cost is BODY STORAGE.
# -> keep rows small in a DB, push bodies to cheap object storage.The numbers make the Phase C insight quantitative: metadata is well under a terabyte of small rows, but bodies are tens of terabytes. Storing bodies as database rows would be both expensive and slow — the sizing itself points at object storage.
D2 — Short-key generation
| Option | How | Pros | Cons |
|---|---|---|---|
| Counter + base62 | Global counter; encode as base62. | No collisions; short, fixed-length keys. | Needs a distributed counter; keys are guessable/sequential. |
| Random key + check | Generate N random base62 chars; verify unused. | Unguessable; stateless to generate. | Must check for collisions and retry. |
Decision: same trick as the URL shortener — counter + base62 with each app server pre-allocated a block of IDs so there's no per-request coordination. For 'unlisted' pastes that should not be guessable, add random bits to the encoding.
BASE62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
def base62(n): # encode a counter value as a short key (D2)
s = ""
while n:
n, r = divmod(n, 62)
s = BASE62[r] + s
return s or "0"
def new_key(id_block): # id_block was handed out in bulk -> no per-request lock
return base62(id_block.next())
def make_paste(id_block, ttl_seconds=None):
key = new_key(id_block)
# expiry is just a timestamp in metadata; a sweeper deletes it later.
expires_at = now() + ttl_seconds if ttl_seconds else None
return key, expires_atD3 — Metadata store
- Choice: a horizontally scalable key-value / wide-column store keyed by paste
key— matches the tiny-row access pattern from Phase C. - What it holds: only metadata —
key, author, createdAt, expiresAt, size, contentType, and a pointer to the body in blob storage. Never the body itself. - Durability: replicate each partition (see Replication) so losing a node does not lose paste records.
D4 — Body store (the key decision)
- Store the paste body in object/blob storage (e.g. S3-style), addressed by the paste
key(or a content hash). This is the decision the whole design hangs on. - Why: object storage is cheap per byte, effectively unbounded, and built to serve large immutable objects — exactly the cheap per paste and durable principles from Phase A.
- Why not the DB: large values bloat database rows, blow up backups, and wreck cache efficiency. Keeping bodies out keeps the metadata store small and fast.
- Immutability: a paste body never changes after creation, so it is a perfect fit for write-once object storage and aggressive caching.
| Approach | What it buys | The gap it can't fill |
|---|---|---|
| Body inside the DB row | One store; the paste is a single read. | Rows bloat to megabytes, backups explode, the cache fills with giant values — cost and latency both blow up. |
| Body in object/blob storage (chosen) | Cheap per byte, unbounded, durable, cacheable at the edge; metadata stays tiny and fast. | Two reads instead of one (metadata then body) — a trivial price, and the body read is usually a cache/CDN hit anyway. |
| Body on app-server local disk | Fast and simple for a single box. | Not shared, not durable, lost when the server dies — unusable past one instance. |
-- Metadata row stays tiny: the body lives in blob storage, not here (D3/D4).
CREATE TABLE paste (
key VARCHAR(12) PRIMARY KEY, -- the base62 short key
author_id BIGINT,
content_type VARCHAR(64),
size_bytes INT,
blob_pointer VARCHAR(256) NOT NULL, -- e.g. s3://pastes/ab/abc123
created_at TIMESTAMP NOT NULL,
expires_at TIMESTAMP -- NULL = never expires
);
-- Read path: one key lookup for metadata, then fetch the body by pointer.
SELECT blob_pointer, content_type, expires_at
FROM paste
WHERE key = 'abc123';D5 — Caching & delivery the hot path
- View is the dominant, latency-critical capability, so put an in-memory cache (e.g. Redis) in front of both metadata and recently-read bodies (see Caching).
- Strategy: cache-aside with a TTL; because bodies are immutable, cached entries never go stale, so hit rates on hot pastes are excellent.
- Edge: serve bodies through a CDN (see CDN) so a popular paste is delivered from an edge near the reader and barely touches the origin — directly realizing read-optimized first.
D6 — Expiry & cross-cutting concerns
- Expiry: store
expiresAtin metadata; a background worker (or an object-storage lifecycle rule) deletes the body and the row after it passes — kept off the create/view path. - Size limits & abuse: cap paste size and rate-limit creation at the gateway (see Rate limiting) so one actor cannot flood storage.
- Idempotency: retrying a create must not spawn duplicate pastes (see Idempotency).
- Consistency: a just-created paste becoming readable a moment later is fine — eventual consistency is an accepted trade (see Consistency models).
- Observability: watch cache hit-rate, body-fetch p99, and storage growth (see Observability).
Scaling & bottlenecks — what breaks first
Pastebin is small, so it scales gracefully — but it still fails in a predictable order. Because bodies are immutable and cacheable, the read path almost never buckles first; the pressure shows up in storage growth and in the handful of pastes that go viral.
| Breaks first as you scale | The symptom | The fix |
|---|---|---|
| Body storage cost/size | The object store grows without bound as old pastes accumulate. | Enforce expiry and lifecycle rules; tier cold pastes to cheaper storage; cap paste size. |
| A viral paste (hot body) | One link floods the origin store with identical body fetches. | Cache the immutable body and serve it from the CDN edge — one fetch warms the edge for everyone. |
| Key-generation coordination | Creating pastes slows if every create contends for a global counter. | Pre-allocate ID blocks per app server so creation needs no per-request lock. |
| Expiry sweep load | The delete worker competes with live traffic when many pastes expire at once. | Run expiry off-peak in batches, or lean on object-storage lifecycle rules instead of a custom sweeper. |
def view_paste(key):
# 1. Hot pastes: the whole response is already cached (bodies are immutable).
hit = cache.get(f"paste:{key}")
if hit:
return hit
# 2. Tiny metadata lookup tells us where the body lives and if it's alive.
meta = db.get_paste(key)
if not meta or expired(meta):
return not_found()
# 3. Fetch the big body by pointer (usually a CDN/edge hit, not the origin).
body = blob_store.get(meta["blob_pointer"])
resp = render(meta, body)
cache.set(f"paste:{key}", resp) # immutable -> never goes stale
return respPhases E & F — Migration Planning
- Greenfield, so sequence by risk: ship create + view with a metadata DB and object storage first — that alone is a working Pastebin.
- Add the cache and CDN once real traffic shows which pastes are hot.
- Add expiry and size governance last, since they are housekeeping that must not block the core launch — the same expand-contract spirit as the TOGAF commerce scenario.
Phases G & H — Governance & Change
- Governance (G): define SLOs (view p99, availability), set per-paste size caps and per-client creation quotas, and set a retention policy for expired and abandoned pastes.
- Change (H): adding syntax highlighting, private pastes, or a diff view is a bounded change — new metadata and a new render path, not a re-architecture, precisely because bodies and metadata were cleanly separated.
Pastebin is the smallest possible lesson in matching storage to data shape — and proof that the ADM's discipline of order pays off even on a weekend project.
Why it matters
- It teaches the single most reusable storage pattern: small structured metadata in a database, large blobs in object storage.
- It makes a near-identical-looking problem (vs. URL shortener) reveal its one real difference through Phase C.
- It shows read-optimization — cache plus CDN — turning an immutable blob into an instant read.
If ignored
- You store megabyte bodies as database rows, and the DB, its backups, and its cache all bloat and slow down.
- Without a cache/CDN, every view of a popular paste hammers the origin store unnecessarily.
- No expiry or size governance and storage grows without bound, breaking the cheap per paste principle.
Where it fits
- Phase D holds the metadata/blob split, key generation, caching, CDN delivery, and expiry.
- Phase C's two-shaped data drives that split; Phase A's cheap-and-durable principles justify object storage.
- It sits right beside the URL shortener as the 'same shape, one crucial difference' pairing.
Related topics
- Design a URL shortener: same key-generation trick; the difference is the blob body
- Caching: the Phase D decision that realizes 'read-optimized first'
- CDN: serves immutable paste bodies from the edge
- SQL vs NoSQL: why metadata is a tiny KV row and the body is not
Interview lens
Questions it unlocks
- Design Pastebin / a text-sharing service.
- Where would you store the paste body, and why not in the database?
- How is this different from a URL shortener?
60-second answer
I'd walk it as an ADM track so the key insight is unavoidable. Phase A sets principles — read-optimized, cheap per paste, durable. Phase B finds two lopsided capabilities, create and view, with view dominating. Phase C is the crux: a paste is really two entities, a tiny metadata record and a potentially large body, so they need different storage. Phase D makes that concrete — counter+base62 keys like a URL shortener, a small key-value metadata store holding a pointer, the immutable body in cheap object storage, a cache-aside layer plus a CDN that absorbs the read load, optional expiry via a background worker or lifecycle rule, and cross-cutting rate limits, idempotency, and observability. E–H ship the core first, then cache and expiry, governed by size caps and retention SLOs. The headline is that Phase C's two data shapes — not a gut call — are what split body from metadata.
Common traps
- Storing the full paste body in a database row, bloating the DB and the cache.
- Treating it as identical to a URL shortener and missing that the value is a large blob.
- Forgetting expiry, size caps, and retention, so storage grows without bound and 'cheap per paste' breaks.