├── log └── .keep ├── tmp └── .keep ├── vendor └── .keep ├── .ruby-version ├── lib ├── assets │ └── .keep └── tasks │ ├── .keep │ └── benchmark.rake ├── public ├── favicon.ico ├── apple-touch-icon.png ├── apple-touch-icon-precomposed.png ├── robots.txt ├── 500.html ├── 422.html └── 404.html ├── app ├── assets │ ├── images │ │ └── .keep │ ├── config │ │ └── manifest.js │ ├── javascripts │ │ └── application.js │ └── stylesheets │ │ └── application.css ├── models │ ├── concerns │ │ └── .keep │ ├── application_record.rb │ ├── opt_lock_account.rb │ └── account.rb ├── controllers │ ├── concerns │ │ └── .keep │ └── application_controller.rb ├── views │ └── layouts │ │ ├── mailer.text.erb │ │ ├── mailer.html.erb │ │ └── application.html.erb ├── helpers │ └── application_helper.rb ├── jobs │ └── application_job.rb ├── mailers │ └── application_mailer.rb └── services │ └── transfer_balance │ ├── v0.rb │ ├── v2.rb │ ├── v1.rb │ ├── opt_lock_v0.rb │ ├── v4.rb │ ├── v3.rb │ ├── v5.rb │ ├── v6.rb │ ├── v7.rb │ ├── opt_lock_v1.rb │ ├── v9.rb │ └── v8.rb ├── .rspec ├── features.png ├── benchmarks1.png ├── benchmarks2.png ├── package.json ├── bin ├── bundle ├── rake ├── rails ├── yarn ├── spring ├── update └── setup ├── config ├── spring.rb ├── routes.rb ├── environment.rb ├── initializers │ ├── mime_types.rb │ ├── filter_parameter_logging.rb │ ├── application_controller_renderer.rb │ ├── cookies_serializer.rb │ ├── backtrace_silencers.rb │ ├── wrap_parameters.rb │ ├── assets.rb │ ├── inflections.rb │ └── content_security_policy.rb ├── boot.rb ├── credentials.yml.enc ├── locales │ └── en.yml ├── application.rb ├── puma.rb ├── environments │ ├── test.rb │ ├── development.rb │ └── production.rb └── database.yml ├── config.ru ├── spec ├── services │ └── transfer_balance │ │ ├── v5_spec.rb │ │ ├── v6_spec.rb │ │ ├── v7_spec.rb │ │ ├── v8_spec.rb │ │ ├── v9_spec.rb │ │ ├── opt_lock_v1_spec.rb │ │ ├── v0_spec.rb │ │ ├── v1_spec.rb │ │ ├── v2_spec.rb │ │ ├── v3_spec.rb │ │ ├── opt_lock_v0_spec.rb │ │ └── v4_spec.rb ├── support │ ├── database_cleaner.rb │ └── shared_contexts │ │ ├── invalid_transfer.rb │ │ ├── valid_transfer.rb │ │ ├── invalid_transfer_with_exception.rb │ │ ├── fully_operational.rb │ │ ├── handles_deadlocks.rb │ │ ├── conflicting_parallel_operations.rb │ │ └── conflicting_parallel_operations_order_matters.rb ├── rails_helper.rb └── spec_helper.rb ├── Rakefile ├── db ├── migrate │ ├── 20180808191051_create_accounts.rb │ └── 20180923070102_create_opt_lock_accounts.rb ├── seeds.rb └── schema.rb ├── .gitignore ├── .rubocop.yml ├── LICENSE ├── Gemfile ├── README.md └── Gemfile.lock /log/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tmp/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /vendor/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.ruby-version: -------------------------------------------------------------------------------- 1 | 2.6.3 -------------------------------------------------------------------------------- /lib/assets/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /lib/tasks/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /app/assets/images/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /app/models/concerns/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /public/apple-touch-icon.png: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /app/controllers/concerns/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /public/apple-touch-icon-precomposed.png: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.rspec: -------------------------------------------------------------------------------- 1 | --require rails_helper 2 | --format doc 3 | -------------------------------------------------------------------------------- /app/views/layouts/mailer.text.erb: -------------------------------------------------------------------------------- 1 | <%= yield %> 2 | -------------------------------------------------------------------------------- /app/helpers/application_helper.rb: -------------------------------------------------------------------------------- 1 | module ApplicationHelper 2 | end 3 | -------------------------------------------------------------------------------- /app/jobs/application_job.rb: -------------------------------------------------------------------------------- 1 | class ApplicationJob < ActiveJob::Base 2 | end 3 | -------------------------------------------------------------------------------- /features.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rabotyaga/alicenbob/HEAD/features.png -------------------------------------------------------------------------------- /benchmarks1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rabotyaga/alicenbob/HEAD/benchmarks1.png -------------------------------------------------------------------------------- /benchmarks2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rabotyaga/alicenbob/HEAD/benchmarks2.png -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "alicenbob", 3 | "private": true, 4 | "dependencies": {} 5 | } 6 | -------------------------------------------------------------------------------- /app/controllers/application_controller.rb: -------------------------------------------------------------------------------- 1 | class ApplicationController < ActionController::Base 2 | end 3 | -------------------------------------------------------------------------------- /app/models/application_record.rb: -------------------------------------------------------------------------------- 1 | class ApplicationRecord < ActiveRecord::Base 2 | self.abstract_class = true 3 | end 4 | -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file 2 | -------------------------------------------------------------------------------- /app/assets/config/manifest.js: -------------------------------------------------------------------------------- 1 | //= link_tree ../images 2 | //= link_directory ../javascripts .js 3 | //= link_directory ../stylesheets .css 4 | -------------------------------------------------------------------------------- /bin/bundle: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) 3 | load Gem.bin_path('bundler', 'bundle') 4 | -------------------------------------------------------------------------------- /app/mailers/application_mailer.rb: -------------------------------------------------------------------------------- 1 | class ApplicationMailer < ActionMailer::Base 2 | default from: 'from@example.com' 3 | layout 'mailer' 4 | end 5 | -------------------------------------------------------------------------------- /config/spring.rb: -------------------------------------------------------------------------------- 1 | %w[ 2 | .ruby-version 3 | .rbenv-vars 4 | tmp/restart.txt 5 | tmp/caching-dev.txt 6 | ].each { |path| Spring.watch(path) } 7 | -------------------------------------------------------------------------------- /config.ru: -------------------------------------------------------------------------------- 1 | # This file is used by Rack-based servers to start the application. 2 | 3 | require_relative 'config/environment' 4 | 5 | run Rails.application 6 | -------------------------------------------------------------------------------- /config/routes.rb: -------------------------------------------------------------------------------- 1 | Rails.application.routes.draw do 2 | # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html 3 | end 4 | -------------------------------------------------------------------------------- /spec/services/transfer_balance/v5_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | describe TransferBalance::V5 do 4 | it_behaves_like 'fully operational' 5 | end 6 | -------------------------------------------------------------------------------- /spec/services/transfer_balance/v6_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | describe TransferBalance::V6 do 4 | it_behaves_like 'fully operational' 5 | end 6 | -------------------------------------------------------------------------------- /spec/services/transfer_balance/v7_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | describe TransferBalance::V7 do 4 | it_behaves_like 'fully operational' 5 | end 6 | -------------------------------------------------------------------------------- /spec/services/transfer_balance/v8_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | describe TransferBalance::V8 do 4 | it_behaves_like 'fully operational' 5 | end 6 | -------------------------------------------------------------------------------- /spec/services/transfer_balance/v9_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | describe TransferBalance::V9 do 4 | it_behaves_like 'fully operational' 5 | end 6 | -------------------------------------------------------------------------------- /config/environment.rb: -------------------------------------------------------------------------------- 1 | # Load the Rails application. 2 | require_relative 'application' 3 | 4 | # Initialize the Rails application. 5 | Rails.application.initialize! 6 | -------------------------------------------------------------------------------- /spec/services/transfer_balance/opt_lock_v1_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | describe TransferBalance::OptLockV1 do 4 | it_behaves_like 'fully operational', OptLockAccount 5 | end 6 | -------------------------------------------------------------------------------- /config/initializers/mime_types.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new mime types for use in respond_to blocks: 4 | # Mime::Type.register "text/richtext", :rtf 5 | -------------------------------------------------------------------------------- /config/boot.rb: -------------------------------------------------------------------------------- 1 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) 2 | 3 | require 'bundler/setup' # Set up gems listed in the Gemfile. 4 | require 'bootsnap/setup' # Speed up boot time by caching expensive operations. 5 | -------------------------------------------------------------------------------- /config/initializers/filter_parameter_logging.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Configure sensitive parameters which will be filtered from the log file. 4 | Rails.application.config.filter_parameters += [:password] 5 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | # Add your own tasks in files placed in lib/tasks ending in .rake, 2 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. 3 | 4 | require_relative 'config/application' 5 | 6 | Rails.application.load_tasks 7 | -------------------------------------------------------------------------------- /bin/rake: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | begin 3 | load File.expand_path('../spring', __FILE__) 4 | rescue LoadError => e 5 | raise unless e.message.include?('spring') 6 | end 7 | require_relative '../config/boot' 8 | require 'rake' 9 | Rake.application.run 10 | -------------------------------------------------------------------------------- /config/initializers/application_controller_renderer.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # ActiveSupport::Reloader.to_prepare do 4 | # ApplicationController.renderer.defaults.merge!( 5 | # http_host: 'example.org', 6 | # https: false 7 | # ) 8 | # end 9 | -------------------------------------------------------------------------------- /config/initializers/cookies_serializer.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Specify a serializer for the signed and encrypted cookie jars. 4 | # Valid options are :json, :marshal, and :hybrid. 5 | Rails.application.config.action_dispatch.cookies_serializer = :json 6 | -------------------------------------------------------------------------------- /bin/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | begin 3 | load File.expand_path('../spring', __FILE__) 4 | rescue LoadError => e 5 | raise unless e.message.include?('spring') 6 | end 7 | APP_PATH = File.expand_path('../config/application', __dir__) 8 | require_relative '../config/boot' 9 | require 'rails/commands' 10 | -------------------------------------------------------------------------------- /app/views/layouts/mailer.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 8 | 9 | 10 | 11 | <%= yield %> 12 | 13 | 14 | -------------------------------------------------------------------------------- /spec/services/transfer_balance/v0_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | describe TransferBalance::V0 do 4 | context 'with valid transfer' do 5 | include_context 'valid transfer' 6 | end 7 | 8 | context 'with invalid transfer' do 9 | include_context 'invalid transfer' 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /spec/services/transfer_balance/v1_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | describe TransferBalance::V1 do 4 | context 'with valid transfer' do 5 | include_context 'valid transfer' 6 | end 7 | 8 | context 'with invalid transfer' do 9 | include_context 'invalid transfer' 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /db/migrate/20180808191051_create_accounts.rb: -------------------------------------------------------------------------------- 1 | class CreateAccounts < ActiveRecord::Migration[5.2] 2 | def change 3 | create_table :accounts do |t| 4 | t.string :name, null: false 5 | t.integer :balance, null: false 6 | 7 | t.timestamps 8 | end 9 | 10 | add_index :accounts, :name, unique: true 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /bin/yarn: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | APP_ROOT = File.expand_path('..', __dir__) 3 | Dir.chdir(APP_ROOT) do 4 | begin 5 | exec "yarnpkg", *ARGV 6 | rescue Errno::ENOENT 7 | $stderr.puts "Yarn executable was not detected in the system." 8 | $stderr.puts "Download Yarn at https://yarnpkg.com/en/docs/install" 9 | exit 1 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /spec/support/database_cleaner.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | RSpec.configure do |config| 4 | config.before(:suite) do 5 | DatabaseCleaner.strategy = :truncation 6 | DatabaseCleaner.clean_with(:truncation) 7 | end 8 | 9 | config.around do |example| 10 | DatabaseCleaner.cleaning do 11 | example.run 12 | end 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /db/seeds.rb: -------------------------------------------------------------------------------- 1 | # This file should contain all the record creation needed to seed the database with its default values. 2 | # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). 3 | # 4 | # Examples: 5 | # 6 | # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) 7 | # Character.create(name: 'Luke', movie: movies.first) 8 | -------------------------------------------------------------------------------- /db/migrate/20180923070102_create_opt_lock_accounts.rb: -------------------------------------------------------------------------------- 1 | class CreateOptLockAccounts < ActiveRecord::Migration[5.2] 2 | def change 3 | create_table :opt_lock_accounts do |t| 4 | t.string :name, null: false 5 | t.integer :balance, null: false 6 | t.integer :lock_version, default: 0 7 | 8 | t.timestamps 9 | end 10 | 11 | add_index :opt_lock_accounts, :name, unique: true 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /app/views/layouts/application.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Alicenbob 5 | <%= csrf_meta_tags %> 6 | <%= csp_meta_tag %> 7 | 8 | <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %> 9 | <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %> 10 | 11 | 12 | 13 | <%= yield %> 14 | 15 | 16 | -------------------------------------------------------------------------------- /spec/services/transfer_balance/v2_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | describe TransferBalance::V2 do 4 | context 'with valid transfer' do 5 | include_context 'valid transfer' 6 | end 7 | 8 | context 'with invalid transfer' do 9 | include_context 'invalid transfer with exception' 10 | end 11 | 12 | context 'with conflicting parallel operations' do 13 | include_context 'conflicting parallel operations' 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /spec/services/transfer_balance/v3_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | describe TransferBalance::V3 do 4 | context 'with valid transfer' do 5 | include_context 'valid transfer' 6 | end 7 | 8 | context 'with invalid transfer' do 9 | include_context 'invalid transfer with exception' 10 | end 11 | 12 | context 'with conflicting parallel operations' do 13 | include_context 'conflicting parallel operations' 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /config/initializers/backtrace_silencers.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. 4 | # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } 5 | 6 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. 7 | # Rails.backtrace_cleaner.remove_silencers! 8 | -------------------------------------------------------------------------------- /config/credentials.yml.enc: -------------------------------------------------------------------------------- 1 | TRi+p2TsK8Xq2cGjSi1CadrTQk/lJHD3KF4Wwn94/TBBxkn0cz+D809w/MBg1X+/sVGbA2GBp2qTMbYSSLKOleM1pr15J4YJeuqcnePkLOx5xYahSrVmtVdLIHgzbwHwbWkic4Wlgey+sDa7m/iQD9tIsC9GDHRgJU8eFcAbTJBmqd7OZ5xDXfRDVrUT6igWFCpCaamr7g7AhIxfdVw9xMSck7QONDLcRoSeJD3+9jxuwWmuRE23+8AZ+Kr409PGvbaNfZ8y6l6zqZEJuVs62IZwXXhQCHU6HQY3M+pJD6DmUe9aYdc9DRNi1aHxNRjsDw6ZFfFuzdaTHwHaHkXCstPJPCjcX3pWm0+7Qcr8R6lxFOdKo+fMtX7V/8mt/JVgZIXNSzmmP6q+KR89hzGw6Zl2kd7WkwR8BE0i--ZEX/zis4QKWTKzvu--kqZYRzvLXgAAmkadkBoD9A== -------------------------------------------------------------------------------- /app/models/opt_lock_account.rb: -------------------------------------------------------------------------------- 1 | class OptLockAccount < ApplicationRecord 2 | validates :balance, numericality: { greater_than_or_equal_to: 0 } 3 | 4 | def withdraw(amount) 5 | update!(balance: balance - amount) 6 | end 7 | 8 | def deposit(amount) 9 | update!(balance: balance + amount) 10 | end 11 | 12 | def self.transfer(from, to, amount) 13 | transaction do 14 | from.withdraw(amount) 15 | to.deposit(amount) 16 | end 17 | end 18 | end 19 | -------------------------------------------------------------------------------- /spec/services/transfer_balance/opt_lock_v0_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | describe TransferBalance::OptLockV0 do 4 | context 'with valid transfer' do 5 | include_context 'valid transfer', OptLockAccount 6 | end 7 | 8 | context 'with invalid transfer' do 9 | include_context 'invalid transfer with exception', OptLockAccount 10 | end 11 | 12 | context 'with conflicting parallel operations' do 13 | include_context 'conflicting parallel operations', OptLockAccount 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /app/models/account.rb: -------------------------------------------------------------------------------- 1 | class Account < ApplicationRecord 2 | validates :balance, numericality: { greater_than_or_equal_to: 0 } 3 | 4 | def withdraw(amount) 5 | with_lock { update!(balance: balance - amount) } 6 | end 7 | 8 | def deposit(amount) 9 | with_lock { update!(balance: balance + amount) } 10 | end 11 | 12 | def self.transfer(from, to, amount) 13 | transaction do 14 | from.lock! 15 | to.lock! 16 | from.withdraw(amount) 17 | to.deposit(amount) 18 | end 19 | end 20 | end 21 | -------------------------------------------------------------------------------- /app/services/transfer_balance/v0.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module TransferBalance 4 | # no transactions 5 | module V0 6 | class << self 7 | def call(from, to, amount) 8 | withdraw(from, amount) 9 | deposit(to, amount) 10 | end 11 | 12 | def withdraw(from, amount) 13 | from.update(balance: from.balance - amount) 14 | end 15 | 16 | def deposit(to, amount) 17 | to.update(balance: to.balance + amount) 18 | end 19 | end 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /spec/support/shared_contexts/invalid_transfer.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | shared_context 'invalid transfer' do |account_class = Account| 4 | let(:alice) { account_class.create(name: 'Alice', balance: 100) } 5 | let(:bob) { account_class.create(name: 'Bob', balance: 100) } 6 | 7 | before do 8 | described_class.call(bob, alice, 200) 9 | end 10 | 11 | it 'both balances stay unchanged' do 12 | aggregate_failures do 13 | expect(bob.reload.balance).to eq 100 14 | expect(alice.reload.balance).to eq 100 15 | end 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /config/initializers/wrap_parameters.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # This file contains settings for ActionController::ParamsWrapper which 4 | # is enabled by default. 5 | 6 | # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. 7 | ActiveSupport.on_load(:action_controller) do 8 | wrap_parameters format: [:json] 9 | end 10 | 11 | # To enable root element in JSON for ActiveRecord objects. 12 | # ActiveSupport.on_load(:active_record) do 13 | # self.include_root_in_json = true 14 | # end 15 | -------------------------------------------------------------------------------- /bin/spring: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | # This file loads spring without using Bundler, in order to be fast. 4 | # It gets overwritten when you run the `spring binstub` command. 5 | 6 | unless defined?(Spring) 7 | require 'rubygems' 8 | require 'bundler' 9 | 10 | lockfile = Bundler::LockfileParser.new(Bundler.default_lockfile.read) 11 | spring = lockfile.specs.detect { |spec| spec.name == "spring" } 12 | if spring 13 | Gem.use_paths Gem.dir, Bundler.bundle_path.to_s, *Gem.path 14 | gem 'spring', spring.version 15 | require 'spring/binstub' 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /spec/support/shared_contexts/valid_transfer.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | shared_context 'valid transfer' do |account_class = Account| 4 | let(:alice) { account_class.create(name: 'Alice', balance: 100) } 5 | let(:bob) { account_class.create(name: 'Bob', balance: 100) } 6 | 7 | before do 8 | described_class.call(bob, alice, 100) 9 | end 10 | 11 | it 'Bob`s balance = 0, Alice`s balance = 200' do 12 | aggregate_failures do 13 | expect(bob.reload.balance).to be_zero 14 | expect(alice.reload.balance).to eq 200 15 | end 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /spec/services/transfer_balance/v4_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | describe TransferBalance::V4 do 4 | context 'with valid transfer' do 5 | include_context 'valid transfer' 6 | end 7 | 8 | context 'with invalid transfer' do 9 | include_context 'invalid transfer with exception' 10 | end 11 | 12 | context 'with conflicting parallel operations' do 13 | include_context 'conflicting parallel operations' 14 | end 15 | 16 | context 'with conflicting parallel operations' do 17 | include_context 'conflicting parallel operations, order matters' 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /app/services/transfer_balance/v2.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module TransferBalance 4 | # simple transaction w/o locking, allows lost update 5 | module V2 6 | class << self 7 | def call(from, to, amount) 8 | ActiveRecord::Base.transaction do 9 | withdraw(from, amount) 10 | deposit(to, amount) 11 | end 12 | end 13 | 14 | def withdraw(from, amount) 15 | from.update!(balance: from.balance - amount) 16 | end 17 | 18 | def deposit(to, amount) 19 | to.update!(balance: to.balance + amount) 20 | end 21 | end 22 | end 23 | end 24 | -------------------------------------------------------------------------------- /app/services/transfer_balance/v1.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module TransferBalance 4 | # transaction w/o raise, does not rollback on validation error 5 | module V1 6 | class << self 7 | def call(from, to, amount) 8 | ActiveRecord::Base.transaction do 9 | withdraw(from, amount) 10 | deposit(to, amount) 11 | end 12 | end 13 | 14 | def withdraw(from, amount) 15 | from.update(balance: from.balance - amount) 16 | end 17 | 18 | def deposit(to, amount) 19 | to.update(balance: to.balance + amount) 20 | end 21 | end 22 | end 23 | end 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files for more about ignoring files. 2 | # 3 | # If you find yourself ignoring temporary files generated by your text editor 4 | # or operating system, you probably want to add a global ignore instead: 5 | # git config --global core.excludesfile '~/.gitignore_global' 6 | 7 | # Ignore bundler config. 8 | /.bundle 9 | 10 | # Ignore all logfiles and tempfiles. 11 | /log/* 12 | /tmp/* 13 | !/log/.keep 14 | !/tmp/.keep 15 | 16 | /node_modules 17 | /yarn-error.log 18 | 19 | /public/assets 20 | .byebug_history 21 | 22 | # Ignore master key for decrypting credentials and more. 23 | /config/master.key 24 | -------------------------------------------------------------------------------- /spec/support/shared_contexts/invalid_transfer_with_exception.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | shared_context 'invalid transfer with exception' do |account_class = Account| 4 | let(:alice) { account_class.create(name: 'Alice', balance: 100) } 5 | let(:bob) { account_class.create(name: 'Bob', balance: 100) } 6 | 7 | it 'raises validation error, both balances stay unchanged' do 8 | aggregate_failures do 9 | expect { described_class.call(bob, alice, 200) } 10 | .to raise_error(ActiveRecord::RecordInvalid) 11 | expect(alice.reload.balance).to eq 100 12 | expect(bob.reload.balance).to eq 100 13 | end 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /.rubocop.yml: -------------------------------------------------------------------------------- 1 | require: rubocop-rspec 2 | 3 | AllCops: 4 | Exclude: 5 | - bin/* 6 | - config/**/* 7 | - config.ru 8 | - db/schema.rb 9 | - db/migrate/* 10 | - db/seeds.rb 11 | - Gemfile 12 | - Rakefile 13 | - spec/spec_helper.rb 14 | - spec/rails_helper.rb 15 | 16 | Style/Documentation: 17 | Exclude: 18 | - app/**/* 19 | 20 | Style/FrozenStringLiteralComment: 21 | Exclude: 22 | - app/**/* 23 | 24 | RSpec/ExampleLength: 25 | Max: 25 26 | 27 | Metrics/BlockLength: 28 | Max: 50 29 | 30 | Metrics/LineLength: 31 | Max: 120 32 | 33 | RSpec/ContextWording: 34 | Exclude: 35 | - spec/support/shared_contexts/* 36 | -------------------------------------------------------------------------------- /config/initializers/assets.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Version of your assets, change this if you want to expire all your assets. 4 | Rails.application.config.assets.version = '1.0' 5 | 6 | # Add additional assets to the asset load path. 7 | # Rails.application.config.assets.paths << Emoji.images_path 8 | # Add Yarn node_modules folder to the asset load path. 9 | Rails.application.config.assets.paths << Rails.root.join('node_modules') 10 | 11 | # Precompile additional assets. 12 | # application.js, application.css, and all non-JS/CSS in the app/assets 13 | # folder are already added. 14 | # Rails.application.config.assets.precompile += %w( admin.js admin.css ) 15 | -------------------------------------------------------------------------------- /config/initializers/inflections.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new inflection rules using the following format. Inflections 4 | # are locale specific, and you may define rules for as many different 5 | # locales as you wish. All of these examples are active by default: 6 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 7 | # inflect.plural /^(ox)$/i, '\1en' 8 | # inflect.singular /^(ox)en/i, '\1' 9 | # inflect.irregular 'person', 'people' 10 | # inflect.uncountable %w( fish sheep ) 11 | # end 12 | 13 | # These inflection rules are supported but not enabled by default: 14 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 15 | # inflect.acronym 'RESTful' 16 | # end 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2018 Ivan Rabotyaga 2 | 3 | Permission to use, copy, modify, and/or distribute this software for any 4 | purpose with or without fee is hereby granted, provided that the above 5 | copyright notice and this permission notice appear in all copies. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 8 | WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 9 | MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 10 | ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 11 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 12 | ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 13 | OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -------------------------------------------------------------------------------- /app/assets/javascripts/application.js: -------------------------------------------------------------------------------- 1 | // This is a manifest file that'll be compiled into application.js, which will include all the files 2 | // listed below. 3 | // 4 | // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's 5 | // vendor/assets/javascripts directory can be referenced here using a relative path. 6 | // 7 | // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the 8 | // compiled file. JavaScript code in this file should be added after the last require_* statement. 9 | // 10 | // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details 11 | // about supported directives. 12 | // 13 | //= require rails-ujs 14 | //= require turbolinks 15 | //= require_tree . 16 | -------------------------------------------------------------------------------- /app/assets/stylesheets/application.css: -------------------------------------------------------------------------------- 1 | /* 2 | * This is a manifest file that'll be compiled into application.css, which will include all the files 3 | * listed below. 4 | * 5 | * Any CSS and SCSS file within this directory, lib/assets/stylesheets, or any plugin's 6 | * vendor/assets/stylesheets directory can be referenced here using a relative path. 7 | * 8 | * You're free to add application-wide styles to this file and they'll appear at the bottom of the 9 | * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS 10 | * files in this directory. Styles in this file should be added after the last require_* statement. 11 | * It is generally better to create a new file per style scope. 12 | * 13 | *= require_tree . 14 | *= require_self 15 | */ 16 | -------------------------------------------------------------------------------- /spec/support/shared_contexts/fully_operational.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | shared_context 'fully operational' do |account_class = Account| 4 | context 'with valid transfer' do 5 | include_context 'valid transfer', account_class 6 | end 7 | 8 | context 'with invalid transfer' do 9 | include_context 'invalid transfer with exception', account_class 10 | end 11 | 12 | context 'with conflicting parallel operations' do 13 | include_context 'conflicting parallel operations', account_class 14 | end 15 | 16 | context 'with conflicting parallel operations' do 17 | include_context 'conflicting parallel operations, order matters', account_class 18 | end 19 | 20 | context 'with non conflicting parallel operations' do 21 | include_context 'handles deadlocks', account_class 22 | end 23 | end 24 | -------------------------------------------------------------------------------- /app/services/transfer_balance/opt_lock_v0.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module TransferBalance 4 | # transaction w/ optimistic locks 5 | # no lost updates 6 | # raises ActiveRecord::StaleObjectError on conflict 7 | module OptLockV0 8 | class << self 9 | def call(from, to, amount) 10 | ActiveRecord::Base.transaction do 11 | # emulate some heavy-lifting stuff 12 | # giving a chance for standalone #withdraw / #deposit finish first 13 | sleep(0.05) 14 | 15 | withdraw(from, amount) 16 | deposit(to, amount) 17 | end 18 | end 19 | 20 | def withdraw(from, amount) 21 | from.update!(balance: from.balance - amount) 22 | end 23 | 24 | def deposit(to, amount) 25 | to.update!(balance: to.balance + amount) 26 | end 27 | end 28 | end 29 | end 30 | -------------------------------------------------------------------------------- /app/services/transfer_balance/v4.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module TransferBalance 4 | # transaction w/ locks in #withdraw / #deposit 5 | # no lost updates 6 | # does not guarantee same order 7 | module V4 8 | class << self 9 | def call(from, to, amount) 10 | ActiveRecord::Base.transaction do 11 | # emulate some heavy-lifting stuff 12 | # giving a chance for standalone #withdraw / #deposit finish first 13 | sleep(0.05) 14 | 15 | withdraw(from, amount) 16 | deposit(to, amount) 17 | end 18 | end 19 | 20 | def withdraw(from, amount) 21 | from.with_lock { from.update!(balance: from.balance - amount) } 22 | end 23 | 24 | def deposit(to, amount) 25 | to.with_lock { to.update!(balance: to.balance + amount) } 26 | end 27 | end 28 | end 29 | end 30 | -------------------------------------------------------------------------------- /app/services/transfer_balance/v3.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module TransferBalance 4 | # transaction w/ single lock in #call 5 | # allows lost updates if non-locking methods called 6 | module V3 7 | class << self 8 | def call(from, to, amount) 9 | ActiveRecord::Base.transaction do 10 | from.lock! 11 | to.lock! 12 | 13 | # emulate some heavy-lifting stuff 14 | # giving a chance for standalone #withdraw / #deposit finish first 15 | sleep(0.05) 16 | 17 | withdraw(from, amount) 18 | deposit(to, amount) 19 | end 20 | end 21 | 22 | def withdraw(from, amount) 23 | from.update!(balance: from.balance - amount) 24 | end 25 | 26 | def deposit(to, amount) 27 | to.update!(balance: to.balance + amount) 28 | end 29 | end 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /app/services/transfer_balance/v5.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module TransferBalance 4 | # transaction w/ locks everywhere 5 | # no lost updates 6 | # guarantees same order 7 | # fails on deadlock 8 | module V5 9 | class << self 10 | def call(from, to, amount) 11 | ActiveRecord::Base.transaction do 12 | from.lock! 13 | to.lock! 14 | 15 | # emulate some heavy-lifting stuff 16 | # giving a chance for standalone #withdraw / #deposit finish first 17 | sleep(0.05) 18 | 19 | withdraw(from, amount) 20 | deposit(to, amount) 21 | end 22 | end 23 | 24 | def withdraw(from, amount) 25 | from.with_lock { from.update!(balance: from.balance - amount) } 26 | end 27 | 28 | def deposit(to, amount) 29 | to.with_lock { to.update!(balance: to.balance + amount) } 30 | end 31 | end 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /bin/update: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require 'fileutils' 3 | include FileUtils 4 | 5 | # path to your application root. 6 | APP_ROOT = File.expand_path('..', __dir__) 7 | 8 | def system!(*args) 9 | system(*args) || abort("\n== Command #{args} failed ==") 10 | end 11 | 12 | chdir APP_ROOT do 13 | # This script is a way to update your development environment automatically. 14 | # Add necessary update steps to this file. 15 | 16 | puts '== Installing dependencies ==' 17 | system! 'gem install bundler --conservative' 18 | system('bundle check') || system!('bundle install') 19 | 20 | # Install JavaScript dependencies if using Yarn 21 | # system('bin/yarn') 22 | 23 | puts "\n== Updating database ==" 24 | system! 'bin/rails db:migrate' 25 | 26 | puts "\n== Removing old logs and tempfiles ==" 27 | system! 'bin/rails log:clear tmp:clear' 28 | 29 | puts "\n== Restarting application server ==" 30 | system! 'bin/rails restart' 31 | end 32 | -------------------------------------------------------------------------------- /config/locales/en.yml: -------------------------------------------------------------------------------- 1 | # Files in the config/locales directory are used for internationalization 2 | # and are automatically loaded by Rails. If you want to use locales other 3 | # than English, add the necessary files in this directory. 4 | # 5 | # To use the locales, use `I18n.t`: 6 | # 7 | # I18n.t 'hello' 8 | # 9 | # In views, this is aliased to just `t`: 10 | # 11 | # <%= t('hello') %> 12 | # 13 | # To use a different locale, set it with `I18n.locale`: 14 | # 15 | # I18n.locale = :es 16 | # 17 | # This would use the information in config/locales/es.yml. 18 | # 19 | # The following keys must be escaped otherwise they will not be retrieved by 20 | # the default I18n backend: 21 | # 22 | # true, false, on, off, yes, no 23 | # 24 | # Instead, surround them with single quotes. 25 | # 26 | # en: 27 | # 'true': 'foo' 28 | # 29 | # To learn more, please read the Rails Internationalization guide 30 | # available at http://guides.rubyonrails.org/i18n.html. 31 | 32 | en: 33 | hello: "Hello world" 34 | -------------------------------------------------------------------------------- /app/services/transfer_balance/v6.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module TransferBalance 4 | # transaction w/ locks everywhere 5 | # no lost updates 6 | # guarantees same order 7 | # avoids deadlock by lock ordering 8 | module V6 9 | class << self 10 | def call(from, to, amount, skip_sleep = false) 11 | ActiveRecord::Base.transaction do 12 | accounts = [from, to].sort_by(&:id) 13 | accounts.first.lock! 14 | accounts.last.lock! 15 | 16 | # emulate some heavy-lifting stuff 17 | # giving a chance for standalone #withdraw / #deposit finish first 18 | sleep(0.05) unless skip_sleep 19 | 20 | withdraw(from, amount) 21 | deposit(to, amount) 22 | end 23 | end 24 | 25 | def withdraw(from, amount) 26 | from.with_lock { from.update!(balance: from.balance - amount) } 27 | end 28 | 29 | def deposit(to, amount) 30 | to.with_lock { to.update!(balance: to.balance + amount) } 31 | end 32 | end 33 | end 34 | end 35 | -------------------------------------------------------------------------------- /app/services/transfer_balance/v7.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module TransferBalance 4 | # transaction w/ locks everywhere 5 | # no lost updates 6 | # guarantees same order 7 | # avoids deadlock by rescue w/ retry 8 | # can be very slow 9 | module V7 10 | class << self 11 | def call(from, to, amount, skip_sleep = false) 12 | ActiveRecord::Base.transaction do 13 | from.lock! 14 | to.lock! 15 | 16 | # emulate some heavy-lifting stuff 17 | # giving a chance for standalone #withdraw / #deposit finish first 18 | sleep(0.05) unless skip_sleep 19 | 20 | withdraw(from, amount) 21 | deposit(to, amount) 22 | end 23 | rescue ActiveRecord::Deadlocked 24 | retry 25 | end 26 | 27 | def withdraw(from, amount) 28 | from.with_lock { from.update!(balance: from.balance - amount) } 29 | end 30 | 31 | def deposit(to, amount) 32 | to.with_lock { to.update!(balance: to.balance + amount) } 33 | end 34 | end 35 | end 36 | end 37 | -------------------------------------------------------------------------------- /bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require 'fileutils' 3 | include FileUtils 4 | 5 | # path to your application root. 6 | APP_ROOT = File.expand_path('..', __dir__) 7 | 8 | def system!(*args) 9 | system(*args) || abort("\n== Command #{args} failed ==") 10 | end 11 | 12 | chdir APP_ROOT do 13 | # This script is a starting point to setup your application. 14 | # Add necessary setup steps to this file. 15 | 16 | puts '== Installing dependencies ==' 17 | system! 'gem install bundler --conservative' 18 | system('bundle check') || system!('bundle install') 19 | 20 | # Install JavaScript dependencies if using Yarn 21 | # system('bin/yarn') 22 | 23 | # puts "\n== Copying sample files ==" 24 | # unless File.exist?('config/database.yml') 25 | # cp 'config/database.yml.sample', 'config/database.yml' 26 | # end 27 | 28 | puts "\n== Preparing database ==" 29 | system! 'bin/rails db:setup' 30 | 31 | puts "\n== Removing old logs and tempfiles ==" 32 | system! 'bin/rails log:clear tmp:clear' 33 | 34 | puts "\n== Restarting application server ==" 35 | system! 'bin/rails restart' 36 | end 37 | -------------------------------------------------------------------------------- /app/services/transfer_balance/opt_lock_v1.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module TransferBalance 4 | # transaction w/ optimistic locks 5 | # no lost updates 6 | # retries on ActiveRecord::StaleObjectError & deadlocks 7 | # does not guarantee same order 8 | module OptLockV1 9 | class << self 10 | def call(from, to, amount, skip_sleep = false) 11 | ActiveRecord::Base.transaction do 12 | # emulate some heavy-lifting stuff 13 | # giving a chance for standalone #withdraw / #deposit finish first 14 | sleep(0.05) unless skip_sleep 15 | 16 | withdraw(from, amount) 17 | deposit(to, amount) 18 | end 19 | rescue ActiveRecord::Deadlocked, ActiveRecord::StaleObjectError 20 | retry 21 | end 22 | 23 | def withdraw(from, amount) 24 | from.update!(balance: from.balance - amount) 25 | rescue ActiveRecord::StaleObjectError 26 | from.reload 27 | retry 28 | end 29 | 30 | def deposit(to, amount) 31 | to.update!(balance: to.balance + amount) 32 | rescue ActiveRecord::StaleObjectError 33 | to.reload 34 | retry 35 | end 36 | end 37 | end 38 | end 39 | -------------------------------------------------------------------------------- /config/initializers/content_security_policy.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Define an application-wide content security policy 4 | # For further information see the following documentation 5 | # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy 6 | 7 | # Rails.application.config.content_security_policy do |policy| 8 | # policy.default_src :self, :https 9 | # policy.font_src :self, :https, :data 10 | # policy.img_src :self, :https, :data 11 | # policy.object_src :none 12 | # policy.script_src :self, :https 13 | # policy.style_src :self, :https 14 | 15 | # # Specify URI for violation reports 16 | # # policy.report_uri "/csp-violation-report-endpoint" 17 | # end 18 | 19 | # If you are using UJS then enable automatic nonce generation 20 | # Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) } 21 | 22 | # Report CSP violations to a specified URI 23 | # For further information see the following documentation: 24 | # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only 25 | # Rails.application.config.content_security_policy_report_only = true 26 | -------------------------------------------------------------------------------- /config/application.rb: -------------------------------------------------------------------------------- 1 | require_relative 'boot' 2 | 3 | require "rails" 4 | # Pick the frameworks you want: 5 | require "active_model/railtie" 6 | require "active_job/railtie" 7 | require "active_record/railtie" 8 | # require "active_storage/engine" 9 | require "action_controller/railtie" 10 | require "action_mailer/railtie" 11 | require "action_view/railtie" 12 | # require "action_cable/engine" 13 | require "sprockets/railtie" 14 | # require "rails/test_unit/railtie" 15 | 16 | # Require the gems listed in Gemfile, including any gems 17 | # you've limited to :test, :development, or :production. 18 | Bundler.require(*Rails.groups) 19 | 20 | module Alicenbob 21 | class Application < Rails::Application 22 | # Initialize configuration defaults for originally generated Rails version. 23 | config.load_defaults 5.2 24 | 25 | # Settings in config/environments/* take precedence over those specified here. 26 | # Application configuration can go into files in config/initializers 27 | # -- all .rb files in that directory are automatically loaded after loading 28 | # the framework and any gems in your application. 29 | 30 | # Don't generate system test files. 31 | config.generators.system_tests = nil 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /spec/support/shared_contexts/handles_deadlocks.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | shared_context 'handles deadlocks' do |account_class = Account| 4 | let(:alice) { account_class.create(name: 'Alice', balance: 1100) } 5 | let(:bob) { account_class.create(name: 'Bob', balance: 1100) } 6 | 7 | before do 8 | alice # create Alice 9 | bob # create Bob 10 | end 11 | 12 | it 'handles deadlocks' do 13 | aggregate_failures do 14 | expect(ActiveRecord::Base.connection.pool.size).to be > 4 15 | available_db_connections = 4 16 | 17 | fails = Array.new(available_db_connections) { false } 18 | 19 | threads = Array.new(available_db_connections) do |i| 20 | Thread.new do 21 | alice = account_class.find_by!(name: 'Alice') 22 | bob = account_class.find_by!(name: 'Bob') 23 | begin 24 | if i.even? 25 | described_class.call(bob, alice, 100) 26 | else 27 | described_class.call(alice, bob, 100) 28 | end 29 | rescue ActiveRecord::RecordInvalid 30 | fails[i] = true 31 | end 32 | end 33 | end 34 | 35 | threads.each(&:join) 36 | expect(fails.count(true)).to eq(0) 37 | expect(alice.reload.balance).to eq(1100) 38 | expect(bob.reload.balance).to eq(1100) 39 | end 40 | end 41 | end 42 | -------------------------------------------------------------------------------- /spec/support/shared_contexts/conflicting_parallel_operations.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | shared_context 'conflicting parallel operations' do |account_class = Account| 4 | let(:alice) { account_class.create(name: 'Alice', balance: 100) } 5 | let(:bob) { account_class.create(name: 'Bob', balance: 100) } 6 | 7 | before do 8 | alice # create Alice 9 | bob # create Bob 10 | end 11 | 12 | it 'fails all but one' do 13 | aggregate_failures do 14 | expect(ActiveRecord::Base.connection.pool.size).to be > 4 15 | available_db_connections = ActiveRecord::Base.connection.pool.size - 1 16 | 17 | fails = Array.new(available_db_connections) { false } 18 | 19 | threads = Array.new(available_db_connections) do |i| 20 | Thread.new do 21 | alice = account_class.find_by!(name: 'Alice') 22 | bob = account_class.find_by!(name: 'Bob') 23 | begin 24 | if i.zero? 25 | described_class.call(bob, alice, 100) 26 | else 27 | # allow first transfer to start first 28 | sleep(0.01) 29 | described_class.withdraw(bob, 100) 30 | end 31 | rescue ActiveRecord::RecordInvalid 32 | fails[i] = true 33 | end 34 | end 35 | end 36 | 37 | threads.each(&:join) 38 | expect(fails.count(true)).to eq(available_db_connections - 1) 39 | end 40 | end 41 | end 42 | -------------------------------------------------------------------------------- /config/puma.rb: -------------------------------------------------------------------------------- 1 | # Puma can serve each request in a thread from an internal thread pool. 2 | # The `threads` method setting takes two numbers: a minimum and maximum. 3 | # Any libraries that use thread pools should be configured to match 4 | # the maximum value specified for Puma. Default is set to 5 threads for minimum 5 | # and maximum; this matches the default thread size of Active Record. 6 | # 7 | threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 } 8 | threads threads_count, threads_count 9 | 10 | # Specifies the `port` that Puma will listen on to receive requests; default is 3000. 11 | # 12 | port ENV.fetch("PORT") { 3000 } 13 | 14 | # Specifies the `environment` that Puma will run in. 15 | # 16 | environment ENV.fetch("RAILS_ENV") { "development" } 17 | 18 | # Specifies the number of `workers` to boot in clustered mode. 19 | # Workers are forked webserver processes. If using threads and workers together 20 | # the concurrency of the application would be max `threads` * `workers`. 21 | # Workers do not work on JRuby or Windows (both of which do not support 22 | # processes). 23 | # 24 | # workers ENV.fetch("WEB_CONCURRENCY") { 2 } 25 | 26 | # Use the `preload_app!` method when specifying a `workers` number. 27 | # This directive tells Puma to first boot the application and load code 28 | # before forking the application. This takes advantage of Copy On Write 29 | # process behavior so workers use less memory. 30 | # 31 | # preload_app! 32 | 33 | # Allow puma to be restarted by `rails restart` command. 34 | plugin :tmp_restart 35 | -------------------------------------------------------------------------------- /spec/support/shared_contexts/conflicting_parallel_operations_order_matters.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | shared_context 'conflicting parallel operations, order matters' do |account_class = Account| 4 | let(:alice) { account_class.create(name: 'Alice', balance: 100) } 5 | let(:bob) { account_class.create(name: 'Bob', balance: 100) } 6 | 7 | before do 8 | alice # create Alice 9 | bob # create Bob 10 | end 11 | 12 | it 'preserves order' do 13 | aggregate_failures do 14 | expect(ActiveRecord::Base.connection.pool.size).to be > 4 15 | available_db_connections = ActiveRecord::Base.connection.pool.size - 1 16 | 17 | fails = Array.new(available_db_connections) { false } 18 | 19 | threads = Array.new(available_db_connections) do |i| 20 | Thread.new do 21 | alice = account_class.find_by!(name: 'Alice') 22 | bob = account_class.find_by!(name: 'Bob') 23 | begin 24 | if i.zero? 25 | described_class.call(bob, alice, 100) 26 | else 27 | # allow first transfer to start first 28 | sleep(0.01) 29 | described_class.withdraw(bob, 100) 30 | end 31 | rescue ActiveRecord::RecordInvalid 32 | fails[i] = true 33 | end 34 | end 35 | end 36 | 37 | threads.each(&:join) 38 | expect(fails.count(true)).to eq(available_db_connections - 1) 39 | expect(alice.reload.balance).to eq(200) 40 | expect(bob.reload.balance).to eq(0) 41 | end 42 | end 43 | end 44 | -------------------------------------------------------------------------------- /db/schema.rb: -------------------------------------------------------------------------------- 1 | # This file is auto-generated from the current state of the database. Instead 2 | # of editing this file, please use the migrations feature of Active Record to 3 | # incrementally modify your database, and then regenerate this schema definition. 4 | # 5 | # Note that this schema.rb definition is the authoritative source for your 6 | # database schema. If you need to create the application database on another 7 | # system, you should be using db:schema:load, not running all the migrations 8 | # from scratch. The latter is a flawed and unsustainable approach (the more migrations 9 | # you'll amass, the slower it'll run and the greater likelihood for issues). 10 | # 11 | # It's strongly recommended that you check this file into your version control system. 12 | 13 | ActiveRecord::Schema.define(version: 2018_09_23_070102) do 14 | 15 | # These are extensions that must be enabled in order to support this database 16 | enable_extension "plpgsql" 17 | 18 | create_table "accounts", force: :cascade do |t| 19 | t.string "name", null: false 20 | t.integer "balance", null: false 21 | t.datetime "created_at", null: false 22 | t.datetime "updated_at", null: false 23 | t.index ["name"], name: "index_accounts_on_name", unique: true 24 | end 25 | 26 | create_table "opt_lock_accounts", force: :cascade do |t| 27 | t.string "name", null: false 28 | t.integer "balance", null: false 29 | t.integer "lock_version", default: 0 30 | t.datetime "created_at", null: false 31 | t.datetime "updated_at", null: false 32 | t.index ["name"], name: "index_opt_lock_accounts_on_name", unique: true 33 | end 34 | 35 | end 36 | -------------------------------------------------------------------------------- /app/services/transfer_balance/v9.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module TransferBalance 4 | # transaction w/ serializable isolation level 5 | # no lost updates 6 | # does not guarantee same order 7 | # avoids deadlock by rescue w/ retry 8 | module V9 9 | class << self 10 | def call(from, to, amount, skip_sleep = false) 11 | ActiveRecord::Base.transaction(options) do 12 | # emulate some heavy-lifting stuff 13 | # giving a chance for standalone #withdraw / #deposit finish first 14 | sleep(0.05) unless skip_sleep 15 | 16 | withdraw(from, amount) 17 | deposit(to, amount) 18 | end 19 | rescue ActiveRecord::Deadlocked, ActiveRecord::SerializationFailure 20 | retry 21 | end 22 | 23 | def withdraw(from, amount) 24 | from.transaction(options) do 25 | from.reload 26 | from.update!(balance: from.balance - amount) 27 | end 28 | rescue ActiveRecord::SerializationFailure 29 | ActiveRecord::Base.connection.transaction_open? ? raise : retry 30 | end 31 | 32 | def deposit(to, amount) 33 | to.transaction(options) do 34 | to.reload 35 | to.update!(balance: to.balance + amount) 36 | end 37 | rescue ActiveRecord::SerializationFailure 38 | ActiveRecord::Base.connection.transaction_open? ? raise : retry 39 | end 40 | 41 | def options 42 | if ActiveRecord::Base.connection.transaction_open? 43 | {} 44 | else 45 | { isolation: :serializable } 46 | end 47 | end 48 | end 49 | end 50 | end 51 | -------------------------------------------------------------------------------- /app/services/transfer_balance/v8.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module TransferBalance 4 | # transaction w/ repeatable_read isolation level 5 | # no lost updates 6 | # does not guarantee same order 7 | # avoids deadlock by rescue w/ retry 8 | module V8 9 | class << self 10 | def call(from, to, amount, skip_sleep = false) 11 | ActiveRecord::Base.transaction(options) do 12 | # emulate some heavy-lifting stuff 13 | # giving a chance for standalone #withdraw / #deposit finish first 14 | sleep(0.05) unless skip_sleep 15 | 16 | withdraw(from, amount) 17 | deposit(to, amount) 18 | end 19 | rescue ActiveRecord::Deadlocked, ActiveRecord::SerializationFailure 20 | retry 21 | end 22 | 23 | def withdraw(from, amount) 24 | from.transaction(options) do 25 | from.reload 26 | from.update!(balance: from.balance - amount) 27 | end 28 | rescue ActiveRecord::SerializationFailure 29 | ActiveRecord::Base.connection.transaction_open? ? raise : retry 30 | end 31 | 32 | def deposit(to, amount) 33 | to.transaction(options) do 34 | to.reload 35 | to.update!(balance: to.balance + amount) 36 | end 37 | rescue ActiveRecord::SerializationFailure 38 | ActiveRecord::Base.connection.transaction_open? ? raise : retry 39 | end 40 | 41 | def options 42 | if ActiveRecord::Base.connection.transaction_open? 43 | {} 44 | else 45 | { isolation: :repeatable_read } 46 | end 47 | end 48 | end 49 | end 50 | end 51 | -------------------------------------------------------------------------------- /public/500.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | We're sorry, but something went wrong (500) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

