Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

ActiveRecord::AtomicCounters

Increments and decrements counters of ActiveRecord records in the database atomically, and returns their new values.

Why?

Rails' increment! updates the counter in the database atomically, but assigns the record its value in memory plus the increment. If the counter was changed elsewhere since the record was loaded, the record's value is stale, so it can't be relied on to decide what to do next. Reloading the record afterwards doesn't help either, since the counter may have changed again between the UPDATE and the reload.

atomic_increment returns the value the UPDATE itself stored (with RETURNING), in the same statement, so each increment sees exactly the value it produced, even when many happen at once.

Enforcing a limit

Two customers buy a product with one available (available_count: 1, purchased_count: 0) at the same time, each incrementing purchased_count. With increment!, both records see purchased_count as 1 (their loaded value of 0, plus 1), so both purchases go through and the product is oversold (with 2 in the database). With atomic_increment, the second increment sees 2, raises, and its transaction rolls the increment back:

product.transaction do
  product.atomic_increment(:purchased_count, 1)

  product.purchased_count <= product.available_count or
    raise Product::NoLongerAvailable, product

  product.purchases.create!(customer:)
end

Numbering a sequence

Each value is returned to exactly one increment, so it can be used as a unique number without a retry on a unique index violation. It's gapless too (unlike a database sequence), since a rolled back increment is undone, and its number reused:

account.transaction do
  number = account.atomic_increment(:invoices_count)
  account.invoices.create!(number:)
end

Acting once on a milestone

Exactly one increment produces each value, so exactly one request reaches a milestone:

if post.atomic_increment(:likes_count) == 1_000
  PostMailer.with(post:).thousand_likes.deliver_later
end

Quotas, without loading records

The class methods return the new values by id, without loading the records first:

requests = ApiKey.atomic_increment_counter(:requests_count, api_key_id)
head :too_many_requests if requests > ApiKey::REQUEST_LIMIT

Installation

Add this line to your application's Gemfile:

gem 'active_record-atomic_counters'

And then execute:

$ bundle

Then include ActiveRecord::AtomicCounters in your models (typically in ApplicationRecord, so all models get it):

class ApplicationRecord < ActiveRecord::Base
  primary_abstract_class

  include ActiveRecord::AtomicCounters
end

Usage

atomic_increment increments a counter in the database, and returns its new value (which is also assigned to the record, without leaving it changed):

post = Post.find(...) # views_count: 10

post.atomic_increment(:views_count)    # => 11
post.atomic_increment(:views_count, 5) # => 16
UPDATE "posts" SET "views_count" = COALESCE("posts"."views_count", 0) + 5
WHERE "posts"."id" = 1 RETURNING "views_count"

atomic_decrement decrements a counter in the same way:

product.atomic_decrement(:stock, 2) # => 8

The changes to the counter (and touched timestamps) are recorded as the record's saved changes, as a save would:

post.atomic_increment(:views_count) # => 11
post.saved_change_to_views_count    # => [10, 11]
post.previous_changes               # => { "views_count" => [10, 11] }

Callbacks and validations are skipped, and unsaved changes to the record's other attributes are kept (as unsaved changes, rather than recorded as saved). Unsaved changes to the counter itself are discarded, in favour of its value in the database. ActiveRecord::RecordNotFound is raised if the record no longer exists.

New records are incremented in memory, without saving them (as increment would).

Touch

As with update_counters, timestamps aren't touched unless given touch: true touches the record's timestamps, and a symbol or array touches the given attributes along with them:

post.atomic_increment(:views_count, touch: true)
post.atomic_increment(:views_count, touch: :viewed_at)
post.atomic_increment(:views_count, touch: %i[viewed_at indexed_at])

Class methods

atomic_increment_counter, atomic_decrement_counter and atomic_update_counters update counters by id (as increment_counter, decrement_counter and update_counters would), and return their new values:

Post.atomic_increment_counter(:views_count, 1)        # => 11
Post.atomic_decrement_counter(:views_count, 1, by: 2) # => 9
Post.atomic_update_counters(1, views_count: 1, shares_count: -1)
# => { "views_count" => 10, "shares_count" => 3 }

Given an array of ids (an array of arrays, with a composite primary key), they return the new values by id:

Post.atomic_increment_counter(:views_count, [1, 2])
# => { 1 => 11, 2 => 4 }

Post.atomic_update_counters([1, 2], views_count: 1)
# => { 1 => { "views_count" => 12 }, 2 => { "views_count" => 5 } }

They return nil for ids which don't exist (rather than raising), skip default scopes, and take touch in the same way:

Post.atomic_increment_counter(:views_count, 1, touch: true)
Post.atomic_update_counters(1, views_count: 1, touch: :viewed_at)

Counter caches

Rails updates counter caches (belongs_to ..., counter_cache: true) atomically in the database, but assigns the records it updates their counters' values in memory plus the increment, which are stale if the counters were changed elsewhere since the records were loaded. Counter caches can assign the counters' new values from the database instead:

# config/application.rb
config.active_record.atomic_counter_cache = true
post = Post.find(...)                 # comments_count: 0
Comment.create!(post: Post.find(...)) # another process adds a comment (comments_count: 1)
Comment.create!(post:)

post.comments_count # => 2 (rather than 1)

This applies wherever Rails updates a counter cache through a loaded record (eg. creating or destroying a record with its belongs_to association loaded, or deleting records through a has_many association), for models which include ActiveRecord::AtomicCounters. As with Rails, the record's saved changes are left as they were, and records which no longer exist are skipped (rather than raising).

Databases

The new values are returned from the UPDATE itself (with RETURNING), so PostgreSQL or SQLite is required.

Development

The specs run against a dummy Rails application in spec/dummy, using SQLite by default:

$ bin/rspec
$ bin/rubocop

PostgreSQL is selected with the DATABASE_ADAPTER and DATABASE_URL environment variables (see .github/workflows/ci.yml).

License

The gem is available as open source under the terms of the MIT License.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages