Understanding Rails · Season 3: Active Record in depth
Transactions and locking
Episode 24 · deep dive · about 5 minutes · Rails 8.1 · by Tommy A. Caruso
How was this episode?
The series' author reads every note, and no one else sees it. When something is wrong or unclear, it gets fixed and the episode re-cut. How this series stays right.
Not endorsed yet. Are you a Rails developer? What's an endorsement?
Endorse this version To endorse: create an account, confirm your email, then link GitHub.
All or nothing, optimistic and pessimistic locks, and race conditions.
Free to watch. If it helped, support the series.
Transcript
0:00 Transactions and locking
Episode twenty four. Transactions and locking. Two problems that only show up when things go wrong: a change that stops halfway, and two people changing the same thing at once. Today: all or nothing, and the locks that keep a change from being lost.
0:20 Half changed
Say we're merging the Home notebook into Ideas. First, move its notes. Then delete the notebook. If something fails between those two steps, the notes have moved, but the notebook is still there. The data is half changed.
0:35 A transaction rolls back
Wrap both steps in a transaction. Begin, move the notes, and then something raises: disk full. Rails rolls the transaction back. The log says begin, the update, then rollback. The error still comes back to you, and nothing changed: Home still has its two notes, and it still exists.
0:54 All or nothing
When the block finishes without an error, Rails commits, and every change lands together. That's the whole idea. All of it, or none of it. And you've been using this all along: every save runs inside a transaction of its own, as episode twenty two showed.
1:11 ActiveRecord::Rollback
To undo a transaction on purpose, without an error, raise active record rollback. The update runs, then rolls back. The transaction block quietly returns nil, and the notebook is still called Home. That rollback error never leaves the block.
1:28 Nested transactions
Now the surprise. Put one transaction inside another, and raise rollback in the inner one. Both renames are committed. There's only one real transaction here, and the inner block just joins it. So the rollback ends the inner block, and nothing is undone.
1:46 requires_new
Pass requires new true to the inner one, and Rails makes a save point. Now the rollback goes back to that save point, and only the inner change is undone. The notebook stays renamed. Ideas keeps its name.
2:00 Last write wins
The second problem is a race. Two people open the same note. One saves milk and eggs. The other, who loaded the note before that, saves oat milk. Last write wins. The first change is gone, and nobody was told.
2:15 Optimistic locking
Optimistic locking catches it. Add a lock version column, an integer with a default of zero, and Rails does the rest. Each update adds one to it, and only matches the row if the version is still the one you loaded.
2:30 StaleObjectError
Watch the second update. It asks for version zero, but the note is now at version one, so no row matches. Rails raises stale object error, and the first change survives.
2:43 lock_version in a form
For a form, the version has to make the round trip. Add lock version as a hidden field, and permit it. In the update action, rescue the stale object error, add a message, and render the form again with the status conflict, four oh nine. The person sees that someone else changed the note, instead of losing work without knowing it.
3:04 Counters race
Counters race too. Load the same notebook twice, and add one to notes count on each copy. Two increments, but the count only went up by one, because each copy wrote back the number it had read.
3:17 Let the database count
So let the database do the arithmetic. Increment with a bang, and update counters, both write one statement: set notes count to notes count plus one. There's nothing to read first, so there's nothing to race.
3:32 Pessimistic locking
Pessimistic locking takes the other approach: lock the row before you change it, so the next person waits. With lock, Rails adds for update to the query on PostgreSQL and MySQL. And with lock wraps a block in a transaction, and reloads the record with that lock.
3:50 On SQLite
On SQLite, which this app uses, the query has no for update at all. SQLite doesn't lock rows. Instead, Rails starts each transaction as begin immediate, which takes the write lock for the whole database. Other writers wait their turn, so with lock still keeps changes in order.
4:09 Which lock
Which lock, then? Optimistic when conflicts are rare and a person can retry, like editing a note. Pessimistic when two changes must never overlap, like moving money, and keep the lock short. And for a simple count, let the database do it.
4:26 The rules
So: wrap steps that belong together in a transaction. Know that nested blocks share one, unless you ask for a save point. And pick a lock before two people find the race for you.
4:38 Next
Next: encrypting attributes.
Check your understanding
-
Inside Notebook.transaction, you raise ActiveRecord::Rollback. What happens?
- The changes are undone, and the error reaches your code
- The changes are undone, and the error stays inside the block
- The changes are kept, and the error is logged
Show answer
The changes are undone, and the error stays inside the block. Rollback undoes the transaction without passing the exception on. The block quietly returns nil. Source: ActiveRecord::Rollback (Rails API 8.1).
-
A transaction block sits inside another, and the inner one raises ActiveRecord::Rollback. Nothing else goes wrong. What is committed?
- Nothing
- Only the outer change
- Only the inner change
- Both changes
Show answer
Both changes. The inner block joins the outer transaction, so the rollback ends only the inner block. Pass requires_new: true to get a save point. Source: ActiveRecord::Transactions::ClassMethods (Rails API 8.1).
-
Notes have a lock_version column. Two people load note 1. The first saves. What happens when the second saves?
- It raises ActiveRecord::StaleObjectError, and the first change survives
- It overwrites the first change
- It waits until the first person closes the page
Show answer
It raises ActiveRecord::StaleObjectError, and the first change survives. Each update checks that lock_version is still the one loaded. It isn't, so no row matches and Rails raises. Source: ActiveRecord::Locking::Optimistic (Rails API 8.1).
-
This app uses SQLite. What does Note.lock.find(1) add to the SQL?
- FOR UPDATE
- FOR UPDATE NOWAIT
- LOCK IN SHARE MODE
- Nothing
Show answer
Nothing. SQLite doesn't lock rows, so Rails leaves the lock clause out. Each transaction starts with BEGIN IMMEDIATE instead. Source: Arel SQLite visitor (Rails source, v8.1.4.1).
Sources
Every example in this episode was run on Rails 8.1.4.1 and Ruby 4.0.2.