data-integrity — скилл для Claude Code: что делает и как установить
Скилл data-integrity для Claude Code помогает писать безопасные при параллельных запросах операции с базой данных. Он подключается к задачам с платежами, остатками, статусами и уникальными записями.
MIT ★ 62 обновлён 2026-11-14
npx skills add globalmpc/backendskills --skill data-integrity -a claude-codeЧто делает data-integrity
data-integrity задаёт правила для кода, который меняет данные, пока запросы, повторы или фоновые задачи могут выполняться одновременно. Он охватывает условные обновления и транзакции, ограничения UNIQUE и CHECK, порядок блокировки строк, ключи идемпотентности и обработку повторных или запоздавших событий.
В примерах используются TypeScript и pg, а SQL написан для Postgres. Для MySQL приведены соответствия on conflict и пояснение, как получить строку после изменения в транзакции. Внешние сервисы нельзя вызывать внутри транзакции: пока идёт запрос к платёжному провайдеру или почте, транзакция удерживает блокировки строк и соединение из пула.
Скилл предлагает проверять конкурентные сценарии параллельными запросами через Promise.all и смотреть на итоговые данные. Команды транзакций можно заменить помощником репозитория; клиентам платежей и почты нужен аргумент idempotencyKey.
Какие задачи решает
- защитить остатки и балансы от отрицательных значений
- не создавать повторные записи при одновременных запросах
- задавать единый порядок блокировки строк
- не допускать повторного списания при повторах
- проверять запись в базу параллельными запросами
Примеры запросов агенту
- Проверь обработчик бронирования мест на гонки при одновременных запросах.
- Добавь защиту от повторного списания при повторах запроса к платёжному провайдеру.
- Проверь, что два параллельных запроса не создают участнику две записи в команде.
Как установить data-integrity
1Через Skills CLI (Vercel)
npx skills add globalmpc/backendskills --skill data-integrity -a claude-code2Вручную: положить файлы
~/.claude/skills/data-integrity/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/data-integrity/
1Через Skills CLI (Vercel)
npx skills add globalmpc/backendskills --skill data-integrity -a codex2Вручную: положить файлы
.agents/skills/data-integrity/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add globalmpc/backendskills --skill data-integrity -a cursor2Вручную: положить файлы
.cursor/skills/data-integrity/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install globalmpc/backendskills skills/data-integrity2Вручную: положить файлы
.github/skills/data-integrity/SKILL.md1Через Skills CLI (Vercel)
npx skills add globalmpc/backendskills --skill data-integrity -a gemini-cli2Командой платформы
gemini skills install https://github.com/globalmpc/backendskills --path skills/data-integrityВручную: положить файлы
.devin/skills/data-integrity/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Claude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Вопросы о data-integrity
Как установить data-integrity в Claude Code?
Выполни npx skills add globalmpc/backendskills --skill data-integrity -a claude-code. Файл скилла находится в ~/.claude/skills/data-integrity/SKILL.md.
Что делает data-integrity?
Скилл описывает, как защищать записи в базе от гонок, повторов и конфликтов при параллельной работе запросов и фоновых задач. Отдельные правила касаются транзакций, уникальности, блокировок и ключей идемпотентности.
Какие примеры базы данных есть в data-integrity?
Примеры кода написаны на TypeScript с pg, а SQL — для Postgres. Для MySQL приведены соответствия синтаксису on conflict.
Исходный текст
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