Designing Pastebin

Difficulty: Beginner Topics: Object Storage, ID Generation, CDN, TTL Asked at: Google, Amazon, Meta · Prerequisites: Caching and CDN


1. Understanding the Problem

Pastebin is a text-sharing service. You paste text (code snippets, logs, config files), get a unique short URL, and anyone with that URL can read the paste. No authentication needed to create or read. That’s it - deceptively simple, but it covers real design concepts: unique ID generation, storage decisions, caching, and data lifecycle management.
💡 The ID is not a detail here — it becomes the URL, and the URL is the only thing standing between a paste and a stranger reading it. Choosing how to generate it is the privacy decision of the whole design.

Real examples: pastebin.com (18M+ pastes/month), GitHub Gist, Hastebin, Privatebin.


2. Naive First Cut

flowchart LR
    USER["User"]
    API["API Server"]
    DB[("Single DB<br/>stores everything")]

    USER --> API
    API --> DB

Store the paste content as a TEXT/BLOB column directly in SQL. Use auto-increment IDs.

Why this breaks:

  • Large pastes in DB - storing 10MB text blobs in a relational DB bloats the table, slows backups, and makes queries inefficient
    💡 A blob is just a lump of bytes the database never looks inside — it cannot filter, sort or join on it. Keeping it in a row means every backup and every replica copies it for no query’s benefit.
  • Sequential IDs - auto-increment exposes paste count and is guessable (scraping paste/1, paste/2, …)
    💡 Auto-increment = the database hands out 1, 2, 3, … in order. Convenient, and it means anyone who has one URL can trivially construct the next one.
  • Single server - one machine handles both reads and writes. Traffic spike kills everything.
  • No caching - every read hits the DB. With 10:1 read-to-write ratio, the DB drowns.
  • No expiry - pastes accumulate forever, storage grows unbounded

The rest of the doc evolves this into a proper scalable design.


3. Prior Art We’re Drawing From

  • GitHub Gist - Stores code snippets with Git-backed versioning. Content lives in object storage, metadata in Postgres. Demonstrates separation of content from metadata at scale. (GitHub Engineering)
  • Hastebin (haste-server) - Minimal open-source paste service. Shows that the core problem is just ID generation + blob storage + serve. (GitHub: haste-server)
  • Cloudflare Workers KV - Globally distributed key-value store with CDN-like read performance. Demonstrates how immutable content benefits from aggressive edge caching. (Cloudflare Workers KV docs)

4. Functional Requirements

Core (Top 3)

  1. Create a paste - user submits text, gets back a unique short URL
  2. Read a paste - anyone with the URL can retrieve the content
  3. Expire pastes - pastes can have a time-to-live (TTL) of 1 hour, 1 day, 1 week, or never
    💡 Time-to-live = a self-destruct timestamp stored with the record. The system has to honour it the moment it passes, which turns out to be a different job from actually reclaiming the disk space.

Below the Line

  • Syntax highlighting per language
  • Edit/update an existing paste
  • User accounts and “my pastes” list
  • Password-protected pastes
  • Raw content endpoint

5. Non-Functional Requirements

NFR Target
Read-heavy 10:1 read-to-write ratio (10K reads/sec, 1K writes/sec)
Low read latency P99 (the delay 99% of reads beat) < 100ms for paste retrieval
Durability Paste content must survive hardware failures (99.999%)
Storage efficiency Handle pastes up to 10MB cheaply

Below the Line

  • Strong consistency on analytics
  • Multi-region deployment
  • End-to-end encryption

6. Scale Estimation (Back-of-Envelope)

  • Write QPS: 1K new pastes/sec (peak during work hours)
    💡 QPS = queries per second, the standard unit for “how much traffic”. Every capacity decision below is really a reaction to one of these two numbers. Learn more →
  • Read QPS: 10K reads/sec (10:1 ratio)
  • Storage: ~315TB paste content/year (avg paste ~10KB, max 10MB), which is why content goes to object storage and only metadata stays in Postgres
  • Bandwidth: ~1 Gbps at peak for content delivery

7. Core Entities

  • Paste - the content (text/code), up to 10MB
  • Metadata - paste ID, creation time, expiry time, language, owner (optional)
  • Short URL - the unique 7-character code that maps to a paste

8. API / System Interface

POST /v1/pastes
  Body: { content, language?, expiresIn?, title? }
  Response: { id: "abc12XY", url: "https://paste.io/abc12XY", expiresAt }

