/ratchet-backend:postgres-lockingfrom ratchet-backend
Use when writing or reviewing PostgreSQL code that takes a row lock (FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE, FOR KEY SHARE), LOCK TABLE, or an advisory lock, serializes concurrent writers, answers a race-condition finding, or enforces a cap, limit, or last-one guard under concurrency. Decides when code may lock and what to use instead.
Ships in ratchet-backend. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Read every applicable AGENTS.md first. Repository-local policy overrides these defaults.
Most writes need no lock: a comment, a like, a vote, a follow, a profile edit. Each lock adds
waiting, deadlock risk, and a reason for the next reader to keep it, and one held too long stalls
every writer queued behind it. By default take none: add one only for a reason under "When a
lock is allowed", and record that reason beside it. When more than one mechanism is correct,
pick the simplest, by the ladder
in postgres-schema-design, which also owns table design.
FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE, FOR KEY SHARE, LOCK TABLE, an advisory lock,
and any helper function that wraps one of them. A share lock is a lock: it blocks writers and
two holders that go on to update deadlock. A foreign key already takes the key-share lock it
needs; do not add one beside it.
ON CONFLICT DO NOTHING. Serializing the writers is not the fix.UPDATE ... WHERE id = $1 AND EXISTS (<guard>) reads the guard and the target in one snapshot.
Do not lock the guarded row first, in a separate statement or in a CTE. A guard on another row
can still change the moment after; that is best effort, and only the reasons under "When a
lock is allowed" justify more.UPDATE ... WHERE state = 'open'
and INSERT ... ON CONFLICT already decide atomically. Delete the SELECT ... FOR UPDATE that
precedes one, and read the row count to learn who won. Do not lock a row to read its prior
value either: RETURNING old.col (PostgreSQL 18) returns it from the write.LIMIT cap + 1), then write. Concurrent requests that all count before any of them commits may each land a row over; say so
and accept it. When asked to make a cap exact, answer with this design. Do not add a lock, a counter or
projection table, a slot or claim table, a constraint that exists only to make the cap exact, or a SERIALIZABLE transaction.SERIALIZABLE transaction whose 40001 is returned
as 409 with no retry. The guard's read and the write it decides run inside that transaction; a
read made before it protects nothing. A scheduled job leaves the work to its next run.postgres-schema-design): no caller can see the order those locks are taken in. Compute each
closed period once, with a scheduled job or a materialized view, and read the open period from
the source rows.Only for these three reasons. Anywhere else, never lock a read set or a parent row to serialize writers, and never close a race with a wider lock. A cap or a last-one guard fits none of them.
SERIALIZABLE, such as many people reordering one shared list. Lock the
shared root row so the writers queue for a moment, and make every writer of those rows take the
same lock. Run the transaction at READ COMMITTED: under SERIALIZABLE or REPEATABLE READ
the snapshot is taken at the lock statement, so a writer that waited still reads the old rows
and fails with 40001.FOR SHARE for the side that only needs the row
to stay put, FOR NO KEY UPDATE taken first by a transaction that will also update it.UPDATE or DELETE ... WHERE <condition re-checked>), a unique constraint with ON CONFLICT, or SERIALIZABLE. The usual
case is an exact quantity (money, a balance, inventory) whose rule spans rows; for one row,
UPDATE stock SET qty = qty - $1 WHERE sku = $2 AND qty >= $1 or a constraint is enough. Then
lock the rows the transaction writes, or their parent.An advisory lock is for those cases only when no row exists to lock, or when the critical section
must span transactions or outside I/O. That second case alone takes a session-level lock: hold it
on a client reserved for it from its own small pool, never one that returns to the request pool
or sits behind a transaction-mode pooler, and release it in a finally. Otherwise avoid them.
Beside every lock, including an advisory one, a comment starting lock-reason: names the
outcome the lock prevents and the writers it keeps apart. A test forces that interleaving and
fails without the lock (see "Tests"). A lock with no recorded reason, often one copied along with
shared code or a helper, is deleted, or its reason is found and recorded.
// lock-reason: concurrent drags fail with 409; moveTrack vs moveTrack, addTrack, removeTrack
await tx.query('SELECT 1 FROM playlists WHERE id = $1 FOR NO KEY UPDATE', [playlistId])
NOWAIT or lock_timeout in a request path, returning 409; a lock
for user experience uses lock_timeout, since NOWAIT returns the 409s it exists to avoid. For
an advisory lock use pg_try_advisory_xact_lock (pg_try_advisory_lock for the session-level
case above) or lock_timeout; the blocking form holds a pooled connection while it waits.hashtext(org_id)
alone is shared by every other lock keyed on the same id; use the two-key form with a namespace
for the operation.SKIP LOCKED is only for competing workers that select rows they then write in the same
transaction. When the queue already runs the job single-flight (an ordering lane, a job id), it
is not needed. A sweep that deletes or updates the rows it found is not a claim: it locks
neither its candidates nor its cursor row (bounded-iteration).SERIALIZABLE transaction may be.Adding a lock is the repository owner's decision.
SERIALIZABLE with 409 do
not fit. A review of a lock asks for whatever is missing.ratchet-workflows:change-review): name the two writers, trace what each writes,
and show they can run at the same time. If the race cannot happen, reply with the reason. If you
cannot tell, reply that it is unverified. Change nothing in either case. Answer only a verified
race, in this order: a constraint; a conditional write; a guard inside the writing statement;
SERIALIZABLE with 409 when the outcome is unacceptable; otherwise "accepted: best effort", with
the worst case stated. Reply with that reasoning and resolve the thread.The rules above are for runtime code. A test is free to try to break the locking: it may take a lock itself, hold a row, or wait until other backends are blocked, to force the interleaving it wants to check. Do not report that as a locking defect.
Do not assert that a lock was taken, the order locks were taken in, or an exact cap under concurrency. Those tests force the lock back in when someone removes it. Assert the final state under the interleaving: no negative balance, no duplicate effect, one winner, or, for a lock taken for user experience, every writer succeeding. That test fails without the lock, which is what keeps it. Where a race has more than one valid outcome, accept each of them.
What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
npx claudepluginhub jongleberry/ratchet-stack --plugin ratchet-backend18 skills in this plugin
/bounded-iterationUse when writing or reviewing a sweep, scheduled job, reconciler, cleanup, dispatcher, backfill, or export - any loop that reads rows. Covers bounding the rows each run reads, sweeps that re-select their own writes, and effects that repeat on every run./error-handlingUse when writing or reviewing code that throws, catches, or matches an error, turns a failure into a response, or reports errors to a tracker such as Sentry, including a review of a diff that does. Covers one defined list of error codes, matching on type or code instead of message, details as attributes on the error, and reporting only errors someone can act on./event-handlersUse when writing or reviewing code that acts on an event or a state change - a serverless function, a queue consumer, a scheduled task, or a deploy or config hook - and above all one that sleeps or waits before it acts. React to the change instead of waiting a fixed time, de-duplicate by reading current state, and defer work the target is not ready for without losing it./expand-contract-migrationsUse when renaming or dropping a column or table, changing a column type, making a column NOT NULL, renaming an API or event field, splitting or merging tables, or changing a config shape that running code reads. Change a shape in separate deploys so old and new code never disagree./feature-rolloutUse when adding or reviewing a feature flag, a flag's default, rollout or rollback steps, or a change that adds a table, migration, service, or write path. Ship new behavior behind a flag that starts off, treat deploying and enabling as separate steps, and add no table or service that no entry point reaches./glide-mqUse when writing or reviewing a queue producer, worker, dispatcher, scheduler, or flow, choosing which queue or lane a job belongs in, deciding what a job payload carries, or handling a request that waits on a job's result. Design glide-mq queues, jobs, lanes, concurrency, rate limits, and replay safety.