GET /pastepins/{id} On a locked paste, it needs a way to send the password. Don’t put it in the query string, because it ends up in logs. Use POST /pastepins/{id}/unlock, which returns a short-lived access token.List and Stats imply user accounts, so add auth (for example, a bearer token).POST /pastepins/
{
"title": "...",
"description": "...",
"body": "...",
"format": "...",
"expiry": "01.01.2050T00:00:00+00",
"password": "*****"
}
POST /pastepins/{id}/toggle-lock
{
"password": "*****"
}
PUT /pastepins/{id}
{
"title": "...",
"description": "...",
"body": "...",
"format": "...",
"expiry": "01.01.2050T00:00:00+00",
"password": "*****"
}
DELETE /pastepins/{id}
GET /pastepins/{id}
GET /pastepins/
GET /pastepins/{id}/stats
The system is a read-heavy service: about 1,000 reads/s against 10 writes/s, a 100:1 ratio. Most design choices follow from that ratio:
| Component Responsibility Why it's there | ||
| CDN | Serves public, unlocked pastes from edge locations. Cache lifetime is the shorter of 1 hour and the time until the paste expires. | Absorbs viral spikes and most reads, which helps meet the 100 ms target. Locked and private pastes are never cached here. |
| Load balancer + API gateway | Terminates TLS, spreads traffic with least-connections routing, runs health checks, verifies auth, and enforces rate limits. Rate-limit counters live in Redis. | Fans traffic across app servers. Being managed and multi-AZ, it isn't a single point of failure. |
| Paste Service (N instances) | Stateless API for CRUD, unlock, list, and stats. Autoscales on CPU and p99 latency. | At about 5k reads/s at peak, 5–10 instances are enough. |
| Redis | Cache-aside store for paste metadata plus the body. Also holds rate-limit counters. | The hot working set is about 2 GB. A cache hit takes about 1 ms. |
| Postgres (primary + read replicas) | Paste metadata, users, the stats table. | Rows are about 500 B, so roughly 150 GB a year. Supports listing by owner and scanning by expiry. |
| S3 | Paste bodies at pastes/{id}/v{n}. | About 3 TB a year, cheap and highly durable. Keeping blobs out of the database keeps its indexes in memory. |
| Kafka → aggregator → Stats DB | Asynchronous view counting and unique-viewer estimates, plus raw events sent to a warehouse. | Avoids running 1,000 counter writes/s and hot-row contention on the read path. |
| Expiry Sweeper | A cron job that deletes expired pastes, including every stored version. | Keeps storage capped at about 3 TB, given the one-year maximum expiry. |
Any instance can serve any request, so the load balancer needs no sticky sessions, and instances can be added or removed freely:
Create: POST /pastepins
pastes/{id}/v1.201 with the ID and URL.Read: GET /pastepins/{id}
expires_at has passed or deleted_at is set, it returns 404.401.POST /pastepins/{id}/unlock.200.Cache-Control header.private, no-store.Update: PUT /pastepins/{id}
v{n+1}.version and content_key.v{n} asynchronously.Because each version has its own key, a cache can never serve half-written content.
Delete: DELETE /pastepins/{id}
deleted_at (a soft delete), so reads return 404 immediately.Stats: GET /pastepins/{id}/stats
Lazy check on read: every read checks expires_at, so an expired paste is never served, even before cleanup runs.
Sweeper: about 10 pastes expire per second, so the sweeper works in batches of 1,000. The steps are ordered so a crash at any point is safe to retry:
WHERE expires_at < now() LIMIT 1000, using the expires_at index.deleted_at on each row as a tombstone.pastes/{id}/, all versions, not only the current one.Orphan reconciler: a weekly job deletes S3 prefixes with no matching metadata row. These come from uploads that succeeded when the database insert then failed.
| Layer Scaling Failure handling | ||
| CDN and load balancer | Managed, global | Multi-AZ, health checks |
| App servers | Horizontal autoscaling | Stateless; a failed instance is simply replaced |
| Redis | Cluster mode, sharded by key | Replicas; if the cache is down, reads fall back to the database |
| Postgres | Read replicas, later hash-sharded by id | Synchronous standby with automatic failover |
| S3 | Effectively unlimited | 11 nines of durability |
| Analytics | Kafka partitioned by paste_id | If it fails, stats lag but reads keep working |
Entities
| TableColumnsNotes | ||
users | id (PK), email (unique), password_hash, created_at | Optional: anonymous pastes are allowed |
pastes | id CHAR(8) (PK), owner_id (FK, nullable), title, description, format, content_key, size_bytes, password_hash (nullable), visibility (public/unlisted/private), version, expires_at, created_at, updated_at, deleted_at | content_key is something like pastes/aZ3k9QpL/v3 |
paste_stats | paste_id (PK), total_views, unique_views (HLL sketch), last_viewed_at | Updated in batches by the aggregator |
paste_views_daily (warehouse) | paste_id, date, views, unique_views, referrer, country | Feeds the stats charts |
Relationships: one user has zero or more pastes, and each paste has one stats row.
Indexes:
(owner_id, created_at DESC) for List.(expires_at) for the expiry sweeper.SQL vs NoSQL: why I’d choose Postgres here
id using hash partitioning.The NoSQL alternative: DynamoDB or Cassandra keyed by id is also defensible. DynamoDB’s native TTL gives expiry for free, and the bodies could be stored inline because 10 KB is well under item limits. The cost is a second index (a GSI) for listing by owner, plus weaker ad-hoc querying. At this scale, either choice works. Pick one and explain the tradeoff.
Requirements:
How many IDs do we need? About 315M a year.
| ApproachProsCons | ||
| Hash of content (MD5 → base62, truncated) | Deduplicates identical pastes | Identical pastes collide. Leaks whether some content already exists. Truncation still needs collision handling. |
| Global counter → base62 | No collisions, simple | IDs are sequential, so anyone can enumerate every paste. Also needs coordination. |
| Pre-generated key service (KGS) | Fast, no collisions | An extra stateful service. Overkill at 10 writes/s. |
| Random 8 chars from a CSPRNG plus insert-if-absent ✅ | Unguessable, stateless, simple | Collisions are rare and are handled by retrying |
My choice: random 8-character IDs.
Caching layers:
Cache-Control: max-age = min(1h, time until expiry) so the CDN never serves an expired paste.paste:{id} holds metadata plus the body if it’s under about 100 KB.Invalidation on update or delete:
v{n+1}) and update the row’s version and content_key.Password-protected pastes:
POST /pastepins/{id}/unlock with the password.GET requests send the token in a header, so the service doesn’t rerun the expensive hash check on every read.Cache-Control: private, no-store.The naive approach: run UPDATE paste_stats SET views = views + 1 on every read.
The design:
{paste_id, ts, ip_hash, referrer, country} to Kafka with a fire-and-forget producer, so the read path doesn’t wait.paste_id, then write one batched upsert per paste per minute to paste_stats. This turns 1,000 writes/s into a few hundred upserts per minute.Stats are eventually consistent, about a minute behind. That is acceptable, and I’d state it as a deliberate tradeoff.
The CDN gotcha (a good staff-level point): reads served by the CDN never reach the origin, so they never produce view events. Two fixes:
expires_at < now() and returns 404/410. Correctness never depends on the cleanup job.expires_at index, deletes them in batches of about 1,000, deletes the S3 objects, and evicts the cache keys.deleted_at first; hard deletion happens on the next sweep. This also allows a short undo window.| LayerHow it scalesFailure handling | ||
| Paste service | Stateless, horizontal autoscaling | Multi-AZ behind the load balancer |
| Redis | Cluster mode, shard by key | Replicas; if Redis is down, fall back to the DB |
| Postgres | Read replicas, then hash-shard by id | Synchronous standby in another AZ with automatic failover |
| S3 | Effectively unlimited | 11 nines of durability |
| Kafka and analytics | Partition by paste_id | Losing stats never breaks reads (graceful degradation) |