InterviewGlide · System Design
System design · interview question

How a like counter survives 1 million likes in one minute

A cricketer posts one photo. Sixty seconds later, a million people have tapped the heart, and the app never froze. Here's what happens behind that number, from the version that breaks to the one that doesn't.

Start reading InterviewGlide Engineering·10 min read·6 live diagrams·1 puzzle
the.cricketer just now
0 likes 0 writes/s
01
The obvious design

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:

schema.sql
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:

like.py · first attempt
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))
USERS APP SERVERS DATABASE app-1 app-2 TABLE posts id 42 likes 500 every like → this one row
Fig 1Every like, from every server, lands on the same row.

Watch what happens when two taps collide

Two people tap at the same moment. Their requests go to two different servers. Follow the numbers.

Tap A · server 1 likes = ? Tap B · server 2 likes = ? DATABASE · post 42 500 expected 502 ← one like lost
Two people tap ♥ at the same moment.

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

atomic.sql
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.

02
The real problem

The hot row

Quick guess
One row, one lock, and each update holds the lock for about a millisecond. Roughly how many likes per second can that row handle?
About 1,000 per second, in theory. If every update holds the lock for ~1 ms (lock, write, log, commit), only one can run at a time, so 1 second ÷ 1 ms ≈ 1,000. Real numbers depend on hardware and database, but for one row it's thousands, not millions. Your viral post needs 16,700.
Demand (average)
16,700 / s

1,000,000 likes ÷ 60 seconds, all aimed at one row. Real traffic spikes even higher.

vs
One row (theoretical)
~1,000 / s

One update at a time, if each holds the lock ~1 ms. Illustrative numbers, real shape.

ROW 42 500 waiting: 0 one at a time →
Fig 3Likes arrive faster than the lock lets them through. The line only grows.

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.

Engineers call this a hot row. The servers aren't the bottleneck. One piece of data is.

The waiting itself is called lock contention. It's a classic interview topic because a bigger machine doesn't make it go away.

Try it yourself

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.

live
Counter rows 1
Likes arriving 40 / s
Time per update 100 ms
Capacity (theoretical)10 / s
Waiting in line0
Avg time in line0 ms
Likes counted0
This is a real limit

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.

03
The fix

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.

LIKES PICK A SHARD post_like_shards · post 42 TOTAL random 0–99 → 37 SUM OF 100 ROWS 1,000,000 ~167 writes/s per row (average) instead of 16,700
Fig 4Each like lands on a random shard. No single row gets hammered.
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;

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.

04
The new problem

So what's the total?

The real count is now the sum of every shard:

total.sql
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:

read.py
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
TIME → real total what users see (cached) 998,402 +6,600 cache refresh in 3.0 s
Fig 5This is why a viral like count freezes for a moment, then jumps by thousands.

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.

One catch: the cache stampede

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.

05
The full picture

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.

Likers16.7k taps/s Load balancer Like servicemany copies ① likes(user_id, post_id)UNIQUE · blocks double likes ② same transaction: +1 on a random shard post_like_shards · 100 rows Viewersmillions Count servicecache first Cachelikes:42 · TTL 3s On miss: SUM(count)one recompute per TTL read 100 rows
Fig 6Writes spread over 100 rows. Most reads never touch the database.
Why the purple table matters

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.

06
Your turn

The puzzle from the video

Think before you click
One of the counters crashes. What happens to the total?

Hint: it depends on what "crash" means, and where the counter lives.

Then break a shard yourself.
Total shown to users1,000,000
Interview one-liner: shards make writes parallel, but each shard still needs durability. If one is down, writes go to other shards and reads fall back to the last good total.
07
Before your interview

The checklist

When you get "design a like counter", walk through these in order. Tick them off as you practise.

  1. Requirements. Peak likes per second, reads vs writes, and does the count need to be exact in real time?
  2. Naive design, then the lost update race.
  3. Atomic increment, then the hot row / lock contention problem, with numbers.
  4. Sharded counter: schema, write path, choosing N, sharding only hot posts.
  5. Read path: sum + cache with a TTL, stampede protection, eventual consistency.
  6. Dedupe with a likes(user_id, post_id) table, in the same transaction.
  7. Failure modes: shard down, cache down, retries, double likes, unlikes.
  8. Alternatives: Redis + flush, queue + batching, and when you'd pick each.
0 / 8 ready

Watch it in 90 seconds

The whole story, animated, on the DevSecRoot YouTube channel.

Explore system design practiceWatch the video