← Back to SQL, page 18

sql-0359 · Hard senior

A 'likes' counter on a viral post causes lock waits because thousands of requests update the same row. How would you redesign it?

Every increment locks the same row, so updates serialise. Spread writes across several counter rows (sharded counters) and sum them on read, or append like events and aggregate periodically, or buffer increments in memory and flush in batches. A likes table with a unique (post_id, user_id) key also prevents double likes.

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 do SUM(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 + :batch periodically, 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