Vineet Ganti
System Design from the Database Up: A Twitter Feature and a URL Shortener
All posts

Data Engineering/Database Engineering · Part 10 of 14

·16 min read

System Design from the Database Up: A Twitter Feature and a URL Shortener

The course's system design sessions, with the tables built and the trade-offs measured: how a tweet gets stored, what a follow button costs, why short codes collide, and the home timeline the course never got to.

DatabasesSystem DesignPostgreSQLBackend

System design tends to get taught as a set of diagrams to memorise. The course does the opposite. It talks through a Twitter clone and a URL shortener with no prepared answer, starting from the simplest thing and asking what breaks. Its repeated line is that there's no perfect design, only trade-offs you can explain.

The sessions are mostly talk and whiteboard, so there was less to re-run here. What I could do is build the tables they describe and measure the claims. I also added the one big piece the course never reached: the home timeline.

#How the course designs things

The method is more useful than either answer. It goes like this:

  1. Write down the features. For Twitter: post a tweet, follow someone, see a home timeline.
  2. Draw the simplest thing that could work.
  3. Ask what fails, and at what scale.
  4. Add a component only for a reason you can state. "Let's not introduce complicated things unless we absolutely have a problem."

And a warning that I found refreshing: don't watch videos that present one final design. There's no such thing. A team with different constraints would draw something else, and be right.

#Part 1: posting a tweet

The simplest design is a client, a server and a database:

Request or acknowledgmentDataMetadata

HTTP is chosen for a dull, good reason: everything speaks it, so the client and server can be anything. Now ask what fails.

The insert fails. The server can retry, but then the client waits, and the server holds memory for each one in flight.

A burst arrives. Each request needs a database connection, and connections are limited.

The server is the limit. One machine can't take it all.

Each answer adds a box:

Request or acknowledgmentData

  • A connection pool on each server, because opening connections is slow. Post 8 measured that at 11 times slower per request.
  • A queue such as Kafka or RabbitMQ, so a spike or a slow database doesn't reach the client. The price: "posted" now means "accepted", and the tweet appears a little later.
  • A load balancer to spread clients over servers.
  • Retries need care. If the client retries after a timeout, a tweet may post twice, which is what idempotency keys are for.

#Load balancing

The course spends a while here, because the choice has real consequences:

Layer 4Layer 7
SeesTCP packetsHTTP requests
TLSPasses throughTerminates, so it holds certificates and keys
RoutingPer connectionPer request: by URL, header, version
ConnectionsOne pathTwo: client to balancer, balancer to server
FeaturesFew, and very fastCaching, retries, blue-green releases

🎓 There's a third option: no balancer at all. The client holds a list of servers and picks one, which the course says Netflix has done to avoid an extra hop. It makes clients more complex, and you lose the ability to shift traffic centrally. The course also likes HTTP/2 end to end, since many requests share one connection, which saves the memory that per-request connections would cost.

#Part 2: the follow feature

A follow is one row: who follows whom. The course considers a list field on the profile and backs away, for reasons post 4 measured. I built its table with a million-follower celebrity and 100,000 ordinary users:

sql
CREATE TABLE follows (follower bigint NOT NULL, followee bigint NOT NULL, PRIMARY KEY (follower, followee));
CREATE INDEX follows_followee ON follows (followee, follower);

The primary key answers "who do I follow?", and the second index answers "who follows me?". The course's reasoning for accepting two indexes is that reads far outnumber follows. Here are the three queries a profile page needs:

✅ ran here · PostgreSQL 18.6 · the queries behind a profile
SELECT count(*) AS followers FROM follows WHERE followee = 1;
 followers 
-----------
   1000000
(1 row)

Time: 47.074 ms

SELECT count(*) AS following FROM follows WHERE follower = 2;
 following 
-----------
        21
(1 row)

Time: 0.521 ms

SELECT EXISTS (SELECT 1 FROM follows WHERE follower = 2 AND followee = 1) AS am_i_following;
 am_i_following 
----------------
 t
(1 row)

Time: 0.187 ms

EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF) SELECT count(*) FROM follows WHERE followee = 1;
                                   QUERY PLAN                                   
--------------------------------------------------------------------------------
 Finalize Aggregate (actual rows=1.00 loops=1)
   Buffers: shared hit=7866 read=8351
   ->  Gather (actual rows=3.00 loops=1)
         Workers Planned: 2
         Workers Launched: 2
         Buffers: shared hit=7866 read=8351
         ->  Partial Aggregate (actual rows=1.00 loops=3)
               Buffers: shared hit=7866 read=8351
               ->  Parallel Seq Scan on follows (actual rows=333333.33 loops=3)
                     Filter: (followee = 1)
                     Rows Removed by Filter: 666667
                     Buffers: shared hit=7866 read=8351
(12 rows)

Time: 49.009 ms

EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF) SELECT EXISTS (SELECT 1 FROM follows WHERE follower = 2 AND followee = 1);
                                    QUERY PLAN                                    
----------------------------------------------------------------------------------
 Result (actual rows=1.00 loops=1)
   Buffers: shared hit=4
   InitPlan 1
     ->  Index Only Scan using follows_pkey on follows (actual rows=1.00 loops=1)
           Index Cond: ((follower = 2) AND (followee = 1))
           Heap Fetches: 0
           Index Searches: 1
           Buffers: shared hit=4
(8 rows)

Time: 0.414 ms

Looking at those numbers as a designer:

  • "Am I following?" takes 4 pages and 0.2 ms. It runs on every profile view to set the button, and that's fine.
  • Counting followers took 47 ms for the celebrity. The planner chose a parallel table scan, since she's a third of the table. That's too slow to run on every view, so keep a counter, and accept that it can lag. As the course says of likes: 3.2 million against 3.1 million doesn't matter.
  • Listing followers must be paged, for the reasons in post 8. You never send 4 million rows.

The course also makes a design point about the page itself: send the profile first, and load the counts and the button state in separate requests, so a user sees something straight away. Each is a separate small query, and the slow one can't hold up the rest.

Try the table yourself:

The follows tableruns in your browser
One row per follow, with an index for each direction. Try the Follow button's query, and see what a counter would save.
Real PostgreSQL loads when you press Run: about 6 MB, once per visit.

#The part the course never reached

The course plans three features and covers two: I confirmed that the home timeline never arrives in these sessions. It's the most interesting one, so here's the classic trade-off, measured.

Pull builds the timeline when you open the app. On a table of two million tweets, with an index on author and id:

At 5k accounts followed: 52.8 ms ✅ measured on PostgreSQL 18.6

Push copies each tweet into a per-user timeline table, so reading is one index range:

At 1M followers: 1,167 ms ✅ measured on PostgreSQL 18.6

The numbers show the shape of the problem. Pull costs in proportion to how many accounts you follow, for every read. Push costs in proportion to your followers, once per tweet: trivial for most people, and over a second of writes for a million-follower account. At real scale that's hundreds of millions of rows for one tweet.

So the usual answer is a mix: push for ordinary accounts, pull for celebrities, and merge them when reading. I'm describing that from general knowledge, not from the course or a test, so treat it as 📘 a well-known pattern rather than something proven here.

#Part 3: a URL shortener

#Design one: generated ids

A table with a serial id and a long URL. The short URL is the id:

✅ ran here · PostgreSQL 18.6
CREATE TABLE urls (id bigserial PRIMARY KEY, long_url text NOT NULL);

INSERT INTO urls (long_url) VALUES ('https://example.com/a'), ('https://example.com/b') RETURNING id;
 id 
----
  1
  2
(2 rows)

SELECT long_url FROM urls WHERE id = 2;
       long_url        
-----------------------
 https://example.com/b
(1 row)

This is simple and fast. The primary key is the only index, and sequential inserts are the best case for it. The drawback is that short URLs are guessable. Anyone can walk through ids and find everything anyone has shortened.

#Design two: hash codes

To get unguessable codes, hash the long URL and keep the first few characters. The primary key on the code catches clashes, and ON CONFLICT handles a repeat:

✅ ran here · PostgreSQL 18.6
CREATE TABLE urls (short_url char(8) PRIMARY KEY, long_url text NOT NULL);

INSERT INTO urls VALUES (left(encode(sha256('https://example.com/a'::bytea), 'base64'), 8), 'https://example.com/a') RETURNING short_url;
 short_url 
-----------
 Lc4KTFBE
(1 row)

INSERT INTO urls VALUES (left(encode(sha256('https://example.com/a'::bytea), 'base64'), 8), 'https://example.com/a');
ERROR:  duplicate key value violates unique constraint "urls_pkey"
DETAIL:  Key (short_url)=(Lc4KTFBE) already exists.

INSERT INTO urls VALUES (left(encode(sha256('https://example.com/a'::bytea), 'base64'), 8), 'https://example.com/a') ON CONFLICT (short_url) DO NOTHING;

The third statement printed nothing and did nothing, which is what you want for a URL shortened twice. But a different URL can land on the same prefix too, and then you need a salt and a retry. How often that happens depends entirely on the length. I hashed a million real URLs:

At 1M URLs shortened: 4 characters 29,032 · 5 characters 436 · 6 characters 8 · 8 characters 0 ✅ measured on 1,000,000 real SHA-256 hashes
Code lengthPossible codesClashes in a million URLs
4About 17 million29,032
5About 1 billion436
6About 69 billion8
8About 281 trillion0

This is the birthday problem: clashes arrive far sooner than the number of codes suggests. The course's 8 characters is a safe choice at this size, and the 5 characters in the sharding demo would need that salt loop quite soon. A random code also makes inserts scatter across the index, as post 4 showed.

Two short URL designsruns in your browser
Generated ids are easy and guessable. Hash codes are unguessable and can collide. Try both.
Real PostgreSQL loads when you press Run: about 6 MB, once per visit.

The course adds that a write-heavy version might suit an LSM engine such as MyRocks, which post 11 explains.

#Scaling it

The key fact is the read-to-write ratio: a short link is created once and clicked many times. So split the paths:

Request or acknowledgmentDataMetadata

A reverse proxy sends POST to a writer, and GET to readers on replicas. Replicas can sit near users, and the replication lag is harmless here: a new short link that takes a moment to resolve elsewhere doesn't hurt anyone. Only if writes outgrow one primary do you reach for sharding.

#Things that can trip you up

  • Designing for scale you don't have. Each box adds failure modes of its own.
  • A queue changes what "done" means. The client's success is now "accepted".
  • Counts computed on read. Fine for small accounts, and a problem for the biggest.
  • Layer 7 balancers terminate TLS. They can read your traffic, so they're part of your security boundary.
  • Assuming a hash won't collide. Prefixes collide much sooner than intuition says.
  • Sequential public ids. They reveal your volume and let people enumerate.
  • Copying a design from a video. Including this one. The constraints are what matter.

#Reproduce this yourself

  1. ✅ Build the follows table as above, load a celebrity and some ordinary users, and run the queries. The plans depend on the ratio of the two, as the parallel scan shows.
  2. ✅ For the timeline, I used tweets (id, author, body) with an index on (author, id DESC), and a LATERAL query taking the 20 latest per followed account:
    sql
    SELECT t.id, t.author, t.body
    FROM follows f CROSS JOIN LATERAL (
      SELECT * FROM tweets t WHERE t.author = f.followee ORDER BY t.id DESC LIMIT 20
    ) t
    WHERE f.follower = 1 ORDER BY t.id DESC LIMIT 20;
    
  3. ✅ For push, time INSERT INTO timelines SELECT g, 1 FROM generate_series(1, n) g.
  4. ✅ For collisions, hash numbered URLs with SHA-256, encode with base64url, cut to each length, and count repeats in a set.
  5. 🎓 The queue, balancer and HTTP/2 parts are design discussion in the course, and I didn't build them.

#Glossary

TermMeaning
Load balancerSpreads traffic across servers
Layer 4, layer 7Balancing by TCP connection, or by reading the HTTP request
Reverse proxyA server in front that forwards requests to backends
Message queueA buffer between producers and consumers
Fan-outDelivering one event to many recipients
Pull, pushBuilding a feed at read time, or at write time
Birthday problemWhy collisions appear far earlier than the size of the space suggests

#Summary

The course's lesson is a way of working: start simple, ask what fails, and justify every box. Posting a tweet gained a pool, a queue and a balancer, each for a stated reason. A follow is a cheap row, and the expensive questions are the counts, so the design stores them. A timeline can pay at read time or write time, and the measurements show why the biggest accounts force a mix. A short URL trades guessable ids against colliding hashes, and because reads dominate, the system splits its read and write paths.

#Concepts at a glance

ConceptIn one lineWhy it matters
Start simpleAdd a box only for a named failureComplexity is a cost
QueueAbsorbs spikes, changes what "done" meansProtects the database
L4 or L7Packets or requestsDecides routing, and who holds TLS keys
Two indexes on followsOne for each directionReads outnumber follows
Stored countersAccept a little lagCounting on each view is too slow
Pull or pushPay at read time or write timeCelebrities break pure push
Short code lengthClashes grow with the square of the countLength is a design decision
Read and write pathsReads go to replicasReads dominate

#Test yourself

A queue sits between your servers and the database. What do you gain, and what does a client's "success" now mean?

You gain protection from spikes and a place to retry. Success now means the write was accepted, not that it's stored. It may appear a little later, and it can still fail after the reply.

Why can't a layer 4 load balancer route /api to one set of servers and /static to another?

It only sees TCP packets and doesn't decrypt or parse HTTP, so it has no idea of the URL. A layer 7 balancer can, because it terminates the connection and reads each request, which means it also holds the TLS keys.

Why not count a user's followers on every profile view?

For most users it's cheap. For a celebrity it reads a large share of the table: 47 ms here, on every view. A stored counter that's slightly stale is fine, because nobody can tell 3.2 million from 3.1 million.

A celebrity with 50 million followers posts. Why is fan-out on write a problem, and what's the usual answer?

It means 50 million timeline writes for one tweet. The usual answer is a mix: push for ordinary accounts, and pull the few celebrities' tweets at read time, merging the two.

Why do 5-character codes collide so early, given that there are about a billion of them?

The birthday problem: each new code can clash with every code already issued, so clashes grow with the square of the count. In a million URLs that gave 436 clashes.

#Open questions and gaps

  • The course's Twitter sessions end after the follow feature. The timeline section is mine, and its hybrid answer is general knowledge, not something I built or the course stated.
  • 🎓 The queue, load balancer and HTTP/2 discussions are reported, not run. The Netflix remark is from the course and I didn't check it.
  • I measured single-client timings on a laptop, so they show how costs grow and not what a real service would see.

#Sources