We're sorry, but something went wrong.

62 |
63 |

If you are the application owner check the logs for more information.

64 |
65 | 66 | 67 | -------------------------------------------------------------------------------- /config/environments/test.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # The test environment is used exclusively to run your application's 5 | # test suite. You never need to work with it otherwise. Remember that 6 | # your test database is "scratch space" for the test suite and is wiped 7 | # and recreated between test runs. Don't rely on the data there! 8 | config.cache_classes = true 9 | 10 | # Do not eager load code on boot. This avoids loading your whole application 11 | # just for the purpose of running a single test. If you are using a tool that 12 | # preloads Rails for running tests, you may have to set it to true. 13 | config.eager_load = false 14 | 15 | # Configure public file server for tests with Cache-Control for performance. 16 | config.public_file_server.enabled = true 17 | config.public_file_server.headers = { 18 | 'Cache-Control' => "public, max-age=#{1.hour.to_i}" 19 | } 20 | 21 | # Show full error reports and disable caching. 22 | config.consider_all_requests_local = true 23 | config.action_controller.perform_caching = false 24 | 25 | # Raise exceptions instead of rendering exception templates. 26 | config.action_dispatch.show_exceptions = false 27 | 28 | # Disable request forgery protection in test environment. 29 | config.action_controller.allow_forgery_protection = false 30 | 31 | config.action_mailer.perform_caching = false 32 | 33 | # Tell Action Mailer not to deliver emails to the real world. 34 | # The :test delivery method accumulates sent emails in the 35 | # ActionMailer::Base.deliveries array. 36 | config.action_mailer.delivery_method = :test 37 | 38 | # Print deprecation notices to the stderr. 39 | config.active_support.deprecation = :stderr 40 | 41 | # Raises error for missing translations 42 | # config.action_view.raise_on_missing_translations = true 43 | end 44 | -------------------------------------------------------------------------------- /public/422.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The change you wanted was rejected (422) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

