System design
Pastebin
Paste text or code, get a short link, read it until it expires.
A system design project. I designed it for 30 million active users across three regions, then built and ran one local copy of the design. Reading a paste by its link is the most used feature, so the design is read-heavy.
How to read this page. Each step is marked Built if it exists in the local build, or Design only if it is on paper only. The estimates come from the design, not from measurement.
Requirements
Functional
- Create a paste: paste plain text or code and get a short link.
- Read a paste: anyone who opens the link sees the text. This is the most used feature, so it is where Redis caching goes.
- Code formatting: a paste marked as code is shown with syntax highlighting for its language.
- Expiry: the user sets an expiry time, and after it the paste can no longer be opened.
Non-functional
- High availability: the app stays up in every region, with no single point of failure.
- Fast reads: most traffic is people opening links, so reads must be quick.
- Durability: a saved paste is never lost before it expires.
- Limits: a paste is at most 10,000 characters.
Estimates
- 350writes a second (30M new pastes a day)
- 3,500reads a second (10 reads per paste)
- 60 GBa day at about 2 KB per paste
- 12 GBfor the hottest 20% of a day, fits on one Redis server
- Users: 30 million active users, about 1 new paste a day each. That is 30 million writes a day. A day is about 86,400 seconds, so about 350 writes a second.
- Reads: each paste is opened about 10 times, so 300 million reads a day, or about 3,500 reads a second. Reads outnumber writes 10 to 1.
- Storage: an average paste is about 2 KB, so 30 million pastes is about 60 GB a day, or about 22 TB a year of paste text. Indexes and metadata add roughly 30% to 50%, and replication multiplies the total, so disk across all copies is closer to 90 TB a year. Pastes expire, so what is stored at any time is lower.
- Cache: caching the hottest 20% of a day's pastes is 30 million x 20% x 2 KB, about 12 GB, which fits on one Redis server. This is a sizing guess, not a hit rate. The real hit rate depends on how skewed traffic is, so it would be measured and the cache resized.
API
POST/pastes
Create a paste. Body: text, type (code or plain_text), optional language, expiresIn in seconds (default 86400, min 60, max 2,592,000).
- 201 with the code, the link and the expiry time
- 400 for bad input
- 429 when rate limited
GET/pastes/:code
Read a paste. Returns the code, text, type, language and expiry time.
- 200 with the paste
- 404 if the code does not exist or has expired
Short codes
- A code is 7 characters from 0-9, a-z and A-Z (62 characters). Symbols are left out because characters like / ? # and % have special meanings in URLs. A UUID would be 36 characters, which is too long for a short link.
- Local build: all 7 characters are random, about 3.5 trillion combinations.
- Multi-region design: the first character names the region that owns the paste, and the other 6 are random. That is 62^6, about 56.8 billion codes per region, about 170 billion in total.
- The server inserts the paste with the code as the primary key. If the database rejects the insert as a duplicate, the server makes a new code and tries again, up to 5 times, then returns an error. The database decides uniqueness because two servers could otherwise pick the same code at the same moment and both pass a check made before saving.
- Collisions are certain at scale, so the retry is a real part of the design. With 1 billion pastes in a region, about 1 new code in 57 is already taken. Two collisions in a row is about 1 in 3,000, and five in a row about 1 in 600 million, which is why the retries are capped at 5.
Data model
pastes
PostgreSQL is the source of truth. Exactly one of text and s3_key is set.
- code
- Primary key, the 7-character short code.
- user_id
- Optional link to users.id. Empty for anonymous pastes.
- text
- The paste content. Empty when the paste is stored in S3.
- s3_key
- Where the paste is stored in S3, for pastes over 10 KB.
- type
- code or plain_text.
- language
- For example python, used for syntax highlighting.
- device_info
- Basic information about the device that created the paste.
- created_at
- When the paste was created.
- expires_at
- When the paste stops being readable. Indexed for the cleanup job.
users
The table exists, but accounts are not in version 1.
- id
- Primary key.
- created_at
- When the account was created.
Diagrams
Tap a diagram to enlarge it.
Components
Client
Design onlyA Next.js web app.
API servers
BuiltNestJS servers that hold no state, so more can be added as traffic grows. Locally, three containers.
Load balancer
BuiltNginx sends each request to the server with the fewest open connections. In the design, two Nginx load balancers share one virtual IP so the balancer is not a single point of failure.
Redis
BuiltKeeps copies of popular pastes so most reads skip the database, and holds the rate-limit counters. Each entry expires when the paste does.
PostgreSQL
BuiltStores every paste's metadata, and its text when it is small. One database locally. In the design it is split into shards, each with a primary and read replicas.
S3
BuiltStores the text of pastes larger than 10 KB. MinIO is the local stand-in.
CDN
Design onlyCaches responses for popular pastes close to users in US East, US West and Europe, and drops the least recently used when space runs out.
Regions and failover
Design onlyThree regions. Geo-DNS with health checks sends users away from a failed region after about 30 seconds. Each region's shards have an asynchronous replica in a second region that is promoted if the owning region stays down.
Sharding
Design onlyThe shard is chosen by hashing the code, modulo the number of shards, so any server can find it without a lookup table. Locally the choice is made in one place so shards can be added later.
Write path: create a paste
- 1The user submits the paste.Built
- 2The request goes through the load balancer to an app server.Built
- 3The server checks the size limit and the rate limit.Built
- 4The server makes a short code. In the multi-region design it starts with its own region's character.Built
- 5If the text is over 10 KB, the server uploads it to S3.Built
- 6The server inserts the row into PostgreSQL, retrying with a new code if the code is taken.Built
- 7The server returns the short link.Built
Read path: open a link
- 1The user opens the link. If the CDN has the paste cached, it returns it straight away.Design only
- 2The first character of the code says which region owns the paste. DNS sends the user to the nearest healthy region, and that region forwards the read to the owning region if needed.Design only
- 3Otherwise the request goes through the load balancer to an app server.Built
- 4The server looks up the code in Redis. On a hit it returns the paste.Built
- 5On a miss it reads the row from PostgreSQL (a replica in the design), and the text from S3 if needed, then saves a copy in Redis.Built
- 6If the expiry time has passed, the server returns 404 instead of the text.Built
Expiry
- Each paste stores an expiry timestamp instead of an "expired" flag. A flag needs something to flip it, but a timestamp can be checked on every read.Built
- Redis: each entry's TTL is the time left until expiry, so Redis never serves an expired paste. Missing codes are cached for 30 seconds so repeated bad links do not hammer the database.Built
- A cleanup job runs every hour and deletes expired rows from PostgreSQL and their files from S3.Built
- CDN: each read response carries a Cache-Control header whose lifetime is the paste's remaining life, capped at 1 hour, so the CDN can never serve a paste after it expires. Missing or expired pastes return 404 with a 30-second max-age.Design only
- To remove a paste early, for example for abuse, it is purged from the CDN with a purge call, because a TTL alone cannot do that.Design only
Rate limiting
- Each client can create at most 10 pastes a minute, counted per IP address. The limit is set by an environment variable.Built
- Counts live in Redis under a key that expires after one minute, so every app server sees the same count. A request over the limit gets 429.Built
- Counting has to be atomic. If two requests arrive together they must not both read 9 and both write 10. One Redis transaction increments the key and sets the 60-second expiry only if none exists yet, then checks the number it got back.Built
- IP addresses are shared by offices and mobile networks, so signed-in users would be limited by user id with a higher limit.Design only
Security (design only)
- Paste text is treated as data, never as code. The API returns it as plain text, and the client shows it as text, which escapes any HTML. Syntax highlighting runs on the escaped text.
- Responses use a safe content type, a Content-Security-Policy that blocks inline scripts, and X-Content-Type-Options: nosniff, so a paste cannot run as a script even if someone opens it directly.
- Every paste page has a Report link that saves the code and a reason. A moderator can delete the paste, which also removes it from Redis and purges it from the CDN.
- Pastes are limited to 10,000 characters of text, binary data is rejected, creation is rate limited, and new pastes can be scanned for known bad patterns such as malware links and leaked keys.
- The server never fetches links found in a paste, and device_info is never shown to other users.