It's just likes + 1, right?
Start with what almost everyone writes first. The post has a row in the database, and the like count is a column in that row:
CREATE TABLE posts ( id BIGINT PRIMARY KEY, likes BIGINT NOT NULL DEFAULT 0 );
When someone taps the heart, the server reads the number, adds one, and writes it back:
def like(post_id): likes = db.query("SELECT likes FROM posts WHERE id = %s", (post_id,)) db.execute("UPDATE posts SET likes = %s WHERE id = %s", (likes + 1, post_id))
Watch what happens when two taps collide
Two people tap at the same moment. Their requests go to two different servers. Follow the numbers.
Two likes, but the counter moved by one. This bug is called a lost update. With a few likes a minute it's rare. With thousands a second, it happens constantly.
The textbook fix: let the database do the math
UPDATE posts SET likes = likes + 1 WHERE id = 42;
Now the read and the add happen inside the database. To keep that safe, the database takes a row lock on row 42 and holds it until the update commits. Any other update to row 42 has to wait for that lock. No more lost updates.
The hot row
1,000,000 likes ÷ 60 seconds, all aimed at one row. Real traffic spikes even higher.
One update at a time, if each holds the lock ~1 ms. Illustrative numbers, real shape.
Waits get longer, database connections run out, requests time out, and other queries on the same database slow down too. Adding more app servers doesn't help: they all line up for the same lock.
The waiting itself is called lock contention. It's a classic interview topic because a bigger machine doesn't make it go away.
One counter vs. many counters
A scaled-down simulation. Each heart is a like; each lane is a counter row that updates one like at a time.
Databases document it. In Google Cloud Firestore, frequent updates to a single document eventually cause contention, so the docs recommend distributed counters: the same idea as the next chapter.
Don't keep one counter. Keep a hundred.
It sounds silly. Instead of one likes number, the post gets 100 small counters. Every tap picks one at random and adds 1 to it. Updates that land on different counters don't wait for each other, so up to 100 can run at the same time.
CREATE TABLE post_like_shards ( post_id BIGINT, shard_id SMALLINT CHECK (shard_id BETWEEN 0 AND 99), count BIGINT NOT NULL DEFAULT 0, PRIMARY KEY (post_id, shard_id) ); -- write path (PostgreSQL). :shard_id is a bind parameter: random 0..99 INSERT INTO post_like_shards (post_id, shard_id, count) VALUES (42, :shard_id, 1) ON CONFLICT (post_id, shard_id) DO UPDATE SET count = post_like_shards.count + 1;
import random SHARDS = 100 def like(post_id): shard = random.randrange(SHARDS) # spread the load db.execute(""" INSERT INTO post_like_shards (post_id, shard_id, count) VALUES (%s, %s, 1) ON CONFLICT (post_id, shard_id) DO UPDATE SET count = post_like_shards.count + 1 """, (post_id, shard))
This pattern is called a sharded counter. You'll also hear distributed counter or striped counter. Two things make it work:
Shards are interchangeable for writes. It doesn't matter which one gets the +1, only that the sum is right. And shards are just rows: all 100 can live in the same database. You're splitting the lock, not buying 100 machines.
So what's the total?
The real count is now the sum of every shard:
SELECT COALESCE(SUM(count), 0) FROM post_like_shards WHERE post_id = 42;
Running that once is fine. Running it for every person who opens the post is wasteful: a viral post has far more viewers than likers, and each view would read 100 rows. So we add it up once and cache the result for a few seconds:
def like_count(post_id): key = f"likes:{post_id}" total = cache.get(key) # e.g. Redis if total is None: # cache miss: add it up once total = db.query("SELECT COALESCE(SUM(count), 0) FROM post_like_shards WHERE post_id = %s", (post_id,)) cache.set(key, total, ttl=3) # fresh enough for a like count return total
The number under the post can be a few seconds stale. While likes pour in it's a little lower than the truth, and it catches up when the cache refreshes. This is called eventual consistency. It's fine for a like count. For a bank balance, you'd design this very differently.
When the cached total expires, thousands of viewers can miss at the same moment and all run the SUM. Let only one request recompute it (a short lock, often called single-flight), or have a background job refresh the total every few seconds so viewers never wait.
The architecture
Writes and reads now take separate paths, and each is built for its own load. Use the buttons to follow one at a time.
The counter only stores a number. To stop someone liking twice, insert into likes(user_id, post_id) with a unique key, and add +1 to a shard in the same transaction, only if that insert succeeded. Save the chosen shard_id in the like row too: on unlike, delete the row and subtract 1 from that same shard.
Trade-offs to say out loud
Interviewers care less about the pattern's name and more about whether you know what it costs.
01Reads cost more
Writes are spread out, but a fresh total has to read all N shards. That's why you usually cache it.
02Choosing N
Too few and the hot row comes back. Too many and every sum gets slower. Start with 1 and split only hot posts when their write rate crosses a threshold.
03A few seconds stale
The shown number lags behind. Fine for likes and views, not fine for money or seats left on a flight.
04More rows
100 rows per hot post instead of 1. Cheap for a few thousand viral posts, wasteful if you shard every post.
Other designs worth mentioning
In-memory counter + flush
Increment in Redis (INCR is atomic and very fast) and save the number to the database every few seconds. One key still lives on one Redis primary, and you can lose the last few seconds of likes unless persistence and replication are set up.
Queue + batching
Each like becomes an event on a queue such as Kafka. A consumer adds them up per post per second and does one likes = likes + 4812. Events can be replayed, as long as the consumer is idempotent so a replay doesn't count twice.
Big systems often combine these: an event log for durability, aggregated or sharded counters for the number, and a cache for reads.
The puzzle from the video
Hint: it depends on what "crash" means, and where the counter lives.
The checklist
When you get "design a like counter", walk through these in order. Tick them off as you practise.
- Requirements. Peak likes per second, reads vs writes, and does the count need to be exact in real time?
- Naive design, then the lost update race.
- Atomic increment, then the hot row / lock contention problem, with numbers.
- Sharded counter: schema, write path, choosing N, sharding only hot posts.
- Read path: sum + cache with a TTL, stampede protection, eventual consistency.
- Dedupe with a
likes(user_id, post_id)table, in the same transaction. - Failure modes: shard down, cache down, retries, double likes, unlikes.
- Alternatives: Redis + flush, queue + batching, and when you'd pick each.
Watch it in 90 seconds
The whole story, animated, on the DevSecRoot YouTube channel.