The change you wanted was rejected.

62 |

Maybe you tried to change something you didn't have access to.

63 |
64 |

If you are the application owner check the logs for more information.

65 |
66 | 67 | 68 | -------------------------------------------------------------------------------- /public/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The page you were looking for doesn't exist (404) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

The page you were looking for doesn't exist.

62 |

You may have mistyped the address or the page may have moved.

63 |
64 |

If you are the application owner check the logs for more information.

65 |
66 | 67 | 68 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | git_source(:github) { |repo| "https://github.com/#{repo}.git" } 3 | 4 | ruby '2.6.3' 5 | 6 | # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' 7 | gem 'rails', '~> 5.2.0' 8 | # Use postgresql as the database for Active Record 9 | gem 'pg', '>= 0.18', '< 2.0' 10 | # Use Puma as the app server 11 | gem 'puma', '~> 3.11' 12 | # Use SCSS for stylesheets 13 | gem 'sass-rails', '~> 5.0' 14 | # Use Uglifier as compressor for JavaScript assets 15 | gem 'uglifier', '>= 1.3.0' 16 | # See https://github.com/rails/execjs#readme for more supported runtimes 17 | # gem 'mini_racer', platforms: :ruby 18 | 19 | # Use CoffeeScript for .coffee assets and views 20 | gem 'coffee-rails', '~> 4.2' 21 | # Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks 22 | gem 'turbolinks', '~> 5' 23 | # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder 24 | gem 'jbuilder', '~> 2.5' 25 | # Use ActiveModel has_secure_password 26 | # gem 'bcrypt', '~> 3.1.7' 27 | 28 | # Use Capistrano for deployment 29 | # gem 'capistrano-rails', group: :development 30 | 31 | # Reduces boot times through caching; required in config/boot.rb 32 | gem 'bootsnap', '>= 1.1.0', require: false 33 | 34 | group :development, :test do 35 | # Call 'byebug' anywhere in the code to stop execution and get a debugger console 36 | gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] 37 | end 38 | 39 | group :development do 40 | gem 'benchmark-ips', require: false 41 | # Access an interactive console on exception pages or by calling 'console' anywhere in the code. 42 | gem 'web-console', '>= 3.3.0' 43 | gem 'listen', '>= 3.0.5', '< 3.2' 44 | # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring 45 | gem 'spring' 46 | gem 'spring-watcher-listen', '~> 2.0.0' 47 | 48 | gem 'rubocop', require: false 49 | gem 'rubocop-rspec', require: false 50 | end 51 | 52 | group :test do 53 | gem 'database_cleaner' 54 | gem 'rspec-rails' 55 | end 56 | 57 | 58 | # Windows does not include zoneinfo files, so bundle the tzinfo-data gem 59 | gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] 60 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Alice and Bob transfers money 2 | 3 | ## Illustrating repository for the [presentation](https://slides.com/ivanrabotyga/alicenbob) 4 | 5 | Setup: 6 | ```sh 7 | git clone git@github.com:rabotyaga/alicenbob.git 8 | bundle 9 | rails db:setup 10 | ``` 11 | 12 | Tests: 13 | ``` 14 | bundle exec rspec 15 | ``` 16 | 17 | Tests output should be like: 18 | ``` 19 | Finished in 13.16 seconds (files took 0.82014 seconds to load) 20 | 47 examples, 10 failures 21 | 22 | Failed examples: 23 | 24 | rspec ./spec/services/transfer_balance/opt_lock_v0_spec.rb:12 # TransferBalance::OptLockV0 with conflicting parallel operations fails all but one 25 | rspec ./spec/services/transfer_balance/opt_lock_v1_spec.rb[1:1:4:1] # TransferBalance::OptLockV1 behaves like fully operational with conflicting parallel operations preserves order 26 | rspec ./spec/services/transfer_balance/v0_spec.rb:8 # TransferBalance::V0 with invalid transfer both balances stay unchanged 27 | rspec ./spec/services/transfer_balance/v1_spec.rb:8 # TransferBalance::V1 with invalid transfer both balances stay unchanged 28 | rspec ./spec/services/transfer_balance/v2_spec.rb:12 # TransferBalance::V2 with conflicting parallel operations fails all but one 29 | rspec ./spec/services/transfer_balance/v3_spec.rb:12 # TransferBalance::V3 with conflicting parallel operations fails all but one 30 | rspec ./spec/services/transfer_balance/v4_spec.rb:16 # TransferBalance::V4 with conflicting parallel operations preserves order 31 | rspec ./spec/services/transfer_balance/v5_spec.rb[1:1:5:1] # TransferBalance::V5 behaves like fully operational with non conflicting parallel operations handles deadlocks 32 | rspec ./spec/services/transfer_balance/v8_spec.rb[1:1:4:1] # TransferBalance::V8 behaves like fully operational with conflicting parallel operations preserves order 33 | rspec ./spec/services/transfer_balance/v9_spec.rb[1:1:4:1] # TransferBalance::V9 behaves like fully operational with conflicting parallel operations preserves order 34 | ``` 35 | 36 | which means 37 | 38 | ![features table](features.png) 39 | 40 | 41 | Benchmarks: 42 | ``` 43 | RAILS_ENV=test bundle exec rake benchmark 44 | ``` 45 | 46 | ![a lot of conflicts benchmark](benchmarks1.png) 47 | 48 | ![no conflicts benchmark](benchmarks2.png) 49 | -------------------------------------------------------------------------------- /config/environments/development.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # In the development environment your application's code is reloaded on 5 | # every request. This slows down response time but is perfect for development 6 | # since you don't have to restart the web server when you make code changes. 7 | config.cache_classes = false 8 | 9 | # Do not eager load code on boot. 10 | config.eager_load = false 11 | 12 | # Show full error reports. 13 | config.consider_all_requests_local = true 14 | 15 | # Enable/disable caching. By default caching is disabled. 16 | # Run rails dev:cache to toggle caching. 17 | if Rails.root.join('tmp', 'caching-dev.txt').exist? 18 | config.action_controller.perform_caching = true 19 | 20 | config.cache_store = :memory_store 21 | config.public_file_server.headers = { 22 | 'Cache-Control' => "public, max-age=#{2.days.to_i}" 23 | } 24 | else 25 | config.action_controller.perform_caching = false 26 | 27 | config.cache_store = :null_store 28 | end 29 | 30 | # Don't care if the mailer can't send. 31 | config.action_mailer.raise_delivery_errors = false 32 | 33 | config.action_mailer.perform_caching = false 34 | 35 | # Print deprecation notices to the Rails logger. 36 | config.active_support.deprecation = :log 37 | 38 | # Raise an error on page load if there are pending migrations. 39 | config.active_record.migration_error = :page_load 40 | 41 | # Highlight code that triggered database queries in logs. 42 | config.active_record.verbose_query_logs = true 43 | 44 | # Debug mode disables concatenation and preprocessing of assets. 45 | # This option may cause significant delays in view rendering with a large 46 | # number of complex assets. 47 | config.assets.debug = true 48 | 49 | # Suppress logger output for asset requests. 50 | config.assets.quiet = true 51 | 52 | # Raises error for missing translations 53 | # config.action_view.raise_on_missing_translations = true 54 | 55 | # Use an evented file watcher to asynchronously detect changes in source code, 56 | # routes, locales, etc. This feature depends on the listen gem. 57 | config.file_watcher = ActiveSupport::EventedFileUpdateChecker 58 | end 59 | -------------------------------------------------------------------------------- /spec/rails_helper.rb: -------------------------------------------------------------------------------- 1 | # This file is copied to spec/ when you run 'rails generate rspec:install' 2 | require 'spec_helper' 3 | ENV['RAILS_ENV'] ||= 'test' 4 | require File.expand_path('../../config/environment', __FILE__) 5 | # Prevent database truncation if the environment is production 6 | abort("The Rails environment is running in production mode!") if Rails.env.production? 7 | require 'rspec/rails' 8 | # Add additional requires below this line. Rails is not loaded until this point! 9 | 10 | # Requires supporting ruby files with custom matchers and macros, etc, in 11 | # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are 12 | # run as spec files by default. This means that files in spec/support that end 13 | # in _spec.rb will both be required and run as specs, causing the specs to be 14 | # run twice. It is recommended that you do not name files matching this glob to 15 | # end with _spec.rb. You can configure this pattern with the --pattern 16 | # option on the command line or in ~/.rspec, .rspec or `.rspec-local`. 17 | # 18 | # The following line is provided for convenience purposes. It has the downside 19 | # of increasing the boot-up time by auto-requiring all files in the support 20 | # directory. Alternatively, in the individual `*_spec.rb` files, manually 21 | # require only the support files necessary. 22 | # 23 | Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } 24 | 25 | # Checks for pending migrations and applies them before tests are run. 26 | # If you are not using ActiveRecord, you can remove this line. 27 | ActiveRecord::Migration.maintain_test_schema! 28 | 29 | RSpec.configure do |config| 30 | # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures 31 | config.fixture_path = "#{::Rails.root}/spec/fixtures" 32 | 33 | # If you're not using ActiveRecord, or you'd prefer not to run each of your 34 | # examples within a transaction, remove the following line or assign false 35 | # instead of true. 36 | config.use_transactional_fixtures = false 37 | 38 | # RSpec Rails can automatically mix in different behaviours to your tests 39 | # based on their file location, for example enabling you to call `get` and 40 | # `post` in specs under `spec/controllers`. 41 | # 42 | # You can disable this behaviour by removing the line below, and instead 43 | # explicitly tag your specs with their type, e.g.: 44 | # 45 | # RSpec.describe UsersController, :type => :controller do 46 | # # ... 47 | # end 48 | # 49 | # The different available types are documented in the features, such as in 50 | # https://relishapp.com/rspec/rspec-rails/docs 51 | config.infer_spec_type_from_file_location! 52 | 53 | # Filter lines from Rails gems in backtraces. 54 | config.filter_rails_from_backtrace! 55 | # arbitrary gems may also be filtered via: 56 | # config.filter_gems_from_backtrace("gem name") 57 | end 58 | -------------------------------------------------------------------------------- /lib/tasks/benchmark.rake: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'benchmark/ips' 4 | 5 | desc 'Run benchmarks' 6 | task benchmark: :environment do 7 | create_accounts 8 | 9 | header('Alice & Bob (very high probability of lock waiting & deadlocks)') 10 | benchmark(:alice_n_bob) 11 | 12 | header('Random accounts (very low probability of lock waiting & deadlocks)') 13 | benchmark(:random_accounts) 14 | end 15 | 16 | # rubocop:disable Metrics/MethodLength 17 | def alice_n_bob(transfer_class, account_class = Account) 18 | threads = Array.new(available_db_connections) do |i| 19 | Thread.new do 20 | alice = account_class.find_by!(name: 'Alice') 21 | bob = account_class.find_by!(name: 'Bob') 22 | if i.even? 23 | transfer_class.call(bob, alice, 1, true) 24 | else 25 | transfer_class.call(alice, bob, 1, true) 26 | end 27 | end 28 | end 29 | 30 | threads.each(&:join) 31 | end 32 | # rubocop:enable Metrics/MethodLength 33 | 34 | def random_accounts(transfer_class, account_class = Account) 35 | threads = Array.new(available_db_connections) do 36 | Thread.new do 37 | acc1 = account_class.find_by!(name: "acc#{rand(1000)}") 38 | acc2 = account_class.find_by!(name: "acc#{rand(1000)}") 39 | transfer_class.call(acc1, acc2, 1, true) 40 | end 41 | end 42 | 43 | threads.each(&:join) 44 | end 45 | 46 | def available_db_connections 47 | ActiveRecord::Base.connection.pool.size - 1 48 | end 49 | 50 | def header(title) 51 | puts '=' * 80 52 | puts title 53 | puts "using #{available_db_connections} threads" 54 | puts '=' * 80 55 | end 56 | 57 | def create_accounts 58 | Account.find_or_create_by(name: 'Alice').update(balance: 1_000_000_000) 59 | Account.find_or_create_by(name: 'Bob').update(balance: 1_000_000_000) 60 | OptLockAccount.find_or_create_by(name: 'Alice').update(balance: 1_000_000_000) 61 | OptLockAccount.find_or_create_by(name: 'Bob').update(balance: 1_000_000_000) 62 | 63 | 1000.times do |i| 64 | Account.find_or_create_by(name: "acc#{i}").update(balance: 1_000_000_000) 65 | OptLockAccount.find_or_create_by(name: "acc#{i}").update(balance: 1_000_000_000) 66 | end 67 | end 68 | 69 | # rubocop:disable Metrics/MethodLength 70 | def benchmark(method) 71 | Benchmark.ips do |x| 72 | x.config(warmup: 0, time: 15) 73 | 74 | x.report('v6 (lock ordering)') do 75 | send(method, TransferBalance::V6) 76 | end 77 | 78 | x.report('v7 (retry on deadlock)') do 79 | send(method, TransferBalance::V7) 80 | end 81 | 82 | x.report('v8 (repeatable read)') do 83 | send(method, TransferBalance::V8) 84 | end 85 | 86 | x.report('v9 (serializable)') do 87 | send(method, TransferBalance::V9) 88 | end 89 | 90 | x.report('opt_lock_v1 (retry on deadlock)') do 91 | send(method, TransferBalance::OptLockV1, OptLockAccount) 92 | end 93 | 94 | x.compare! 95 | end 96 | end 97 | # rubocop:enable Metrics/MethodLength 98 | -------------------------------------------------------------------------------- /config/database.yml: -------------------------------------------------------------------------------- 1 | # PostgreSQL. Versions 9.1 and up are supported. 2 | # 3 | # Install the pg driver: 4 | # gem install pg 5 | # On OS X with Homebrew: 6 | # gem install pg -- --with-pg-config=/usr/local/bin/pg_config 7 | # On OS X with MacPorts: 8 | # gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config 9 | # On Windows: 10 | # gem install pg 11 | # Choose the win32 build. 12 | # Install PostgreSQL and put its /bin directory on your path. 13 | # 14 | # Configure Using Gemfile 15 | # gem 'pg' 16 | # 17 | default: &default 18 | adapter: postgresql 19 | encoding: unicode 20 | # For details on connection pooling, see Rails configuration guide 21 | # http://guides.rubyonrails.org/configuring.html#database-pooling 22 | pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> 23 | 24 | development: 25 | <<: *default 26 | database: alicenbob_development 27 | 28 | # The specified database role being used to connect to postgres. 29 | # To create additional roles in postgres see `$ createuser --help`. 30 | # When left blank, postgres will use the default role. This is 31 | # the same name as the operating system user that initialized the database. 32 | #username: alicenbob 33 | 34 | # The password associated with the postgres role (username). 35 | #password: 36 | 37 | # Connect on a TCP socket. Omitted by default since the client uses a 38 | # domain socket that doesn't need configuration. Windows does not have 39 | # domain sockets, so uncomment these lines. 40 | #host: localhost 41 | 42 | # The TCP port the server listens on. Defaults to 5432. 43 | # If your server runs on a different port number, change accordingly. 44 | #port: 5432 45 | 46 | # Schema search path. The server defaults to $user,public 47 | #schema_search_path: myapp,sharedapp,public 48 | 49 | # Minimum log levels, in increasing order: 50 | # debug5, debug4, debug3, debug2, debug1, 51 | # log, notice, warning, error, fatal, and panic 52 | # Defaults to warning. 53 | #min_messages: notice 54 | 55 | # Warning: The database defined as "test" will be erased and 56 | # re-generated from your development database when you run "rake". 57 | # Do not set this db to the same as development or production. 58 | test: 59 | <<: *default 60 | database: alicenbob_test 61 | 62 | # As with config/secrets.yml, you never want to store sensitive information, 63 | # like your database password, in your source code. If your source code is 64 | # ever seen by anyone, they now have access to your database. 65 | # 66 | # Instead, provide the password as a unix environment variable when you boot 67 | # the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database 68 | # for a full rundown on how to provide these environment variables in a 69 | # production deployment. 70 | # 71 | # On Heroku and other platform providers, you may have a full connection URL 72 | # available as an environment variable. For example: 73 | # 74 | # DATABASE_URL="postgres://myuser:mypass@localhost/somedatabase" 75 | # 76 | # You can use this database configuration with: 77 | # 78 | # production: 79 | # url: <%= ENV['DATABASE_URL'] %> 80 | # 81 | production: 82 | <<: *default 83 | database: alicenbob_production 84 | username: alicenbob 85 | password: <%= ENV['ALICENBOB_DATABASE_PASSWORD'] %> 86 | -------------------------------------------------------------------------------- /config/environments/production.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # Code is not reloaded between requests. 5 | config.cache_classes = true 6 | 7 | # Eager load code on boot. This eager loads most of Rails and 8 | # your application in memory, allowing both threaded web servers 9 | # and those relying on copy on write to perform better. 10 | # Rake tasks automatically ignore this option for performance. 11 | config.eager_load = true 12 | 13 | # Full error reports are disabled and caching is turned on. 14 | config.consider_all_requests_local = false 15 | config.action_controller.perform_caching = true 16 | 17 | # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] 18 | # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). 19 | # config.require_master_key = true 20 | 21 | # Disable serving static files from the `/public` folder by default since 22 | # Apache or NGINX already handles this. 23 | config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? 24 | 25 | # Compress JavaScripts and CSS. 26 | config.assets.js_compressor = :uglifier 27 | # config.assets.css_compressor = :sass 28 | 29 | # Do not fallback to assets pipeline if a precompiled asset is missed. 30 | config.assets.compile = false 31 | 32 | # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb 33 | 34 | # Enable serving of images, stylesheets, and JavaScripts from an asset server. 35 | # config.action_controller.asset_host = 'http://assets.example.com' 36 | 37 | # Specifies the header that your server uses for sending files. 38 | # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache 39 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX 40 | 41 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 42 | # config.force_ssl = true 43 | 44 | # Use the lowest log level to ensure availability of diagnostic information 45 | # when problems arise. 46 | config.log_level = :debug 47 | 48 | # Prepend all log lines with the following tags. 49 | config.log_tags = [ :request_id ] 50 | 51 | # Use a different cache store in production. 52 | # config.cache_store = :mem_cache_store 53 | 54 | # Use a real queuing backend for Active Job (and separate queues per environment) 55 | # config.active_job.queue_adapter = :resque 56 | # config.active_job.queue_name_prefix = "alicenbob_#{Rails.env}" 57 | 58 | config.action_mailer.perform_caching = false 59 | 60 | # Ignore bad email addresses and do not raise email delivery errors. 61 | # Set this to true and configure the email server for immediate delivery to raise delivery errors. 62 | # config.action_mailer.raise_delivery_errors = false 63 | 64 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 65 | # the I18n.default_locale when a translation cannot be found). 66 | config.i18n.fallbacks = true 67 | 68 | # Send deprecation notices to registered listeners. 69 | config.active_support.deprecation = :notify 70 | 71 | # Use default logging formatter so that PID and timestamp are not suppressed. 72 | config.log_formatter = ::Logger::Formatter.new 73 | 74 | # Use a different logger for distributed setups. 75 | # require 'syslog/logger' 76 | # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') 77 | 78 | if ENV["RAILS_LOG_TO_STDOUT"].present? 79 | logger = ActiveSupport::Logger.new(STDOUT) 80 | logger.formatter = config.log_formatter 81 | config.logger = ActiveSupport::TaggedLogging.new(logger) 82 | end 83 | 84 | # Do not dump schema after migrations. 85 | config.active_record.dump_schema_after_migration = false 86 | end 87 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | # This file was generated by the `rails generate rspec:install` command. Conventionally, all 2 | # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. 3 | # The generated `.rspec` file contains `--require spec_helper` which will cause 4 | # this file to always be loaded, without a need to explicitly require it in any 5 | # files. 6 | # 7 | # Given that it is always loaded, you are encouraged to keep this file as 8 | # light-weight as possible. Requiring heavyweight dependencies from this file 9 | # will add to the boot time of your test suite on EVERY test run, even for an 10 | # individual file that may not need all of that loaded. Instead, consider making 11 | # a separate helper file that requires the additional dependencies and performs 12 | # the additional setup, and require it from the spec files that actually need 13 | # it. 14 | # 15 | # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration 16 | RSpec.configure do |config| 17 | # rspec-expectations config goes here. You can use an alternate 18 | # assertion/expectation library such as wrong or the stdlib/minitest 19 | # assertions if you prefer. 20 | config.expect_with :rspec do |expectations| 21 | # This option will default to `true` in RSpec 4. It makes the `description` 22 | # and `failure_message` of custom matchers include text for helper methods 23 | # defined using `chain`, e.g.: 24 | # be_bigger_than(2).and_smaller_than(4).description 25 | # # => "be bigger than 2 and smaller than 4" 26 | # ...rather than: 27 | # # => "be bigger than 2" 28 | expectations.include_chain_clauses_in_custom_matcher_descriptions = true 29 | end 30 | 31 | # rspec-mocks config goes here. You can use an alternate test double 32 | # library (such as bogus or mocha) by changing the `mock_with` option here. 33 | config.mock_with :rspec do |mocks| 34 | # Prevents you from mocking or stubbing a method that does not exist on 35 | # a real object. This is generally recommended, and will default to 36 | # `true` in RSpec 4. 37 | mocks.verify_partial_doubles = true 38 | end 39 | 40 | # This option will default to `:apply_to_host_groups` in RSpec 4 (and will 41 | # have no way to turn it off -- the option exists only for backwards 42 | # compatibility in RSpec 3). It causes shared context metadata to be 43 | # inherited by the metadata hash of host groups and examples, rather than 44 | # triggering implicit auto-inclusion in groups with matching metadata. 45 | config.shared_context_metadata_behavior = :apply_to_host_groups 46 | 47 | # The settings below are suggested to provide a good initial experience 48 | # with RSpec, but feel free to customize to your heart's content. 49 | =begin 50 | # This allows you to limit a spec run to individual examples or groups 51 | # you care about by tagging them with `:focus` metadata. When nothing 52 | # is tagged with `:focus`, all examples get run. RSpec also provides 53 | # aliases for `it`, `describe`, and `context` that include `:focus` 54 | # metadata: `fit`, `fdescribe` and `fcontext`, respectively. 55 | config.filter_run_when_matching :focus 56 | 57 | # Allows RSpec to persist some state between runs in order to support 58 | # the `--only-failures` and `--next-failure` CLI options. We recommend 59 | # you configure your source control system to ignore this file. 60 | config.example_status_persistence_file_path = "spec/examples.txt" 61 | 62 | # Limits the available syntax to the non-monkey patched syntax that is 63 | # recommended. For more details, see: 64 | # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ 65 | # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ 66 | # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode 67 | config.disable_monkey_patching! 68 | 69 | # Many RSpec users commonly either run the entire suite or an individual 70 | # file, and it's useful to allow more verbose output when running an 71 | # individual spec file. 72 | if config.files_to_run.one? 73 | # Use the documentation formatter for detailed output, 74 | # unless a formatter has already been configured 75 | # (e.g. via a command-line flag). 76 | config.default_formatter = "doc" 77 | end 78 | 79 | # Print the 10 slowest examples and example groups at the 80 | # end of the spec run, to help surface which specs are running 81 | # particularly slow. 82 | config.profile_examples = 10 83 | 84 | # Run specs in random order to surface order dependencies. If you find an 85 | # order dependency and want to debug it, you can fix the order by providing 86 | # the seed, which is printed after each run. 87 | # --seed 1234 88 | config.order = :random 89 | 90 | # Seed global randomization in this process using the `--seed` CLI option. 91 | # Setting this allows you to use `--seed` to deterministically reproduce 92 | # test failures related to randomization by passing the same `--seed` value 93 | # as the one that triggered the failure. 94 | Kernel.srand config.seed 95 | =end 96 | end 97 | -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: https://rubygems.org/ 3 | specs: 4 | actioncable (5.2.2.1) 5 | actionpack (= 5.2.2.1) 6 | nio4r (~> 2.0) 7 | websocket-driver (>= 0.6.1) 8 | actionmailer (5.2.2.1) 9 | actionpack (= 5.2.2.1) 10 | actionview (= 5.2.2.1) 11 | activejob (= 5.2.2.1) 12 | mail (~> 2.5, >= 2.5.4) 13 | rails-dom-testing (~> 2.0) 14 | actionpack (5.2.2.1) 15 | actionview (= 5.2.2.1) 16 | activesupport (= 5.2.2.1) 17 | rack (~> 2.0) 18 | rack-test (>= 0.6.3) 19 | rails-dom-testing (~> 2.0) 20 | rails-html-sanitizer (~> 1.0, >= 1.0.2) 21 | actionview (5.2.2.1) 22 | activesupport (= 5.2.2.1) 23 | builder (~> 3.1) 24 | erubi (~> 1.4) 25 | rails-dom-testing (~> 2.0) 26 | rails-html-sanitizer (~> 1.0, >= 1.0.3) 27 | activejob (5.2.2.1) 28 | activesupport (= 5.2.2.1) 29 | globalid (>= 0.3.6) 30 | activemodel (5.2.2.1) 31 | activesupport (= 5.2.2.1) 32 | activerecord (5.2.2.1) 33 | activemodel (= 5.2.2.1) 34 | activesupport (= 5.2.2.1) 35 | arel (>= 9.0) 36 | activestorage (5.2.2.1) 37 | actionpack (= 5.2.2.1) 38 | activerecord (= 5.2.2.1) 39 | marcel (~> 0.3.1) 40 | activesupport (5.2.2.1) 41 | concurrent-ruby (~> 1.0, >= 1.0.2) 42 | i18n (>= 0.7, < 2) 43 | minitest (~> 5.1) 44 | tzinfo (~> 1.1) 45 | arel (9.0.0) 46 | ast (2.4.0) 47 | benchmark-ips (2.7.2) 48 | bindex (0.5.0) 49 | bootsnap (1.3.2) 50 | msgpack (~> 1.0) 51 | builder (3.2.3) 52 | byebug (10.0.2) 53 | coffee-rails (4.2.2) 54 | coffee-script (>= 2.2.0) 55 | railties (>= 4.0.0) 56 | coffee-script (2.4.1) 57 | coffee-script-source 58 | execjs 59 | coffee-script-source (1.12.2) 60 | concurrent-ruby (1.1.5) 61 | crass (1.0.4) 62 | database_cleaner (1.7.0) 63 | diff-lcs (1.3) 64 | erubi (1.7.1) 65 | execjs (2.7.0) 66 | ffi (1.9.25) 67 | globalid (0.4.2) 68 | activesupport (>= 4.2.0) 69 | i18n (1.1.1) 70 | concurrent-ruby (~> 1.0) 71 | jaro_winkler (1.5.1) 72 | jbuilder (2.8.0) 73 | activesupport (>= 4.2.0) 74 | multi_json (>= 1.2) 75 | listen (3.1.5) 76 | rb-fsevent (~> 0.9, >= 0.9.4) 77 | rb-inotify (~> 0.9, >= 0.9.7) 78 | ruby_dep (~> 1.2) 79 | loofah (2.2.3) 80 | crass (~> 1.0.2) 81 | nokogiri (>= 1.5.9) 82 | mail (2.7.1) 83 | mini_mime (>= 0.1.1) 84 | marcel (0.3.3) 85 | mimemagic (~> 0.3.2) 86 | method_source (0.9.2) 87 | mimemagic (0.3.3) 88 | mini_mime (1.0.1) 89 | mini_portile2 (2.4.0) 90 | minitest (5.11.3) 91 | msgpack (1.2.4) 92 | multi_json (1.13.1) 93 | nio4r (2.3.1) 94 | nokogiri (1.10.4) 95 | mini_portile2 (~> 2.4.0) 96 | parallel (1.12.1) 97 | parser (2.5.3.0) 98 | ast (~> 2.4.0) 99 | pg (1.1.3) 100 | powerpack (0.1.2) 101 | puma (3.12.0) 102 | rack (2.0.6) 103 | rack-test (1.1.0) 104 | rack (>= 1.0, < 3) 105 | rails (5.2.2.1) 106 | actioncable (= 5.2.2.1) 107 | actionmailer (= 5.2.2.1) 108 | actionpack (= 5.2.2.1) 109 | actionview (= 5.2.2.1) 110 | activejob (= 5.2.2.1) 111 | activemodel (= 5.2.2.1) 112 | activerecord (= 5.2.2.1) 113 | activestorage (= 5.2.2.1) 114 | activesupport (= 5.2.2.1) 115 | bundler (>= 1.3.0) 116 | railties (= 5.2.2.1) 117 | sprockets-rails (>= 2.0.0) 118 | rails-dom-testing (2.0.3) 119 | activesupport (>= 4.2.0) 120 | nokogiri (>= 1.6) 121 | rails-html-sanitizer (1.0.4) 122 | loofah (~> 2.2, >= 2.2.2) 123 | railties (5.2.2.1) 124 | actionpack (= 5.2.2.1) 125 | activesupport (= 5.2.2.1) 126 | method_source 127 | rake (>= 0.8.7) 128 | thor (>= 0.19.0, < 2.0) 129 | rainbow (3.0.0) 130 | rake (12.3.2) 131 | rb-fsevent (0.10.3) 132 | rb-inotify (0.9.10) 133 | ffi (>= 0.5.0, < 2) 134 | rspec-core (3.8.0) 135 | rspec-support (~> 3.8.0) 136 | rspec-expectations (3.8.2) 137 | diff-lcs (>= 1.2.0, < 2.0) 138 | rspec-support (~> 3.8.0) 139 | rspec-mocks (3.8.0) 140 | diff-lcs (>= 1.2.0, < 2.0) 141 | rspec-support (~> 3.8.0) 142 | rspec-rails (3.8.1) 143 | actionpack (>= 3.0) 144 | activesupport (>= 3.0) 145 | railties (>= 3.0) 146 | rspec-core (~> 3.8.0) 147 | rspec-expectations (~> 3.8.0) 148 | rspec-mocks (~> 3.8.0) 149 | rspec-support (~> 3.8.0) 150 | rspec-support (3.8.0) 151 | rubocop (0.60.0) 152 | jaro_winkler (~> 1.5.1) 153 | parallel (~> 1.10) 154 | parser (>= 2.5, != 2.5.1.1) 155 | powerpack (~> 0.1) 156 | rainbow (>= 2.2.2, < 4.0) 157 | ruby-progressbar (~> 1.7) 158 | unicode-display_width (~> 1.4.0) 159 | rubocop-rspec (1.30.1) 160 | rubocop (>= 0.60.0) 161 | ruby-progressbar (1.10.0) 162 | ruby_dep (1.5.0) 163 | sass (3.7.2) 164 | sass-listen (~> 4.0.0) 165 | sass-listen (4.0.0) 166 | rb-fsevent (~> 0.9, >= 0.9.4) 167 | rb-inotify (~> 0.9, >= 0.9.7) 168 | sass-rails (5.0.7) 169 | railties (>= 4.0.0, < 6) 170 | sass (~> 3.1) 171 | sprockets (>= 2.8, < 4.0) 172 | sprockets-rails (>= 2.0, < 4.0) 173 | tilt (>= 1.1, < 3) 174 | spring (2.0.2) 175 | activesupport (>= 4.2) 176 | spring-watcher-listen (2.0.1) 177 | listen (>= 2.7, < 4.0) 178 | spring (>= 1.2, < 3.0) 179 | sprockets (3.7.2) 180 | concurrent-ruby (~> 1.0) 181 | rack (> 1, < 3) 182 | sprockets-rails (3.2.1) 183 | actionpack (>= 4.0) 184 | activesupport (>= 4.0) 185 | sprockets (>= 3.0.0) 186 | thor (0.20.3) 187 | thread_safe (0.3.6) 188 | tilt (2.0.8) 189 | turbolinks (5.2.0) 190 | turbolinks-source (~> 5.2) 191 | turbolinks-source (5.2.0) 192 | tzinfo (1.2.5) 193 | thread_safe (~> 0.1) 194 | uglifier (4.1.20) 195 | execjs (>= 0.3.0, < 3) 196 | unicode-display_width (1.4.0) 197 | web-console (3.7.0) 198 | actionview (>= 5.0) 199 | activemodel (>= 5.0) 200 | bindex (>= 0.4.0) 201 | railties (>= 5.0) 202 | websocket-driver (0.7.0) 203 | websocket-extensions (>= 0.1.0) 204 | websocket-extensions (0.1.3) 205 | 206 | PLATFORMS 207 | ruby 208 | 209 | DEPENDENCIES 210 | benchmark-ips 211 | bootsnap (>= 1.1.0) 212 | byebug 213 | coffee-rails (~> 4.2) 214 | database_cleaner 215 | jbuilder (~> 2.5) 216 | listen (>= 3.0.5, < 3.2) 217 | pg (>= 0.18, < 2.0) 218 | puma (~> 3.11) 219 | rails (~> 5.2.0) 220 | rspec-rails 221 | rubocop 222 | rubocop-rspec 223 | sass-rails (~> 5.0) 224 | spring 225 | spring-watcher-listen (~> 2.0.0) 226 | turbolinks (~> 5) 227 | tzinfo-data 228 | uglifier (>= 1.3.0) 229 | web-console (>= 3.3.0) 230 | 231 | RUBY VERSION 232 | ruby 2.6.3p62 233 | 234 | BUNDLED WITH 235 | 1.17.3 236 | --------------------------------------------------------------------------------