Video in progress
A popular post's likes_count row receives thousands of UPDATEs per second and lock waits have increased. How do you solve it?
A single hot row is a bottleneck that serializes writes. The solutions: split the counter across several "slot" rows and sum them on read, accumulate changes in memory or Redis and flush to the database periodically, or use eventually consistent aggregation.
📖 Answer
The mechanics of the problem: UPDATE post SET likes = likes + 1 WHERE id = 7 takes a row lock. Each following transaction waits for the previous one's commit. If a commit with fsync is about 1-2 ms, a few hundred updates per second on a single row is the ceiling. On top of that, every update is a new version, so bloat builds up around that one row.
- A sharded counter:
CREATE TABLE post_like_counter (
post_id bigint, slot smallint, cnt bigint NOT NULL DEFAULT 0,
PRIMARY KEY (post_id, slot)
);
-- write: a random slot (0..15)
INSERT INTO post_like_counter VALUES (:postId, :slot, 1)
ON CONFLICT (post_id, slot) DO UPDATE SET cnt = post_like_counter.cnt + 1;
-- read
SELECT sum(cnt) FROM post_like_counter WHERE post_id = :postId;
Contention drops 16 times, and reads get a bit more expensive.
-
Buffering: likes are accumulated with Redis
INCRor in application memory, and every 5 seconds a singleUPDATE ... + :deltais run. Very fast, but on a crash a few seconds of delta can be lost, which is usually acceptable for likes and not for money. -
Don't count: the
post_like(user_id, post_id)table stays as the source of truth (a unique constraint also solves "liked twice"), and the number is computed by an asynchronous job.
Which one to choose depends on the business: does the number need to be exact in real time? Often "roughly accurate, 5 seconds behind" is enough, and option 2 is the simplest. For money or warehouse stock, option 1 or sequential processing through a queue, to keep it exact.
Sign up to mark studied questions and save your progress.