GET /v1/pastes/{id}
  Response: { id, content, language, createdAt, expiresAt, title }

DELETE /v1/pastes/{id}
  Headers: Authorization: Bearer <token>
  Response: 204 No Content

Security note: Creating pastes can be anonymous, but deleting requires ownership proof. Rate-limit creation by IP to prevent spam.


9. High-Level Design

Let’s build this incrementally, one functional requirement at a time.

FR1: Create a Paste - Generating a Unique ID and Storing Content

The first thing a user does: paste text, click submit, get a short URL back. So we need an identifier for the paste, somewhere to keep the text, and a URL built from the two.

Build the obvious version. One service, one database, and the identifier is the one the database already gives us for free.

New components:

  1. Paste Service - the API layer. Validates input (size < 10MB) and writes the paste.
  2. Postgres - a pastes table holding the id, the content as a TEXT column, and the metadata: created time, expiry, language.
flowchart LR
    USER["User"]
    API["Paste Service"]
    DB[("Postgres pastes<br/>content and metadata")]

    USER -->|"1. POST paste content"| API
    API -->|"2. Insert row and get id"| DB
    API -->|"3. Return the short URL"| USER

Step-by-step flow:

  1. User submits text and options → POST /v1/pastes
  2. Paste Service checks the content is under 10MB and the caller is within its rate limit
  3. It inserts one row — content included — and takes the auto-increment primary key as the paste id
  4. It returns { url: "paste.io/8675309" }

Why one table rather than two stores? Because a paste is one logical thing written once, and splitting it across a database and a blob store immediately creates a consistency problem: two writes that can half-succeed, leaving either a row pointing at content that is not there or content nobody can find. One row is one atomic write. That simplicity is worth real money for as long as it holds.

What we have deliberately left broken. A paste can be created and fetched by URL, which is the requirement. Two choices in step 3 are wrong:

  • The id is sequential, so every paste is enumerable. paste.io/8675309 invites anyone to try 8675308. At ~1000 pastes/sec that is 86M pastes a day, all walkable with a for-loop — and people paste logs, config and keys into these. Unlisted is the only privacy model this product has, and an auto-increment id defeats it entirely. It also leaks the total paste count to any competitor who creates one paste a day. That is Deep Dive 1.
  • A 10MB blob is sitting in a relational table. It is not just the size: that column is replicated to every replica, copied into every backup, and walked by vacuum, all for bytes no query ever filters or joins on. At 1000 pastes/sec averaging 10KB the table grows ~864GB a day, and the metadata lookups that should be sub-millisecond are sharing a buffer pool with it. That is Deep Dive 2.
    💡 The buffer pool is the slice of RAM a database keeps hot rows in. It is fixed in size, so every megabyte of paste text squatting in it is a megabyte not holding the small metadata rows that reads actually need.

FR2: Read a Paste - Serving Reads at Scale with Caching

Now users want to read pastes. With a 10:1 read-to-write ratio, reads dominate — so this is the path that decides what the system costs.

New components: none. The paste is a row; fetching it is a primary-key read.

flowchart LR
    READER["Reader"]
    API["Paste Service"]
    DB[("Postgres pastes")]

    READER -->|"1. GET paste by id"| API
    API -->|"2. Select by primary key"| DB
    API -->|"3. Check expiry"| API
    API -->|"4. Return content or 404"| READER

Step-by-step flow:

  1. Reader visits paste.io/8675309 → the request reaches the Paste Service
  2. SELECT * FROM pastes WHERE id = 8675309 — one primary-key lookup, which is the cheapest thing a database does
  3. If expires_at has passed, return 404 Gone without returning content. Checking on read is what makes expiry correct the instant it fires, regardless of when anything gets cleaned up
  4. Otherwise return the content

Why check expiry on read rather than trusting a cleanup job? Because a cleanup job runs on a schedule and expiry is a promise to the user. If the job is late, backed up, or failed, a lazy check on the read path still returns 404 at exactly the right moment. The job reclaims storage; the read check enforces the contract. Those are different jobs and conflating them is how expired content gets served.

What we have deliberately left broken. Reads are correct and the query is cheap. Every single one of them crosses the planet to reach us:

