Skip to content

Serialize lock_and_write when creating a missing entry - #325

Open
seuros wants to merge 2 commits into
rails:mainfrom
seuros:fix-lock-and-write-race
Open

seuros wants to merge 2 commits into
rails:mainfrom
seuros:fix-lock-and-write-race

Conversation

@seuros

@seuros seuros commented Oct 30, 2026 •

Copy link
Copy Markdown
Member

Locking a missing row locks nothing on PostgreSQL and only a gap on MySQL, so concurrent increments or unless_exist writes creating the same key both saw nil. On PostgreSQL the second upsert overwrote the first and an increment was lost; on MySQL the two gap locks deadlocked and the failsafe returned nil.

When the locked read finds no row, that transaction now ends, which also releases MySQL's gap lock. A second transaction inserts a placeholder, skipping on conflict, then locks the row. A concurrent creator waits on the unique index and computes from the committed value. If the block writes nothing, the placeholder is deleted. Existing rows keep the single transaction path.

PS: we should probably drop 7.2 support .

Locking a missing row locks nothing on PostgreSQL and only a gap on MySQL,
so concurrent increments or unless_exist writes creating the same key both
saw nil. On PostgreSQL the second upsert overwrote the first and an
increment was lost; on MySQL the two gap locks deadlocked and the failsafe
returned nil.

When the locked read finds no row, that transaction now ends, which also
releases MySQL's gap lock. A second transaction inserts a placeholder,
skipping on conflict, then locks the row. A concurrent creator waits on
the unique index and computes from the committed value. If the block
writes nothing, the placeholder is deleted. Existing rows keep the single
transaction path.
Before Rails 8, SQLite transactions are deferred, so a writer that waited on another raises BusyException instead of retrying. The unpatched lock_and_write fails the same way there.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant