Video in progress
How do you count likes and views on posts when tens of thousands of writes per second come in?
UPDATE posts SET likes = likes + 1 for every like chokes a single row on its lock. You need to accumulate the counter in Redis with INCR, or in a sharded counter split into several pieces, and write to the DB in batches; the like itself is stored in a separate table with a unique key.
📖 Answer
A popular post gets thousands of likes at once. Every transaction tries to update the same row, they queue up — row lock contention, and the DB is full of waiting, not CPU work.
You need to separate two things:
1. Who liked it — this is the source of truth, and there must be no duplicates:
CREATE TABLE post_likes (
post_id BIGINT, user_id BIGINT, created_at TIMESTAMPTZ DEFAULT now(),
PRIMARY KEY (post_id, user_id)
);
INSERT INTO post_likes VALUES (:post, :user) ON CONFLICT DO NOTHING;
These inserts go to different rows and don't block each other.
2. How many likes — a number for display. Running COUNT(*) every time is expensive, so keep a separate counter:
INCR post:42:likesin Redis — atomic and very fast. Increment it only when the insert succeeded.- A background job writes the Redis values into
posts.like_countin the DB every few seconds.
Without Redis, use a sharded counter inside the DB: post_counters(post_id, shard, cnt), where each write goes to a random shard (0..15) and a read does SUM(cnt). Contention drops 16 times.
Views are even more numerous and accuracy doesn't matter — you can accumulate them in memory and send them with a single INCRBY every 5–10 seconds. If a pod dies, a few seconds of views are lost — that's usually acceptable.
Sign up to mark studied questions and save your progress.