A paste is immutable — once written the content never changes — and we are serving it from one origin anyway. So a reader in Sydney pays a trans-Pacific round trip for bytes that could have been sitting in Sydney, and a paste that gets 100K views causes 100K identical origin reads of a row that could not possibly have changed between them. At 10K reads/sec that is ~864M origin requests a day doing work whose answer was already known.
💡 Immutable means nothing can edit the content after creation. That one property removes the hardest question in caching — “is my copy stale?” — because the answer can never become yes.

Immutable, publicly addressable, read-many content is the single most cacheable thing in computing, and we are not caching it anywhere. That is Deep Dive 3.


FR3: Expire Pastes - Handling TTL Without Slowing Reads

Users can set an expiry: 1 hour, 1 day, 1 week. After expiry the paste must return 404 — and the storage it occupied has to come back, because dead content costs the same as live content.

New component:

  1. Cleanup Service - a background job that deletes expired rows on a schedule.
    💡 A background job is code on a timer with no user waiting for it. That is exactly why it cannot be trusted to enforce expiry — nothing breaks visibly when it is an hour late.
flowchart LR
    API["Paste Service"]
    DB[("Postgres pastes")]
    CRON["Cleanup Service<br/>runs every 5 min"]

    API -->|"1. Check expiry on every read"| DB
    CRON -->|"2. Scan for expired pastes"| DB
    CRON -->|"3. Delete expired rows"| DB

Two-pronged expiry strategy:

  1. Lazy check on read - FR2 step 3 already does this. When someone requests a paste, compare expires_at to now and return 404 if it has passed. The row still exists but is unreachable, which gives instant correctness: nobody ever sees an expired paste, no matter what the cleanup job is doing.

  2. Background cleanup job - runs every 5 minutes:

    • SELECT id FROM pastes WHERE expires_at < NOW() LIMIT 1000
    • Deletes those rows in batches, so one pass never holds a long transaction
    • This reclaims storage — without it, dead content accumulates forever

Why both? They solve different problems and neither covers the other. The lazy check is an immediate guarantee to the user and reclaims nothing; the job reclaims space and is always at least a little late. Relying only on the job means serving expired content for up to five minutes; relying only on the check means paying to store pastes nobody can read, forever.

What we have deliberately left broken. Expiry is correct and storage is reclaimed. Two things this creates for the deep dives rather than solves:

  • Step 2 scans by expires_at across the whole table, which needs its own index, and that index is maintained on every insert — so the write path from FR1 pays for the cleanup path. Once Deep Dive 2 moves content out of the row, this job has to delete from two places and can half-fail, leaving orphaned blobs that nothing will ever reference again.
  • Once Deep Dive 3 adds a cache, expiry gets a second enforcement point. A paste cached at an edge is served without consulting expires_at at all, so a reader can see a paste after it expired. The lazy check only works while every read passes through us, and the entire point of Deep Dive 3 is that they stop doing that.

10. Technology Choices

Tier Purpose Primary Pick Alternatives Why Primary Wins Here
Object Storage Paste content blobs S3 GCS, Azure Blob, MinIO Cheap, durable, handles 10MB blobs natively without bloating the DB
Metadata DB Paste metadata + expiry Postgres MySQL, DynamoDB, CockroachDB Relational simplicity for small rows; TTL index for expiry queries
Cache Hot paste reads Redis Memcached, Caffeine, Varnish Sub-ms reads for viral pastes; TTL eviction matches paste expiry
CDN Serve popular pastes at edge CloudFront Cloudflare, Fastly, Akamai Immutable content = perfect cache hit ratio at edge
ID Generation Short unique paste URLs Base62 (Snowflake/Counter) UUIDv7, NanoID, hashids 64-bit numeric → short URL, time-sorted, non-guessable

Why S3 over storing blobs in Postgres? Pastes up to 10MB would bloat table size, slow backups, and make write-ahead log (WAL) replay painful. S3 gives unlimited cheap storage with 11-nines durability, and content is immutable — a perfect fit for object storage.
💡 A write-ahead log is a running record of every change, written before the change itself, so a crashed database can replay it and recover. Put a 10MB blob in a row and that blob goes through the log too. Learn more →


11. Data Modeling

Postgres (Metadata DB — paste records):

CREATE TABLE pastes (
    paste_id VARCHAR(10) PRIMARY KEY,  -- base62 short code
    s3_key VARCHAR(128) NOT NULL,      -- content location in S3
    language VARCHAR(30),
    title VARCHAR(200),
    owner_id UUID,                     -- null for anonymous pastes
    size_bytes INTEGER NOT NULL,
    is_public BOOLEAN DEFAULT true,
    created_at TIMESTAMP NOT NULL,
    expires_at TIMESTAMP               -- null = never expires
);
CREATE INDEX idx_pastes_expiry ON pastes(expires_at) WHERE expires_at IS NOT NULL;
CREATE INDEX idx_pastes_owner ON pastes(owner_id, created_at DESC);

