Back to Course

Practice · Scaling · Card 5

Why is the counter cache slowing down every comment?

A counter cache. Reasonable schema. Then a celebrity user posts. Suddenly every comment INSERT takes 800ms. Same table. Same indexes. What changed?

The setup

A counter cache on a Twitter-style app. The celebrity user has 100,000 followers and just posted; thousands of comments arrive within seconds.

class Comment < ApplicationRecord
  belongs_to :post, counter_cache: true
end

# Every Comment.create! generates:
#
#   BEGIN;
#   INSERT INTO comments (post_id, body, ...) VALUES (...);
#   UPDATE posts SET comments_count = comments_count + 1
#     WHERE id = 42;
#   COMMIT;

# The post is post #42. Thousands of users comment in the same second.

The question

Why does every comment INSERT slow down, given the comments table itself has plenty of capacity?

Take a moment. Pick the best answer. Wrong picks reveal why they're wrong, which is half the point.