Skip to content

Commit

Permalink
Add optimistic lock to avoid race conditions when handling votes (mas…
Browse files Browse the repository at this point in the history
…todon#10196)

* Add optimistic lock to avoid race conditions when handling votes

* Force-reload polls when getting `ActiveRecord::StaleObjectError`
  • Loading branch information
ClearlyClaire authored and Gargron committed Mar 6, 2019
1 parent ed04c4c commit cab2e1d
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 1 deletion.
1 change: 1 addition & 0 deletions app/models/poll.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
# last_fetched_at :datetime
# created_at :datetime not null
# updated_at :datetime not null
# lock_version :integer default(0), not null
#

class Poll < ApplicationRecord
Expand Down
3 changes: 3 additions & 0 deletions app/models/poll_vote.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,8 @@ def object_type
def increment_counter_cache
poll.cached_tallies[choice] = (poll.cached_tallies[choice] || 0) + 1
poll.save
rescue ActiveRecord::StaleObjectError
poll.reload
retry
end
end
6 changes: 6 additions & 0 deletions db/migrate/20190306145741_add_lock_version_to_polls.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
class AddLockVersionToPolls < ActiveRecord::Migration[5.2]
def change
add_column :polls, :lock_version, :integer, null: false, default: 0
end
end

3 changes: 2 additions & 1 deletion db/schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.

ActiveRecord::Schema.define(version: 2019_03_04_152020) do
ActiveRecord::Schema.define(version: 2019_03_06_145741) do

# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
Expand Down Expand Up @@ -464,6 +464,7 @@
t.datetime "last_fetched_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "lock_version", default: 0, null: false
t.index ["account_id"], name: "index_polls_on_account_id"
t.index ["status_id"], name: "index_polls_on_status_id"
end
Expand Down

0 comments on commit cab2e1d

Please sign in to comment.