Design a Scalable Text Paste Service (Pastebin Clone)
System DesignModel answerLast updated
Design a text sharing system that accepts raw text or code snippets and generates short, durable URLs with customizable TTLs under high read concurrency.
Problem Overview
Design a distributed text-sharing web application similar to Pastebin. Users should be able to upload plain text or code snippets, assign optional expiration policies, generate a short non-predictable URL, and distribute that link to others.
Functional Requirements
- Paste Creation: Users submit text data and optionally pick an expiration timeframe (e.g., 10 minutes, 1 day, 30 days, or infinite). They may also supply a custom string identifier.
- Paste Access: Anyone presenting a valid unique key gets the original raw text content.
- Paste Deletion: Anonymous creations cannot be deleted manually. Authenticated authors can explicitly purge pastes they own.
- Expiration Handling: Once a paste passes its expiration timestamp, it must be inaccessible to readers.
Non-Functional Requirements
- Low Latency & High Availability: Read queries must return in under 50ms. The system operates under a heavy read-to-write skew (between 10:1 and 50:1).
- Durability: Uploaded snippets must remain persistent and uncorrupted until their expiration date.
- Collision Resistance & Entropy: Generated keys must be unique. Private pastes should rely on unguessable key formats.
System Capacity & Scale Assumptions
- Write Throughput: 10 million new paste submissions per day (~115 writes/sec average, ~500 writes/sec peak).
- Read Throughput: 100 million paste reads per day (~1,150 reads/sec average, ~5,000 reads/sec peak).
- Payload Constraints: Average paste payload size is 10 KB; absolute maximum is 2 MB per paste.
- Storage Projections: ~100 GB of fresh content ingested daily (~36.5 TB/year before compression or eviction).
What Your Architecture Should Cover
- API Endpoints: Formal RESTful interface definitions for key operations, including payloads, failure cases, and status codes.
- Storage Split & Data Model: Schema design for metadata vs. raw payload storage, detailing the rationale behind separating object storage from relational/NoSQL metadata engines.
- Identifier Generation: Comparison of identifier allocation strategies (Key Generation Service with memory-buffered ranges vs. inline cryptographic hashing/counters).
- End-to-End Execution Flow: Complete trace of read/write lifecycles through load balancers, web tiers, distributed caches, storage tiers, and garbage collection workers.
- Operational Edge Cases & Trade-offs: Strategies for handling viral/hot keys, rate limiting, and cache invalidation strategies during deletions.
Hints
Hint 1
Consider how separating small metadata (e.g., owner, TTL, key) from heavy payloads (up to 2 MB) impacts database indexing and buffer pool efficiency.
Hint 2
Evaluate how pre-generating short unique strings in bulk off the critical write path eliminates database lock contention and collision checks.
Hint 3
Ensure lazy expiration logic on the read path so strict system correctness does not depend on background cleanups running instantaneously.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
1. High-Level Requirements & Mathematical Sizing
Traffic Metrics
- Writes: $10^7$ writes / $86,400$ sec $\approx 115$ req/s (average), peak $\approx 500$ req/s.
- Reads: $10^8$ reads / $86,400$ sec $\approx 1,150$ req/s (average), peak $\approx 5,000$ req/s.
- Read/Write Ratio: 10:1 average ratio.
Storage Estimations
- Raw Content: $10^7 \text{ pastes/day} \times 10\text{ KB} = 100\text{ GB/day} \approx 36.5\text{ TB/year}$. With standard gzip compression (approx 3:1 ratio for source code/plain text), physical raw storage drops to $\approx 12\text{ TB/year}$.
- Metadata Storage: Each record contains metadata fields total $\approx 300\text{ bytes}$. $10^7 \text{ writes/day} \times 300\text{ bytes} = 3\text{ GB/day} \approx 1.1\text{ TB/year}$.
Addressable Key Space
Using a 62-character alphabet ([a-z], [A-Z], [0-9]):
- Length 7 string: $62^7 \approx 3.5 \times 10^{12}$ unique combinations.
- Length 8 string: $62^8 \approx 2.18 \times 10^{14}$ unique combinations.
An 8-character Base62 string covers decades of pastes while remaining sparse enough to prevent key-enumeration attacks. For explicitly private pastes, key length can be extended to 16 characters or upgraded to standard UUIDv4 strings.
2. API Contract
Create a Paste
POST /v1/pastes
- Headers:
Authorization: Bearer <token>(Optional),Content-Type: application/json - Request Body:
{ "content": "def hello_world():\n print('Hello, World!')", "title": "sample.py", "expires_in_seconds": 86400, "custom_alias": "my-script", "visibility": "public" } - Responses:
201 Created{ "key": "x9K2pQ1z", "url": "https://paste.example.com/x9K2pQ1z", "expires_at": "2024-07-01T12:00:00Z" }400 Bad Request(Invalid TTL or payload)409 Conflict(Custom alias already taken)413 Payload Too Large(Payload exceeds 2 MB)429 Too Many Requests(Rate limit hit)
Fetch Paste Metadata & Payload
GET /v1/pastes/{key}
- Responses:
200 OK{ "key": "x9K2pQ1z", "title": "sample.py", "content": "def hello_world():\n print('Hello, World!')", "created_at": "2024-06-30T12:00:00Z", "expires_at": "2024-07-01T12:00:00Z" }404 Not Found(Key does not exist)410 Gone(Paste has expired or been purged)
Fetch Raw Content
GET /{key}/raw
- Response:
200 OKwithContent-Type: text/plain; charset=utf-8. Direct response for simple curl/script consumption. Highly cacheable via CDN header controls (Cache-Control: public, max-age=3600).
Delete a Paste
DELETE /v1/pastes/{key}
- Headers:
Authorization: Bearer <token>(Required) - Responses:
204 No Content(Successfully soft-deleted)401 Unauthorized/403 Forbidden(User does not match owner ID)404 Not Found
3. Data Storage & Decoupling Strategy
Mixing arbitrary-sized binary large objects (BLOBs) directly within structured transactional tables harms database index operations, fills buffer pool memory, and inflates database snapshot backups. Therefore, metadata and text content are physically separated:
+-------------------------------------------------------+
| Application Tier |
+--------------------------+----------------------------+
|
+--------------+--------------+
| |
v v
+-----------------------+ +-----------------------+
| Metadata Store | | Object Store |
| (DynamoDB/PostgreSQL)| | (AWS S3 / GCS Cloud) |
+-----------------------+ +-----------------------+
| Stores: Key, Owner, | | Stores: Compressed |
| Object Path, TTL, | | Text Payload |
| Expiration Index | | File Blobs |
+-----------------------+ +-----------------------+
Storage Schema Definitions
Metadata Store Table (DynamoDB or Sharded PostgreSQL)
key(STRING, Primary Key): Unique 8-char base62 code or custom string.owner_id(STRING, Nullable): Account ID of the creator. Null if created anonymously.blob_url(STRING): Object storage location path (e.g.,s3://pastes-bucket/2024/06/30/x9K2pQ1z.gz).size_bytes(INTEGER): Payload size in bytes.created_at(TIMESTAMP): Time of insertion.expires_at(TIMESTAMP, Nullable): Expiration deadline. Null means infinite lifetime.is_deleted(BOOLEAN): Soft-deletion flag.
Optimization: Small-Payload Inlining
For pastes below a small threshold (e.g., $< 4\text{ KB}$), saving payload data directly inside a small_content metadata column saves an extra S3 fetch operation on reads. Pastes $\ge 4\text{ KB}$ store small_content as NULL and retrieve data via blob_url.
4. Identifier Allocation Strategy
| Strategy | Advantages | Disadvantages |
|---|---|---|
| Base62 of Auto-Increment ID | Zero collisions; trivial to implement. | Sequential IDs are predictable; central auto-increment sequence forms single-point bottleneck. |
| Inline Cryptographic Hash (MD5/SHA256 of Payload + Timestamp) | Distributed & stateless key assignment. | Collisions require database read checks (retry loop). Identical content requires salting. |
| Key Generation Service (KGS) | O(1) allocation speed, guaranteed unguessable, zero collision overhead on write path. | Requires maintaining dedicated key supply workers and state. |
Preferred Solution: Centralized Key Generation Service (KGS)
A background process pre-generates random 8-character strings and inserts them into a key management database table containing two columns: (key VARCHAR, is_used BOOLEAN).
+-----------------------+
| KGS Key Database |
| (Pre-computed Keys) |
+-----------+-----------+
| Batch Allocation
v
+------------------+ 1000 Keys +------------------+
| App Instance #1 | <---------- | KGS Service |
| (Memory Buffer) | | Coordinator |
+------------------+ +------------------+
- Each Stateless Application Node requests a batch (e.g., 1,000 unused keys) from the KGS over an internal gRPC endpoint.
- The KGS marks those keys as assigned in the database using an atomic transaction and serves the key block to the requesting app node.
- App instances draw locally from their memory buffer for standard write operations.
- If an app server crashes, its assigned local key block is discarded. Given an 8-character Base62 space ($2.18 \times 10^{14}$ values), losing candidate keys causes negligible depletion.
Exception Handling for Custom Aliases: Custom aliases bypass the KGS. They perform an atomic conditional write directly against the primary Metadata store (INSERT IF NOT EXISTS). If the alias exists, the service returns 409 Conflict.
5. End-to-End System Architecture
+---------------------+
| CDN Edge |
+----------+----------+
|
v
+---------------------+
| L7 Load Balancer |
+----------+----------+
|
v
+---------------------+
| Paste Services |
| (Stateless API) |
+---+----+-------+----+
| | |
+------------------------+ | +-------------------------+
| | |
v v v
+-----------------------+ +-----------------------+ +-----------------------+
| Redis Cache Cluster | | Metadata DB Cluster | | Object Storage (S3) |
| (Hot Pastes / Metadata| | (DynamoDB / Postgres) | | (Compressed Payloads) |
+-----------------------+ +-----------------------+ +-----------------------+
^
|
+----------+----------+
| Expiry Purge Worker |
+---------------------+
Write Path Execution Walkthrough
- Request Reception: Client sends a
POST /v1/pastesrequest. - Validation: System validates that size $\le 2\text{ MB}$, checks client rate limits via Redis token-bucket algorithms, and verifies ownership token if present.
- Key Reservation: App node extracts an available unique 8-character key from its local pre-fetched KGS memory buffer.
- Content Upload: Payload text is compressed via
gzipand stored in Object Storage (S3). - Metadata Persistence: The metadata record (including
blob_url,expires_at,key) is written to the Metadata DB. - Response: App returns
201 Createdwith key and short link.
Read Path Execution Walkthrough
- Edge Cache Lookup: Edge CDN checks if the raw object URL (
/{key}/raw) is available in local edge memory. - Application Cache Hit: On CDN miss, request reaches API Service. The node queries the Redis cluster using key
paste:{key}.- If present: Validates
expires_attimestamp. If expired, returns410 Gone. Otherwise, returns text content directly.
- If present: Validates
- Database & Storage Fallback: On Redis cache miss, system queries the Metadata DB.
- If not found or
is_deleted == true: Return404 Not Found. - If
expires_at < CurrentTimestamp(): Return410 Goneand schedule asynchronous cleanup. - Fetch target blob payload from S3 (or inline metadata column), decompress payload, store entry in Redis with TTL $=\min(\text{Remaining Paste TTL}, 24\text{ hours})$, and return payload to client.
- If not found or
6. Edge Cases & Operational Trade-offs
1. Handling "Hot" Viral Pastes
- Problem: A popular link creates extreme read concurrency on a single key.
- Solution:
- Single-Flight Request Coalescing: When a cache miss happens for a hot key, local application servers use single-flight locks so only one thread queries S3/Database while all concurrent reader threads block and wait for that single result to populate local cache.
- Multi-tier caching strategy using CDN at the outermost layer, Redis cluster with read-replicas, and local in-memory LRU cache directly inside API workers.
2. Expiration Engine & Soft Deletions
- Lazy Eviction: Expiration dates are checked on every read path call. Even if a background removal worker has not processed an expired paste, users will not be able to read it.
- Asynchronous Purge Engine: A scheduled background job (or native cloud TTL mechanisms like AWS DynamoDB TTL) scans metadata partition ranges periodically during low-traffic windows. It marks expired entries, removes associated object storage files from S3, and purges corresponding keys from Redis.
- S3 Lifecycle Integration: Object storage buckets utilize bucket prefix rules based on creation dates (
pastes/YYYY/MM/DD/) matching short-term paste policies to allow native automated lifecycle deletions.
3. Cache Invalidation & Consistency
- Text content is immutable once submitted (no editing permitted). This simplifies cache consistency.
- When an owner explicitly deletes a paste (
DELETE /v1/pastes/{key}), the system immediately setsis_deleted = truein the DB, evicts keypaste:{key}from Redis, and fires a CDN purge call. - Negative lookups (non-existent keys) are cached in Redis with a short TTL (e.g., 30 seconds) to defend against cache-penetration attacks attempting to exhaust DB connections.