Design Pastebin
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite students want to share an error log or lab code with a mentor through a link, not a screenshot. It is almost the URL shortener again, except each item is a large block of text.
Your turn: sharing a stack trace
A student pastes a 60 KB stack trace and sends the link to a mentor. Assume 100,000 pastes a day, each read about 10 times, and each kept for at most a week. Think first:
- Where would you keep the text: in the database or somewhere else, and why?
- Can you reuse the shortener's counter for the link? What could go wrong for private pastes?
- After a week, who removes a paste, and what does a reader see?
Write down your answers, then compare them with the design below.
Requirements: create, read, expiry and a size limit
Unlisted means anyone who has the link can read a paste, but the paste is never shown in lists or search, so the link itself works like a password.
The requirements, then a program that turns 100,000 pastes a day into writes per second and terabytes.
Example 1 · Estimate traffic and storage
public class PasteEstimateDemo { public static void main(String[] args) { long pastesPerDay = 100_000; int readsPerWrite = 10; long avgPasteBytes = 10_000; // about 10 KB of text long metadataBytes = 300; // id, key, size, times, owner int years = 5;
long pastes = pastesPerDay * 365 * years; double contentTb = (double) pastes * avgPasteBytes / 1e12; double metadataGb = (double) pastes * metadataBytes / 1e9; double writesPerSecond = pastesPerDay / 86_400.0; double readsPerSecond = writesPerSecond * readsPerWrite;
System.out.printf("Writes per second: %.1f%n", writesPerSecond); System.out.printf("Reads per second: %.1f%n", readsPerSecond); System.out.println("Pastes in " + years + " years: " + pastes); System.out.printf("Paste text: %.2f TB%n", contentTb); System.out.printf("Metadata rows: %.1f GB%n", metadataGb); }}Writes per second: 1.2 Reads per second: 11.6 Pastes in 5 years: 182500000 Paste text: 1.83 TB Metadata rows: 54.8 GB
What this code does
- 100,000 pastes a day is only about 1.2 writes per second; reads are about 12 per second.
- The text, 1.83 TB in five years, is about 33 times bigger than the metadata rows, which is why they are stored apart.
Functional requirements: create a paste and get a link, read a paste by its link, and choose an expiry (10 minutes, 1 day, 1 week or never). Pastes can be public or unlisted.
Non-functional requirements: reads are fast, pastes are never lost before they expire, and one paste is at most 512 KB, which protects the disks from huge uploads. With 100,000 new pastes a day and 10 reads each, traffic is small: about 1 write and 12 reads per second. The text is the big number: about 1.8 TB in five years.
Metadata in the database, text in object storage
Object storage is a service that stores files, called objects, by a key, such as Amazon S3 or Google Cloud Storage. It is cheap per GB, very durable and grows without limits, but it has no SQL queries.
One paste is split in two: a small row in the database and the text in object storage. The diagram shows create and read; the Java sketch keeps both stores in maps.
(1) [Client] --POST /api/v1/pastes--> [App server](2) [App server] --check size, make random key--> itself(3) [App server] --PUT pastes/Xk29fQa1.txt--> [(Object storage)](4) [App server] --INSERT metadata row--> [(MySQL pastes table)](5) [App server] --201 + link--> [Client]Read: [Client] --> [CDN] --miss--> [App server] --> [(MySQL)] + [(Object storage)]Example 2 · Metadata row in the DB, text in object storage
import java.util.HashMap;import java.util.Map;
record PasteMeta(String id, String objectKey, int sizeBytes, String syntax, long expiresAt) {}
class ObjectStore { private final Map<String, String> blobs = new HashMap<>(); long bytes = 0;
void put(String key, String content) { blobs.put(key, content); bytes += content.length(); }
String get(String key) { return blobs.get(key); }}
class MetadataDb { private final Map<String, PasteMeta> rows = new HashMap<>();
void insert(PasteMeta meta) { rows.put(meta.id(), meta); }
PasteMeta find(String id) { return rows.get(id); }
int count() { return rows.size(); }}
public class PasteSplitStorageDemo { public static void main(String[] args) { MetadataDb db = new MetadataDb(); ObjectStore store = new ObjectStore();
String log = "ERROR at OrderService.java:42\n".repeat(2_000); // a big stack trace String notes = "DBMS unit 3: normalisation, 1NF to BCNF";
createPaste(db, store, "Xk29fQa1", log, "text"); createPaste(db, store, "Pq7LmZ03", notes, "markdown");
PasteMeta meta = db.find("Xk29fQa1"); System.out.println("Metadata row: " + meta); System.out.println("Content starts: " + store.get(meta.objectKey()).lines().findFirst().orElse("")); System.out.println("Rows in DB: " + db.count()); System.out.println("Bytes in object storage: " + store.bytes); }
static void createPaste(MetadataDb db, ObjectStore store, String id, String content, String syntax) { String key = "pastes/" + id + ".txt"; store.put(key, content); // 1. the big text goes to object storage db.insert(new PasteMeta(id, key, content.length(), syntax, 0)); // 2. the small row goes to the DB }}Metadata row: PasteMeta[id=Xk29fQa1, objectKey=pastes/Xk29fQa1.txt, sizeBytes=60000, syntax=text, expiresAt=0] Content starts: ERROR at OrderService.java:42 Rows in DB: 2 Bytes in object storage: 60039
What this code does
createPastewrites the text to the object store first, then the smallPasteMetarow that points to it withobjectKey.- The 60,000-byte log lives only in the object store; the database row holds its size and key.
- Writing the object first means a row never points to missing text. If the row insert fails, the cleanup job can delete the orphan object.
The design splits each paste in two. The small metadata row (id, object key, size, syntax, owner, created and expiry times) goes to the database. The text itself goes to object storage under a key such as pastes/Xk29fQa1.txt.
This keeps the database small: 55 GB of rows instead of 1.8 TB of text, so it stays fast, cheap to back up and easy to index. Object storage can also be read directly by a CDN for popular pastes.
Order of execution
Create a paste
Put the steps of POST /api/v1/pastes in the right order.
Keys: reuse the shortener idea, but make them unguessable
Unguessable key is an identifier drawn from a secure random source, so knowing one key tells nobody anything about another. It protects unlisted pastes, whose only protection is the link.
A counter key has neighbours an attacker can try; a random key does not. The program shows both and counts the key space.
Example 3 · Guessable counter keys vs random keys
import java.math.BigInteger;import java.security.SecureRandom;import java.util.HashSet;import java.util.Set;
public class PasteKeyDemo { static final String ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; static final SecureRandom RANDOM = new SecureRandom();
static String encode(long n) { StringBuilder sb = new StringBuilder(); do { sb.append(ALPHABET.charAt((int) (n % 62))); n /= 62; } while (n > 0); return sb.reverse().toString(); }
static String randomKey(int length) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { sb.append(ALPHABET.charAt(RANDOM.nextInt(62))); } return sb.toString(); }
public static void main(String[] args) { long myPasteId = 56_800_300_000L; System.out.println("My private paste: " + encode(myPasteId)); System.out.println("An attacker tries: " + encode(myPasteId - 1) + ", " + encode(myPasteId + 1));
Set<String> issued = new HashSet<>(); while (issued.size() < 100_000) { issued.add(randomKey(8)); // a key already used is not added, so the loop draws again } System.out.println("Random 8-char keys issued: " + issued.size()); System.out.println("Every key has length 8: " + issued.stream().allMatch(k -> k.length() == 8));
BigInteger space = BigInteger.valueOf(62).pow(8); BigInteger pastes = BigInteger.valueOf(1_000_000_000L); System.out.println("8-char key space: " + space); System.out.println("With 1 billion pastes, one guess hits 1 in " + space.divide(pastes)); }}My private paste: 1000gKY An attacker tries: 1000gKX, 1000gKZ Random 8-char keys issued: 100000 Every key has length 8: true 8-char key space: 218340105584896 With 1 billion pastes, one guess hits 1 in 218340
What this code does
- A counter key has neighbours one step away, so an attacker can walk through them.
randomKeypicks each of 8 symbols withSecureRandom.nextInt(62); theSetmakes sure each key is used once.- Dividing 62⁸ by 1 billion pastes shows how rare a lucky guess is: 1 in about 218,000.
The key is generated the same way as a short code: base62 symbols, checked for uniqueness. The difference is privacy. A counter-based key such as 1000gKY tells an attacker that 1000gKX and 1000gKZ probably exist, so they can read other people's unlisted pastes. So Pastebin keys must be unguessable: draw each symbol from SecureRandom, a random number source made for security, and check that the key is not already used. With 8 symbols there are 62⁸, about 218 trillion keys.
Even with 1 billion stored pastes, one random guess finds a paste only about once in 218,000 tries. Add rate limiting on reads and a wall of guesses becomes useless.
SecureRandom, not Random, for keys that protect data. Random is predictable once someone sees a few outputs.Expiry cleanup job and CDN caching
Lazy deletion means an expired item is treated as gone the moment someone asks for it, because every read checks expires_at, even though a background job removes the stored data only later.
A cleanup job that deletes expired pastes in batches, and a helper that decides how long a CDN may cache a paste.
Example 4 · Cleanup job and CDN max-age
import java.util.ArrayList;import java.util.List;import java.util.TreeMap;
public class PasteCleanupDemo { // expiresAt (seconds) -> paste ids that expire then; TreeMap keeps them sorted by time static final TreeMap<Long, List<String>> byExpiry = new TreeMap<>(); static final long NEVER = Long.MAX_VALUE;
static void add(String id, long expiresAt) { byExpiry.computeIfAbsent(expiresAt, t -> new ArrayList<>()).add(id); }
static List<String> cleanup(long now, int batchSize) { List<String> deleted = new ArrayList<>(); while (!byExpiry.isEmpty() && byExpiry.firstKey() <= now && deleted.size() < batchSize) { List<String> ids = byExpiry.pollFirstEntry().getValue(); deleted.addAll(ids); // real job: delete the object, then the metadata row } return deleted; }
static long cacheSeconds(long expiresAt, long now) { long oneHour = 3_600; return expiresAt == NEVER ? oneHour : Math.min(oneHour, expiresAt - now); }
public static void main(String[] args) { add("quiz-ans", 600); // 10 minutes add("hostel-wifi", 86_400); add("lab-code", 604_800); add("dbms-notes", NEVER); add("otp-log", 600);
System.out.println("Run at 1 hour: deleted " + cleanup(3_600, 100)); System.out.println("Run at 2 days: deleted " + cleanup(172_800, 100)); System.out.println("Still stored: " + byExpiry.values());
System.out.println("CDN max-age for lab-code at 2 days: " + cacheSeconds(604_800, 172_800) + "s"); System.out.println("CDN max-age for a paste ending in 90s: " + cacheSeconds(1_000, 910) + "s"); System.out.println("CDN max-age for dbms-notes: " + cacheSeconds(NEVER, 172_800) + "s"); }}Run at 1 hour: deleted [quiz-ans, otp-log] Run at 2 days: deleted [hostel-wifi] Still stored: [[lab-code], [dbms-notes]] CDN max-age for lab-code at 2 days: 3600s CDN max-age for a paste ending in 90s: 90s CDN max-age for dbms-notes: 3600s
What this code does
- A
TreeMapkeyed by expiry time keeps the soonest expiry first, like a database index onexpires_at. cleanupdeletes only what has expired, at mostbatchSizeitems per run, so one run never locks the system for long.cacheSecondscaps the CDN time at one hour and never past the expiry: a paste ending in 90 seconds is cached for 90 seconds.
Expiry has two parts. On every read the server checks expires_at and answers 404 when the time has passed. A cleanup job then runs every few minutes, finds expired rows by an index on expires_at, and deletes the object and then the row in small batches.
Popular public pastes get many reads, so a CDN (content delivery network: cache servers close to users) can serve them. The app sets Cache-Control: public, max-age=N, where N is never longer than the time left before expiry. Unlisted pastes may be cached; private pastes that need a login must not be cached by a shared CDN.
Single-file simulation: a paste store with TTL and a size limit
TTL (time to live) is how long an item may exist after it is created. A paste created at time now with a TTL of 600 seconds has expiresAt = now + 600 and counts as gone after that moment.
A paste store that rejects text over 512 KB with a 413 and expires pastes by a fake clock.
Example 5 · Paste store with TTL and a size limit
import java.nio.charset.StandardCharsets;import java.util.HashMap;import java.util.Map;
class FakeClock { private long seconds = 0;
long now() { return seconds; }
void advance(long s) { seconds += s; }}
record Paste(String content, long expiresAt) {}
class PasteStore { static final int MAX_BYTES = 512 * 1024; // 512 KB limit private final Map<String, Paste> pastes = new HashMap<>(); private final FakeClock clock; private long nextId = 1;
PasteStore(FakeClock clock) { this.clock = clock; }
String create(String content, long ttlSeconds) { int size = content.getBytes(StandardCharsets.UTF_8).length; if (size > MAX_BYTES) { return "413 Content Too Large (" + size + " bytes)"; } String id = "p" + nextId++; // the real design uses a random 8-char key long expiresAt = ttlSeconds == 0 ? Long.MAX_VALUE : clock.now() + ttlSeconds; pastes.put(id, new Paste(content, expiresAt)); return "201 Created: /" + id; }
String read(String id) { Paste p = pastes.get(id); if (p == null) { return "404 Not Found"; } if (clock.now() >= p.expiresAt()) { pastes.remove(id); // lazy delete on read; a cleanup job removes the rest return "404 Not Found (expired)"; } return "200 OK: " + p.content(); }}
public class PasteStoreDemo { public static void main(String[] args) { FakeClock clock = new FakeClock(); PasteStore store = new PasteStore(clock);
System.out.println(store.create("Wi-Fi password for hostel block C", 600)); System.out.println(store.create("public static void main(String[] args) {}", 0)); System.out.println(store.create("x".repeat(600_000), 600));
System.out.println("t=0 p1 -> " + store.read("p1")); clock.advance(601); System.out.println("t=601 p1 -> " + store.read("p1")); System.out.println("t=601 p2 -> " + store.read("p2")); clock.advance(365L * 86_400); System.out.println("t=1 year p2 -> " + store.read("p2")); System.out.println("t=1 year p9 -> " + store.read("p9")); }}201 Created: /p1
201 Created: /p2
413 Content Too Large (600000 bytes)
t=0 p1 -> 200 OK: Wi-Fi password for hostel block C
t=601 p1 -> 404 Not Found (expired)
t=601 p2 -> 200 OK: public static void main(String[] args) {}
t=1 year p2 -> 200 OK: public static void main(String[] args) {}
t=1 year p9 -> 404 Not FoundWhat this code does
createmeasures the text in UTF-8 bytes, not characters, and refuses anything over 512 KB.- A TTL of 0 means never:
expiresAtisLong.MAX_VALUE, so p2 is still there after one year. readdeletes an expired paste when it meets one (lazy delete) and answers 404, exactly like the real read path.
The simulation keeps pastes in a Map, stores expiresAt = now + ttl, and rejects text over 512 KB with 413 Content Too Large.
A fake clock replaces the real time, so the program can jump forward 601 seconds or one year and still print the same output every run. Real code takes the clock as a parameter for the same reason: tests can control time.
Find the bug
Find the bug in the paste service
Tap the line that is wrong, then read why.
Make a key for an unlisted paste.
Round 1 of 3Next step
Check your understanding
12 quick questions