[Ruby on Rails (RoR)] Using ActiveRecord::CounterCache::ClassMethods to Prevent Race Conditions

Using ActiveRecord::CounterCache::ClassMethods to Prevent Race Conditions

Race conditions are arguably the most insidious kind of bug; they’re intermittent, subtle, and most likely to occur in production. ActiveRecord’s update_counter and other methods provides us with a convenient way to avoid race conditions when incrementing or decrementing values in the database.

Instance Public methods

decrement_counter(counter_name, id, touch: nil)

Decrement a numeric field by one, via a direct SQL update.

This works the same as increment_counter but reduces the column value by 1 instead of increasing it.

Parameters

  • counter_name - The name of the field that should be decremented.

  • id - The id of the object that should be decremented or an array of ids.

  • :touch - Touch timestamp columns when updating. Pass true to touch updated_at and/or updated_on. Pass a symbol to touch that column or an array of symbols to touch just those ones.

Examples

1
2
3
4
5
6
# Decrement the posts_count column for the record with an id of 5
DiscussionBoard.decrement_counter(:posts_count, 5)

# Decrement the posts_count column for the record with an id of 5
# and update the updated_at value.
DiscussionBoard.decrement_counter(:posts_count, 5, touch: true)

increment_counter(counter_name, id, touch: nil)

Increment a numeric field by one, via a direct SQL update.

This method is used primarily for maintaining counter_cache columns that are used to store aggregate values. For example, a DiscussionBoard may cache posts_count and comments_count to avoid running an SQL query to calculate the number of posts and comments there are, each time it is displayed.

Parameters

  • counter_name - The name of the field that should be incremented.

  • id - The id of the object that should be incremented or an array of ids.

  • :touch - Touch timestamp columns when updating. Pass true to touch updated_at and/or updated_on. Pass a symbol to touch that column or an array of symbols to touch just those ones.

Examples

1
2
3
4
5
6
# Increment the posts_count column for the record with an id of 5
DiscussionBoard.increment_counter(:posts_count, 5)

# Increment the posts_count column for the record with an id of 5
# and update the updated_at value.
DiscussionBoard.increment_counter(:posts_count, 5, touch: true)

reset_counters(id, *counters, touch: nil)

Resets one or more counter caches to their correct value using an SQL count query. This is useful when adding new counter caches, or if the counter has been corrupted or modified directly by SQL.

Parameters

  • id - The id of the object you wish to reset a counter on.

  • counters - One or more association counters to reset. Association name or counter name can be given.

  • :touch - Touch timestamp columns when updating. Pass true to touch updated_at and/or updated_on. Pass a symbol to touch that column or an array of symbols to touch just those ones.

Examples

1
2
3
4
5
6
# For the Post with id #1, reset the comments_count
Post.reset_counters(1, :comments)

# Like above, but also touch the +updated_at+ and/or +updated_on+
# attributes.
Post.reset_counters(1, :comments, touch: true)

update_counters(id, counters)

A generic “counter updater” implementation, intended primarily to be used by increment_counter and decrement_counter, but which may also be useful on its own. It simply does a direct SQL update for the record with the given ID, altering the given hash of counters by the amount given by the corresponding value:

Parameters

  • id - The id of the object you wish to update a counter on or an array of ids.

  • counters - A Hash containing the names of the fields to update as keys and the amount to update the field by as values.

  • :touch option - Touch timestamp columns when updating. If attribute names are passed, they are updated along with updated_at/on attributes.

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# For the Post with id of 5, decrement the comment_count by 1, and
# increment the action_count by 1
Post.update_counters 5, comment_count: -1, action_count: 1
# Executes the following SQL:
# UPDATE posts
# SET comment_count = COALESCE(comment_count, 0) - 1,
# action_count = COALESCE(action_count, 0) + 1
# WHERE id = 5

# For the Posts with id of 10 and 15, increment the comment_count by 1
Post.update_counters [10, 15], comment_count: 1
# Executes the following SQL:
# UPDATE posts
# SET comment_count = COALESCE(comment_count, 0) + 1
# WHERE id IN (10, 15)

# For the Posts with id of 10 and 15, increment the comment_count by 1
# and update the updated_at value for each counter.
Post.update_counters [10, 15], comment_count: 1, touch: true
# Executes the following SQL:
# UPDATE posts
# SET comment_count = COALESCE(comment_count, 0) + 1,
# `updated_at` = '2016-10-13T09:59:23-05:00'
# WHERE id IN (10, 15)

References

[1] Using ActiveRecord’s #update_counters to Prevent Race Conditions - Honeybadger Developer Blog - https://www.honeybadger.io/blog/activerecord-update-counters-race-conditions/

[2] ActiveRecord::CounterCache::ClassMethods - https://api.rubyonrails.org/v6.1.4/classes/ActiveRecord/CounterCache/ClassMethods.html

[3] Pulling the trigger: How to update counter caches in your Rails app without Active Record callbacks — Martian Chronicles, Evil Martians’ team blog - https://evilmartians.com/chronicles/pulling-the-trigger-how-to-update-counter-caches-in-you-rails-app-without-active-record-callbacks