Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add optimistic lock to avoid race conditions when handling votes #10196

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions app/models/poll.rb
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
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
Gargron marked this conversation as resolved.
Show resolved Hide resolved
end
end
6 changes: 6 additions & 0 deletions db/migrate/20190306145741_add_lock_version_to_polls.rb
@@ -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
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