ruby
43 lines · 9 steps
Atomic money transfers with Rails transactions
A service object moves funds between two accounts atomically using row locks and a database transaction.
Explained by
highlit
1class FundsTransfer
2 class InsufficientFundsError < StandardError; end
3
4 def initialize(source:, destination:, amount:)
5 @source = source
6 @destination = destination
7 @amount = amount
8 end
9
10 def call
11 ActiveRecord::Base.transaction do
12 @source.lock!
13 @destination.lock!
14
15 raise InsufficientFundsError if @source.balance < @amount
16
17 @source.update!(balance: @source.balance - @amount)
18 @destination.update!(balance: @destination.balance + @amount)
19
20 transfer = Transfer.create!(
21 source_account: @source,
22 destination_account: @destination,
23 amount: @amount,
24 status: :completed
25 )
26
27 LedgerEntry.create!(account: @source, transfer: transfer, change: -@amount)
28 LedgerEntry.create!(account: @destination, transfer: transfer, change: @amount)
29
30 transfer
31 end
32 rescue InsufficientFundsError
33 errors << "Source account has insufficient funds"
34 false
35 rescue ActiveRecord::RecordInvalid => e
36 errors << e.record.errors.full_messages.to_sentence
37 false
38 end
39
40 def errors
41 @errors ||= []
42 end
43end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Wrapping mutations in a transaction guarantees that a partial failure rolls everything back.
- 2Pessimistic row locks serialize concurrent transfers so two requests can't double-spend the same balance.
- 3Rescuing specific exceptions lets a service return a clean false-or-result instead of leaking raw errors.
Related explainers
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/atomic-money-transfers-with-rails-transactions-explained-ruby-3aee/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.