S3 (Object Storage — paste content blobs):

Key: "pastes/{paste_id}/{version}" → Raw text/code content (up to 10MB)
Content-Type: text/plain
Cache-Control: public, max-age=31536000, immutable  (content never changes)

Redis (Cache — hot paste reads):

Key: "paste:{pasteId}" → String (paste content, compressed if > 1KB)
TTL: 24 hours (popular pastes stay cached; evicted by LRU otherwise)

Access Patterns:

Query Data Source How
Read paste (hot) Redis → S3 Check Redis first, on miss fetch from S3 and backfill cache
Create paste S3 + Postgres Upload content to S3 → insert metadata to Postgres → return short URL
Delete/expire paste Postgres + S3 + Redis Mark deleted in Postgres, delete S3 object, DEL Redis key
Expiry cleanup Postgres Cron: DELETE FROM pastes WHERE expires_at < now() + S3 batch delete

How a Paste Is Created Without Collision:

  1. User submits content → Write Service asks Snowflake ID generator for a unique 64-bit ID
    💡 Snowflake is a well-known scheme for building an ID out of a timestamp plus a machine number plus a counter, so many servers can mint unique IDs without talking to each other. Deep Dive 1 explains why its time-ordering is a drawback here. Learn more →
  2. Base62-encode → 7-character paste code (e.g., aB3xY9)
  3. Upload content to S3 at key pastes/aB3xY9/1
  4. Insert metadata into Postgres (paste_id, s3_key, size, expiry)
  5. Return https://paste.example.com/aB3xY9 — no collision check needed (Snowflake is unique by construction)

12. Deep Dives

1) An unlisted paste is private only if nobody can guess its URL. Can they guess ours?

Problem: The paste ID appears in the URL (paste.io/abc12XY). It must be unique, short, and not guessable (sequential IDs let people scrape all pastes).

Bad: the auto-increment primary key FR1 used as the paste id. It is unique, it is short, and it is the one property that matters here that it fails: it is predictable.

Unlisted is the entire privacy model of this product — there are no access control lists (ACLs), no sharing permissions, nothing but an unguessable URL. A sequential id means a for loop reads the whole corpus. At ~1000 pastes/sec that is 86M pastes a day, and people paste exactly the things you would not want enumerated: stack traces, config files, connection strings, API keys. So the defect is not “IDs look ugly”, it is that the product has no confidentiality at all.

It leaks a second thing for free. Create one paste today and one tomorrow, subtract, and you know our daily volume — a business metric handed to anyone who asks.

Good: Hash-based - MD5/SHA256 of content, take first 7 chars of Base62. Same content = same ID (deduplication!). But different pastes can collide (same first 7 chars), requiring retry logic.

Great: Random 7-character Base62 string with collision check. Generate abc12XY randomly, check if it exists in the metadata DB (fast primary key lookup), retry on collision. At 3.5 trillion possible IDs with 1 billion pastes stored, a given random code collides about once in 3,500 attempts - rare enough that the retry costs nothing, and frequent enough that the existence check is mandatory rather than belt-and-braces.

In simple terms: Generate a random 7-character code (like “aB3xY9”), check whether it already exists in the database, and retry if it does. With 3.5 trillion possibilities the retry almost never fires twice, so the write path stays one lookup plus one insert - and the code is non-guessable.

Why random beats hash: With hash-based IDs, two different pastes CAN produce the same first 7 chars (collision). You’d need collision resolution anyway, so random is simpler. Hash-based is better when you WANT deduplication (same content → same URL), but that’s not a requirement here.

Why random beats counter/Snowflake: Snowflake IDs are time-sorted and somewhat predictable. For a paste service where privacy matters (users don’t want their paste URLs guessable), random is preferred.


2) Why should a 10MB blob not live in the row next to its metadata?

Problem: Paste content ranges from 1 byte to 10MB. Where should it live?

Bad: the TEXT column FR1 built.

Factor DB (Postgres BYTEA) Object Storage (S3)
Max practical size ~1MB per row (performance degrades) Up to 5TB per object
Cost $0.10-0.20/GB/month (EBS-backed) $0.023/GB/month (S3 Standard)
Backup speed Slow when table has large blobs Independent - DB stays lean
Read latency Fast for small rows ~50ms first byte (CDN fixes this)
Scaling Vertical (bigger instance) Infinite horizontal

Good: Object Storage for all content. Cheap, scalable, durable. The 50ms latency is a non-issue because CDN absorbs 95%+ of reads.

Great: Object Storage + content-hash deduplication. If two users paste identical content, store it once in S3 with the content hash as the key. Both paste metadata rows point to the same S3 object. Saves storage at scale.

In simple terms: If two users paste the exact same text, store it only once in S3 and have both paste URLs point to the same file. Saves storage money.


3) The content never changes and we fetch it from origin 864M times a day. Why?

Problem: 10K reads/sec. Object Storage charges per request and has ~50ms latency. We need most reads to never touch the origin.

Bad: no caching anywhere, which is what FR2 built. Every read reaches our origin and, once Deep Dive 2 moves the bytes to object storage, every read becomes an object-storage GET as well.

Price it. 10K reads/sec is 864M requests a day. S3 charges about $0.0004 per thousand GETs, so that is roughly $346/day — about $126K a year in request charges alone, before a byte of egress. And it buys nothing: the content is immutable, so the overwhelming majority of those requests retrieve something already retrieved.
💡 Egress = bytes leaving the cloud provider’s network, billed separately from the request count. It is the line item that makes serving popular content from one origin expensive twice over.

Latency is the other half, and it is the half users feel. An object-storage GET is ~50ms to first byte before any network distance, so a reader in Sydney hitting a US origin waits on a trans-Pacific round trip plus that 50ms, for a file that has not changed since it was written.

The waste is concentrated exactly where it is cheapest to remove: a popular paste might get 100K views, and after the first one the remaining 99,999 are identical.

Good: Application-level cache (Redis) in front of S3. Reduces origin hits. But Redis costs memory, and popular pastes might be large (10MB cache entry).

Great: CDN at the edge. Pastes are immutable (write-once, never updated), making them ideal CDN candidates. Set Cache-Control: public, max-age=86400 (24h). After the first read, all subsequent reads from the same region are served in <10ms from the CDN edge. For a popular paste with 100K views, only 1 request reaches your origin.
💡 A content delivery network (CDN) is a fleet of caches the provider already operates in hundreds of cities. “At the edge” means the copy answering a Sydney reader is physically in Sydney, so the round trip never crosses an ocean.

In simple terms: Since pastes never change after creation, a CDN can cache them forever. After the first person reads a paste, everyone else in that region gets it instantly from the CDN — your origin server is never hit again for that paste.

Cache invalidation: For expired pastes, the CDN might serve stale content for up to max-age seconds. Solutions:

  • Set max-age = min(time_until_expiry, 24h) - paste expiring in 1 hour gets 1h cache
  • For immediate removal: call CDN purge API when a paste is deleted

13. Design Self-Audit

Question Answer
Single points of failure? S3 is multi-AZ (copied across several independent availability zones). Metadata DB needs a replica. Paste Service is stateless, meaning it holds nothing between requests, so you can add machines freely → scale horizontally.
Abuse prevention? Rate limit by IP (100 creates/hour), max size 10MB, content scanning for malware.
What if S3 is slow? CDN absorbs 95% of reads. The remaining 5% (cold misses) tolerate 50ms.
Orphan cleanup? Background reconciliation job scans for S3 keys without metadata matches (hourly).

14. Core Flows

Flow: Create a Paste (End-to-End)

sequenceDiagram
    participant U as User
    participant API as Paste Service
    participant ID as ID Generator
    participant S3 as Object Storage
    participant DB as Metadata DB

    U->>API: POST /pastes content + options
    API->>API: Validate size < 10MB
    API->>ID: Generate unique ID
    ID-->>API: "abc12XY"
    API->>S3: PUT key=abc12XY body=content
    S3-->>API: OK
    API->>DB: INSERT id expiry language
    DB-->>API: OK
    API-->>U: 201 url=paste.io/abc12XY

Non-obvious failure: What if S3 write succeeds but the DB insert fails? The content exists in S3 but no metadata points to it - it’s an orphan. Solution: the Cleanup Service also scans for S3 keys that don’t have a corresponding metadata row (runs less frequently, once/hour).

Flow: Read a Paste (CDN Hit vs Miss)

