data-integrity — Claude Code skill: what it does, how to install
data-integrity is a Claude Code skill for database writes that may overlap or be retried. It applies to work involving payments, inventory, balances, status changes, and unique records.
MIT ★ 62 updated 2026-11-14
npx skills add globalmpc/backendskills --skill data-integrity -a claude-codeWhat data-integrity does
data-integrity sets out safeguards for writes that can run at the same time in requests, retries, or background jobs. Its rules cover conditional updates and transactions, UNIQUE and CHECK constraints, consistent row-lock order, idempotency keys, and duplicate or out-of-order events.
The examples use TypeScript with pg, and the SQL targets Postgres. MySQL equivalents for on conflict are included, along with guidance on reading a changed row within the same transaction. Calls to payment or email services stay outside transactions; while those calls wait, the transaction holds row locks and a pool connection.
The skill suggests testing concurrent writes with Promise.all and checking the resulting state. A repository transaction helper can replace the shown transaction commands. Payment and email clients need to accept an idempotencyKey argument.
What it helps with
- prevent stock and balances from dropping below zero
- stop simultaneous requests from creating duplicate rows
- lock rows in a consistent order
- avoid duplicate charges after retries
- test database writes under concurrent requests
Example prompts for the agent
- Check this booking handler for races when requests arrive together.
- Add protection against charging twice if a payment request is retried.
- Verify that parallel requests cannot add the same user to a team twice.
How to install data-integrity
1Skills CLI (Vercel)
npx skills add globalmpc/backendskills --skill data-integrity -a claude-code2Manually: put the files in place
~/.claude/skills/data-integrity/SKILL.mdCopy the whole skill folder; for one project use .claude/skills/data-integrity/
1Skills CLI (Vercel)
npx skills add globalmpc/backendskills --skill data-integrity -a codex2Manually: put the files in place
.agents/skills/data-integrity/SKILL.mdFor all projects use ~/.agents/skills/
1Skills CLI (Vercel)
npx skills add globalmpc/backendskills --skill data-integrity -a cursor2Manually: put the files in place
.cursor/skills/data-integrity/SKILL.mdCursor also reads .agents/skills/ and .claude/skills/
1GitHub CLI
gh skill install globalmpc/backendskills skills/data-integrity2Manually: put the files in place
.github/skills/data-integrity/SKILL.md1Skills CLI (Vercel)
npx skills add globalmpc/backendskills --skill data-integrity -a gemini-cli2Platform CLI
gemini skills install https://github.com/globalmpc/backendskills --path skills/data-integrityManually: put the files in place
.devin/skills/data-integrity/SKILL.mdThe legacy .windsurf/skills/ path still works
Claude.ai
Zip the folder and upload it in Settings → Capabilities → Skills
Step by step, with commands for each platform: How to install skills in Claude Code: five ways
Questions about data-integrity
How do I install data-integrity in Claude Code?
Run npx skills add globalmpc/backendskills --skill data-integrity -a claude-code. The skill file is at ~/.claude/skills/data-integrity/SKILL.md.
What does data-integrity do?
It describes safeguards for database writes exposed to concurrency, retries, and background jobs. The rules address transactions, uniqueness, row locks, and idempotency.
Which database examples does data-integrity include?
The code examples use TypeScript with pg, and the SQL is for Postgres. The skill also gives MySQL equivalents for on conflict.
Source text
SKILL.md · MIT
---
name: data-integrity
description: Rules for code that writes to the database where two requests, retries or jobs can run at once. Use for anything that changes money, stock, balances, counters or statuses, creates rows that must be unique, or calls a payment provider, email or other outside service. Applies in endpoints, webhooks and background jobs.
---
# Data integrity
Examples are TypeScript with `pg`. The rules apply to any stack. Assume every write can run twice at the
same time: two clicks, a client retry, two servers picking up the same job.
The SQL is Postgres. On MySQL, `on conflict ... do update` is `on duplicate key update`, and `on conflict
do nothing` is `on duplicate key update id = id` (0 affected rows: the row was there; not `insert ignore`,
which hides other errors too). There's no `returning`: read the row back in the same transaction.
`id = any($1)` is `id in (...)`.
## 1. Read-then-write is one conditional statement, or one transaction with a lock
Why: two requests at once both read "1 seat left", both book it. Counts go negative and money gets created.
```ts
// Bad: check and write are separate; a concurrent request slips in between
const { rows: [e] } = await pool.query("select seats_left from events where id = $1", [id]);
if (e.seats_left < seats) return sendError(res, 409, "sold_out", "Not enough seats");
await pool.query("update events set seats_left = seats_left - $1 where id = $2", [seats, id]);
// Good: the check is part of the write
const { rowCount } = await client.query(
"update events set seats_left = seats_left - $1 where id = $2 and seats_left >= $1", [seats, id]);
if (rowCount === 0) throw new HttpError(409, "sold_out", "Not enough seats");
```
When several rows must change together (every line of a booking, both accounts in a payment), do it in one
transaction. Put a database CHECK behind it (`seats_left >= 0`, `balance_cents >= 0`) as the last line of
defence.
## 2. Uniqueness is a UNIQUE constraint, not a check before the insert
Why: two requests both find "no row yet" and both insert. You get two accounts per email or two reviews
per user.
```ts
// Bad: a concurrent request inserts between the select and the insert
const { rows } = await pool.query("select 1 from memberships where team_id = $1 and user_id = $2", [team, user]);
if (rows.length) return sendError(res, 409, "already_member", "Already a member");
await pool.query("insert into memberships (team_id, user_id) values ($1, $2)", [team, user]);
// Good: unique (team_id, user_id) in the schema; the database decides who was first
const { rowCount } = await pool.query(
"insert into memberships (team_id, user_id) values ($1, $2) on conflict do nothing", [team, user]);
if (rowCount === 0) return sendError(res, 409, "already_member", "Already a member");
```
## 3. Lock rows in a fixed order
Why: request A locks row 1 then row 2 while request B locks 2 then 1, and Postgres kills one of them with a
deadlock. Two payments between the same two accounts, in opposite directions, are enough to cause it.
```ts
// Bad: lock order follows the request (payer first, lines in the order given)
for (const id of [payerId, payeeId]) await client.query("select ... where id = $1 for update", [id]);
// Good: always lowest id first, in one statement
await client.query("select id, balance_cents from accounts where id = any($1) order by id for update",
[[payerId, payeeId]]);
```
## 4. Never call an outside service inside a transaction
Why: the payment provider, HTTP, email all take tens of milliseconds to seconds. During that wait the
transaction holds its row locks and a pool connection. Under load every connection is held and the app
hangs. This is worse still if the client library uses the same pool.
```ts
// Bad: charge while the seat rows are locked
await client.query("begin");
await holdSeats(client, seats);
const { paymentId } = await payments.charge({ amountCents: total });
await client.query("commit");
// Good: short write, call, short write
const bookingId = await tx(async (c) => { await holdSeats(c, seats); return createBooking(c, "pending"); });
let paymentId: string;
try {
({ paymentId } = await payments.charge({ amountCents: total, idempotencyKey: `booking-${bookingId}` }));
} catch (err) {
// No confirmed charge: give the seats back. If it went through after all (a timeout), the provider's
// charge.succeeded webhook finds a failed booking and refunds it (rule 5).
await tx(async (c) => { await releaseSeats(c, seats); await markBooking(c, bookingId, "failed"); });
return sendError(res, 502, "payment_failed", "Payment failed");
}
// Outside the try: the customer has paid, so a database error here must never release the seats.
// The booking stays pending and the webhook marks it paid.
await pool.query("update bookings set status = 'paid', payment_id = $2 where id = $1 and status = 'pending'",
[bookingId, paymentId]);
```
## 5. Anything that charges, refunds or sends gets an idempotency key
Why: a retry (by the client, a proxy, or your own code after a timeout) charges the customer twice.
- Pass a key derived from your own record (`booking-<id>`, `refund-<bookingId>`), not a random one per attempt.
- Change state only from the state you expect (`update bookings set status = 'cancelled' where id = $1 and
status = 'paid'`), and act only if a row changed. Two cancellations at once must not both refund.
- Events can arrive twice or out of order (webhooks, queue messages). Handling one must not move a record
back to an earlier state. A `charge.succeeded` for a booking you already marked failed means a refund,
not a revived booking.
## 6. Test it with requests at once
Why: every bug above passes a test that sends one request at a time.
Send the same write 10–20 times in parallel (`Promise.all`) and check the end state: counts never below 0,
money neither created nor lost, one charge per order, no deadlock errors.
## Make it yours
Your team's choices. Until you change a line, it's the default.
- **Transactions:** `pool.connect()` + `begin`/`commit`/`rollback`, or the repo's transaction helper if it has one.
- **Payment and email clients:** take an `idempotencyKey` argument; check the client in the repo for its name.
© globalmpc · MIT · globalmpc/backendskills