Back to Course

Practice · Scaling · Card 6

What's wrong with this counter increment under load?

Locally the test passes. In production the counter drifts off the real number over time. The code reads correct. The model is what fails.

The code

Tracking page views. Each visit calls this.

def increment_views(post_id)
  post = Post.find(post_id)
  post.update!(views_count: post.views_count + 1)
end

The question

Two requests for the same post arrive at the same millisecond. The final counter ends up at 1, not 2. Why?

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