sequenceDiagram
    participant R as Reader
    participant CDN as CDN Edge
    participant API as Paste Service
    participant DB as Metadata DB
    participant S3 as Object Storage

    R->>CDN: GET paste.io/abc12XY
    alt Cache Hit
        CDN-->>R: 200 content (sub-10ms)
    else Cache Miss
        CDN->>API: Forward request
        API->>DB: SELECT WHERE id=abc12XY
        DB-->>API: Metadata (not expired)
        API->>S3: GET key=abc12XY
        S3-->>API: Content
        API-->>CDN: 200 + Cache-Control headers
        CDN-->>R: 200 content
        CDN->>CDN: Cache for next reader
    end

15. Final Architecture

flowchart LR
    USER["User"]
    CDN["CDN<br/>edge cache"]
    API["Paste Service"]
    ID["ID Generator"]
    S3[("Object Storage<br/>paste content")]
    META[("Metadata DB<br/>id expiry lang")]
    CLEANUP["Cleanup Service"]
    READER["Reader"]

    USER -->|"POST paste content"| API
    API -->|"Generate short ID"| ID
    API -->|"Store paste text"| S3
    API -->|"Save paste metadata"| META
    READER -->|"GET paste by ID"| CDN
    CDN -->|"Forward on miss"| API
    CLEANUP -->|"Scan expired pastes"| META
    CLEANUP -->|"Delete expired content"| S3

How it works end-to-end (write path):

  1. User creates paste — sends content to the Paste Service API
  2. ID Generator produces short ID — Base62-encoded random ID for a non-guessable URL
  3. Content stored in Object Storage — raw paste text written to S3 (cheap, durable blob store)
  4. Metadata saved — ID, expiry, language hint persisted to the Metadata DB

How it works end-to-end (read path):

  1. Reader requests paste — hits CDN edge first (immutable content = high cache hit rate)
  2. CDN cache miss — request falls through to the Paste Service which fetches from S3 and Metadata DB
  3. Cleanup Service handles expiry — periodically scans Metadata DB for expired pastes and deletes their content from S3

Key Technologies

Term What it is
Object Storage (S3/GCS) Cloud storage for arbitrary blobs. Pay per GB. Virtually unlimited. Perfect for paste content.
Base62 Encoding Encoding using 62 characters (a-z, A-Z, 0-9). 7 chars = 3.5 trillion combinations. Short, URL-safe.
CDN (CloudFront/Cloudflare) Caches content at edge servers worldwide. Immutable pastes = extremely high hit rate.
TTL (Time To Live) How long a paste lives before expiring. Stored as expiresAt timestamp.
Metadata DB Small structured data per paste (ID, timestamps, language). Stays lean because content lives elsewhere.

What’s Expected at Each Level

Mid-level

Design basic paste creation and retrieval. Propose object storage (S3) for content and a database for metadata. Understand Base62 ID generation (same pattern as URL shortener). Explain why storing large text blobs directly in a relational DB is a bad idea - cost, backup speed, and query performance all suffer.

Senior

Explain the separation of content (S3) from metadata (Postgres) - different access patterns, different cost profiles. Propose CDN caching for immutable pastes (write-once, read-many = perfect cache hit ratio). Discuss expiry handling with lazy deletion on read plus background cleanup for storage reclamation. Know the failure mode: S3 write succeeds but DB insert fails → orphan handling.

Staff+

Address abuse prevention (rate limiting per IP, content scanning for malware/spam, CAPTCHA). Discuss storage cost optimization via content-hash deduplication (same content = same S3 key). Cover CDN cache invalidation for expired pastes (short max-age for short-lived pastes). Discuss multi-region: replicate metadata DB for low-latency reads, S3 is already multi-AZ, CDN handles global distribution.


🎯 Key Takeaways

  • Separate metadata from content - small DB rows for fast lookups, object storage for cheap blob storage
  • Base62 random IDs give short, URL-safe, non-guessable paste links
  • CDN is a perfect fit because pastes are immutable - write once, read many
  • Two-pronged expiry - lazy check for correctness, background job for cleanup
  • This is essentially a simpler URL shortener: generate ID → store blob → serve it


Understand the building blocks used in this design:

  • Object Storage → — stores large paste blobs cheaply instead of bloating the database
  • CDN → — serves popular pastes from the edge to cut read latency
  • Caching → — keeps hot paste content and metadata in memory
  • Database Sharding → — partitions the paste metadata store as volume grows