Skip to content

Lock scope records without instantiating them - #75

Merged
brendon merged 2 commits into
mainfrom
perf/lock-without-loading-records
Nov 27, 2026
Merged

brendon merged 2 commits into
mainfrom
perf/lock-without-loading-records

Conversation

@brendon

@brendon brendon commented Oct 16, 2026 •

Copy link
Copy Markdown
Owner

When a list has no parent row to lock, positioning locks every row in the list instead. That covers a model with no scope, a scope on plain columns, and (since #76) a list whose belongs_to parent is nil, such as the roots of a tree. It did this with scope_of(record).lock.all.load, which runs SELECT * … FOR UPDATE and builds an Active Record object for every row in the list on every create, update and destroy. For a model with no scope, that's every row in the table. Only the row locks are needed.

Fix

lock_scope_of now locks those rows with scope_of(record).reorder(primary_key).lock.ids, which runs SELECT id … ORDER BY id FOR UPDATE. The same rows are locked, but only their ids are fetched, so no records are built. For a composite primary key, primary_key is an array, and reorder orders by each of its columns: Active Record 7.2 and 8.1 both flatten its arguments.

The ordering is there because plain lock.ids deadlocks more often on MySQL:

  • For a model with no scope, MySQL answers plain lock.ids from the position index, and the moves test below raised ActiveRecord::Deadlocked in each of three runs. Ordering by id makes MySQL read the primary key instead.
  • For a scope on a plain column with only a [scope, position] unique index, MySQL reads that index either way, and sorts the ids afterwards when they're ordered. Plain lock.ids still deadlocked more often there (table below). I don't know why the sort makes the difference.

Measurements

MySQL 9.7.4 and PostgreSQL 18, locally.

Which index MySQL reads to take the locks, from EXPLAIN:

List main This PR
No scope (Product) whole table, then sorts by position primary key
Tree roots (Category, parent_id IS NULL) [parent_id, position] index parent_id index
Plain column scope, only a [scope, position] unique index [scope, position] index [scope, position] index, then sorts by id

Deadlocks on MySQL, moving 10 records in one list to position 1, four at a time, 30 moves per run, three runs:

List main This PR Plain lock.ids
Plain column scope, only a [scope, position] unique index 3, 2, 3 3, 2, 3 5, 10, 10
Tree roots 0, 0, 0 0, 0, 0 not run

Positions were correct after every run. Creating 21 tree roots, five at a time (the probe from #76), gave no deadlocks and no duplicate positions on either main or this PR.

Time to take the lock, in its own transaction, for Product (no scope), averaged over 30 runs:

Rows main, MySQL This PR, MySQL main, PostgreSQL This PR, PostgreSQL
1,000 4.0 ms 2.1 ms 7.6 ms 5.2 ms
10,000 27.0 ms 9.2 ms 31.4 ms 9.0 ms

Considered and dropped

  • Fetching nothing. Selecting 1 instead of the id, or counting the rows of a locking subquery, took about the same time as fetching ids: 9 to 10 ms for 10,000 rows on both databases. Nearly all of the time is the database finding and locking each row.
  • Locking the whole table. LOCK TABLE … IN SHARE ROW EXCLUSIVE MODE took 0.5 ms on PostgreSQL at any size. But it's database-specific, and it blocks every insert, update and delete on the table, for every list, until the transaction ends. MySQL's LOCK TABLES commits the open transaction, so it can't be used inside one.

Who this changes things for

Only lists with no parent row to lock. The same rows are locked; they're no longer loaded. Which index MySQL reads depends on its optimizer and the app's indexes, and I've only measured MySQL 9.7.4.

Tests

  • Locking a scope of three products builds no records. With main's lock.all.load, it builds 3.
  • Locking with a composite primary key orders by both of its columns. This uses a composite primary key item with no list, so it takes the same branch. Nothing ran this query with a composite primary key before. Without the ordering, or with reorder(:id), the test fails.
  • 10 products moved to position 1, four at a time, end up at positions 1 to 10. This passes on main too. It guards against the deadlock above: with plain lock.ids instead, it raised ActiveRecord::Deadlocked on MySQL in each of three runs.

Changelog: When a scope has no belongs_to association, lock the records in it without loading them. Before, every create, update and destroy loaded every record in the scope (for a model with no scope, every record in the table) just to lock them.

🤖 Generated with Claude Code

@brendon
brendon marked this pull request as draft November 9, 2026 02:29
@brendon brendon added the concurrency Locking, isolation and race conditions label Nov 9, 2026
@brendon
brendon force-pushed the perf/lock-without-loading-records branch 2 times, most recently from eca96d3 to 4425cbb Compare November 20, 2026 00:42
When a scope has no belongs_to association, its rows were locked with
lock.all.load, which builds an Active Record object for every row in
the scope on every create, update and destroy. For a model with no
scope, that's the whole table. Only the row locks are needed.

They're now locked with reorder(primary_key).lock.ids. Ordering by
primary key matters on MySQL. With plain lock.ids, MySQL can answer
the query from the (scope, position) index, so a transaction waiting
for the lock waits inside that index. InnoDB then stops our own
UPDATEs from writing position values into the gap it's waiting on, and
the two transactions deadlock. Ordering by primary key keeps those
waits on the primary key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@brendon
brendon force-pushed the perf/lock-without-loading-records branch from 4425cbb to 38436f2 Compare November 27, 2026 09:59
Active Record flattens the arguments to reorder in 7.2 and 8.1, so
reorder(primary_key) gives the same SQL as reorder(*Array(primary_key))
for single and composite primary keys.

Nothing ran this lock query with a composite primary key, so add a test
that does, with a composite primary key item whose list is nil.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@brendon
brendon marked this pull request as ready for review November 27, 2026 22:54
@brendon
brendon merged commit ba0a0d7 into main Nov 27, 2026
27 checks passed
brendon added a commit that referenced this pull request Nov 28, 2026
When a scope has no belongs_to association, or its parent is nil, the
healer locks the scope's records with plain lock.ids. On MySQL, that
deadlocks more often against saves to the same list than ordering the
lock by primary key, which #75 does for positioning's own lock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
brendon added a commit that referenced this pull request Nov 28, 2026
When a scope has no belongs_to association, or its parent is nil, the
healer locks the scope's records with plain lock.ids. On MySQL, that
deadlocks more often against saves to the same list than ordering the
lock by primary key, which #75 does for positioning's own lock.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

concurrency Locking, isolation and race conditions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant