Databases · Senior · Question 74 of 75
How do you keep a denormalized value like posts.comments_count correct under concurrency?
- ✓Correct answer: Update it atomically in the same transaction as the comment insert (
SET comments_count = comments_count + 1), or recompute it periodically from the source - 2Update it once a year
- 3Read the current value in the app, add 1 and write it back
Explanation
Read-modify-write in the app loses updates. For very hot counters, consider sharded counters or async aggregation with occasional reconciliation.