/ratchet-backend:bounded-iterationfrom ratchet-backend
Use 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.
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.
These rules are for code that runs against production data, including a one-off backfill. A test, a fixture, or a seed on a disposable database may read, delete, or loop over every row.
A run's cost is the rows it reads and the work it starts, not the memory it holds. Read sweep patterns for worked SQL and loop shapes. List endpoints, feeds, and pagination are in list-reads.
OR of unrelated
conditions, and EXISTS as the only condition are not filters. Eligibility belongs in the
WHERE, not in a filter after the read, which pays for rows it then skips.
Base a sweep on updated_at only if the sweep controls all of updated_at's inputs, or doing
the work twice is no harm. A trigger sets updated_at on any update to the row, so every other
writer moves it. A table only for post moderations can be swept by updated_at; posts cannot.
Twice is no harm for an aggregation such as a vote tally, because it makes no external API
calls, needs no locks or transactions and has no potential conflicts, and already runs with
per-entity concurrency. A per-row threshold becomes one bucket per distinct value, comparing the
stored fact with a bound, never with another column; timestamptz + interval is not immutable,
so it cannot be indexed. See per-row
interval and age
milestones.LIMIT.
For writes the LIMIT goes in a CTE. A list read has no candidate cap. A dispatcher whose
output order does not matter may cap the rows it reads, apply eligibility from other tables
outside that cap, and save the last row it consumed as its position (capped read walk).
A sweep takes no locks. Do not lock the candidate rows it selected or its cursor row. Write
a page in one statement that re-checks eligibility on its own target:
DELETE FROM t WHERE id IN (SELECT id FROM t WHERE <eligible> ORDER BY id LIMIT $1) AND <still eligible> RETURNING id. The inner select carries the same eligibility test; a looser one fills
pages with rows the write skips, each run ends on them, and the sweep never gets past them.
A row that stopped being eligible after the read is left alone, and overlapping runs repeat
work at worst. Count the rows it returned: a full page means run again, and a short or empty
page ends the run. A row another writer changed first can end a run early; the next run picks
up the rest. Never read or lock an extra row to learn whether more remains; that is a list's
next-page check (list-reads). Use two statements only when code must
inspect the rows between them, and then the write repeats the test:
DELETE ... WHERE id = ANY($1) AND <still eligible>. Before writing or approving a sweep that
deletes, read what each deleted row sets off: an ON DELETE CASCADE, an AFTER DELETE
trigger, a counter it keeps. Each runs per row inside the statement, so it can lock other rows
or multiply the page; size the page for it, or say why it is safe. When eligibility depends on
another row, such as a hold on the parent, put that guard in the write as well;
postgres-locking says when such a guard needs a lock. FOR UPDATE SKIP LOCKED is only for a
work-item claim, where two workers must not do the same non-idempotent work.
(postgres-locking)(time, id)
position on a time only the database sets and that only moves forward (<verb>_through_at;
see sweep patterns), fix the sweep's end when it starts, and rescan an overlap
when insert order differs from commit order. A run's position belongs to that run: keep it in
the job's data and pass it to the job that continues the run. No two runs then write the same
position, and overlapping runs repeat work at worst. A stored cursor that runs share is only
for a position that must commit in the same transaction as domain rows. It follows
table shapes and advances with a
compare-and-set on the value the batch started from, never an unconditional write, so an
overlapping or stale run cannot move it backward. Asked to guard a shared cursor that does not
need to be shared, move the position into the job's data instead of adding the guard: that
removes the race, and a guard only survives it. A sweep that keeps any persisted cursor says
why a predicate the processed row leaves, as in rule 16, does not work.Promise.all only over a bounded result, with bounded
concurrency.LIMIT 1 and an external API's page maximum are contracts, not tunables.OR of unrelated reasons into one dispatcher per
reason, each with its own index-served predicate, position, and schedule, all enqueuing the same
idempotent job. Writes that cause a signal enqueue directly; the sweep is the backstop. See
one dispatcher per signal.updated_at it selects by, unless that write is a lease; otherwise each run
creates the next run's work and the sweep never ends. Read the table's triggers in the
migrations before judging a sweep, and say what they do instead of asking the author to check.
A write that takes a row out of the selection, such as setting processed_at on rows selected
by processed_at IS NULL, is the point. A recovery sweep should use its own columns: it finds
stalled rows by a column the worker writes, such as a heartbeat, and marks the rows it enqueues
in a column of its own. An event is a per-column field, such as enqueued_at or
completed_at, or a row in a history table (table
shapes). The mark makes the row
ineligible until it stalls again, and no other writer can hide a stalled row. updated_at is
not ruled out where the sweep controls all of its inputs (rule 1). Rule 1's no-harm exception
does not apply here, because another writer can hide a stalled row. Replay only idempotent
"ensure" effects: an on-create effect, such as a notification or a charge, repeats on every
run. Test it: once no eligible rows remain, another run writes nothing and creates no new job
(a repeated idempotent enqueue is not new work). Recurring work that is unconditional by
design, such as a scheduled materialized-view refresh, is exempt.ORDER BY, so the scan stops at the
LIMIT instead of reading and sorting every match. Compare rows read with rows returned.For work-item, lease, and cursor tables, read postgres-schema-design. For query shape and streaming, read performance patterns; for UUIDv7 windows and pruning, UUIDv7 partitioning. A consuming repository owns run caps, tunable names and ceilings, schedules, and enforcement.
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
/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./http-api-designUse when writing or reviewing an endpoint, route handler, service layer, or an edge or CDN worker in front of an API, choosing identifiers in URLs, storing tokens or one-time codes, or setting cache headers. Shape an HTTP API around resources, thin route handlers, user-facing identifiers, and one owner each for secret storage and cache headers.