Full answer
Options:
- Sharded counter:
post_like_counts(post_id, shard, n, PRIMARY KEY (post_id, shard)). Each increment picks a random shard 0 to 15; reads doSUM(n). Contention drops roughly by the number of shards. - Event table plus rollup: insert into
likes(post_id, user_id, created_at)(inserts do not contend on one row) and refresh a cached count every few seconds. - Buffered increments: collect counts in an in-memory store and apply
UPDATE ... SET n = n + :batchperiodically, accepting a small delay and possible loss on crash.
A unique key on likes(post_id, user_id) makes "like" idempotent and allows unliking. Displaying '12.4K likes' rarely needs exact real-time accuracy, which gives room for these trade-offs.
Key points
- Single-row counters serialise writers
- Sharded counters spread contention
- Insert events and aggregate later
- Batch increments
- Exact real-time counts are rarely needed
Common mistakes
- Adding more app servers, which increases contention
- Counting likes with COUNT(*) on every page view at scale
Follow-ups
- How would you show whether the current user liked the post?
- How many shards are enough?
Tips
- Quantify why one row serialises