pattern/transactions/idempotency
- Bun
- ElysiaJS
- PostgreSQL
- TypeScript
- node-postgres
- Docker
A mesma requisição repetida tem um só efeito: chave, efeito e resposta gravados juntos; retentativas recebem a resposta gravada.
pattern/transactions/idempotency
Cenário
PIX de R$ 150,00 com resposta perdida e dois reenvios: um só débito. Um segundo PIX chega em três cópias simultâneas: também um só débito.
Planta
Sequência7 passos — reproduza para seguir o fluxo
Como funciona
4passos
A mesma requisição repetida tem um só efeito: chave, efeito e resposta gravados juntos
Esconde cada passo: lembre antes de tocar para revelar.
Idempotency-Key UUID obrigatória, uma por operação
A chave primária deixa só uma requisição inserir, mesmo simultâneas
Quem insere debita e grava PIX e resposta na mesma transação
As demais recebem a resposta gravada; corpo diferente com a mesma chave → 422
Trade-offs
O que se ganha, o que se paga
Vantagens
Retentativa sem débito duplo
Concorrência resolvida pela PK
Custos
Uma escrita a mais por chamada
Chaves exigem expiração
Código
pattern/transactions/idempotency
7 arquivos./
sql/
src/
Executar com Docker
./docker.shuntil docker exec idempotency-db pg_isready -h 127.0.0.1 -U postgres >/dev/null 2>&1; do sleep 1; donebun install# dependênciasbun run demo# roda o cenáriodocker rm -f idempotency-dbSaída: tentativa 1 responde 201 com saldo 85000; tentativas 2 e 3 respondem 201 (replay) com a mesma resposta; das 3 cópias simultâneas, 1 executa e 2 viram replay ou 409; a conta fecha em R$ 700.00 com 2 transferências.
Código
src/demo.ts// Demo: the PIX response is lost and the app retries with the same Idempotency-Key; the account is debited once.
import { Elysia, t } from "elysia";
import pg from "pg";
const pool = new pg.Pool({ connectionString: Bun.env.IDEMPOTENCY_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/idempotency_db" });
const requestHash = (body: unknown) => new Bun.CryptoHasher("sha256").update(JSON.stringify(body)).digest("hex");
// Debit, transfer and the stored response commit in one transaction: there is never an effect without its answer.
async function pixTransfer(key: string, body: { accountId: string; pixKey: string; amountCents: number }) {
const client = await pool.connect();
try {
await client.query("BEGIN");
const { rows: [account] } = await client.query<{ balance_cents: string }>("UPDATE accounts SET balance_cents = balance_cents - $2 WHERE id = $1 RETURNING balance_cents", [body.accountId, body.amountCents]);
await client.query("INSERT INTO pix_transfers (account_id, pix_key, amount_cents) VALUES ($1, $2, $3)", [body.accountId, body.pixKey, body.amountCents]);
const response = { amountCents: body.amountCents, balanceCents: Number(account!.balance_cents) };
await client.query("UPDATE idempotency_keys SET response_status = 201, response_body = $2 WHERE key = $1", [key, response]);
await client.query("COMMIT");
return response;
} catch (error) {
await client.query("ROLLBACK");
// Technical failure: nothing committed, so the key is released and the retry runs for real.
await pool.query("DELETE FROM idempotency_keys WHERE key = $1", [key]);
throw error;
} finally {
client.release();
}
}
const app = new Elysia().post(
"/pix",
async ({ headers, body, set, status }) => {
const key = headers["idempotency-key"];
// Only one request can insert the key; the primary key settles concurrent copies too.
const { rowCount } = await pool.query("INSERT INTO idempotency_keys (key, request_hash) VALUES ($1, $2) ON CONFLICT DO NOTHING", [key, requestHash(body)]);
if (rowCount === 1) return status(201, await pixTransfer(key, body));
const { rows: [stored] } = await pool.query<{ request_hash: string; response_status: number | null; response_body: unknown }>("SELECT request_hash, response_status, response_body FROM idempotency_keys WHERE key = $1", [key]);
if (stored!.request_hash !== requestHash(body)) return status(422, { error: "idempotency.key.reused" });
if (stored!.response_status === null) return status(409, { error: "idempotency.request.in-progress" });
set.headers["x-idempotent-replay"] = "true";
return status(201, stored!.response_body);
},
// The key is born in the client, one per operation intent.
{ headers: t.Object({ "idempotency-key": t.String({ format: "uuid" }) }), body: t.Object({ accountId: t.String(), pixKey: t.String(), amountCents: t.Integer({ minimum: 1 }) }) },
);
const { rows: [account] } = await pool.query<{ id: string }>("INSERT INTO accounts (owner_name, balance_cents) VALUES ('Ana Lima', 100000) RETURNING id");
const transfer = JSON.stringify({ accountId: account!.id, pixKey: "maria@bank.com", amountCents: 15_000 });
const pixPost = (key: string) => app.handle(new Request("http://localhost/pix", { method: "POST", headers: { "content-type": "application/json", "idempotency-key": key }, body: transfer }));
const key = crypto.randomUUID();
for (let attempt = 1; attempt <= 3; attempt++) {
const response = await pixPost(key);
console.log(` [ATTEMPT ${attempt}] ${response.status}${response.headers.get("x-idempotent-replay") ? " (replay)" : ""} ${await response.text()}`);
}
// Three copies of a second PIX at once: the primary key lets one insert; the others replay or get 409 while it runs.
const keyBurst = crypto.randomUUID();
const burst = await Promise.all([1, 2, 3].map(() => pixPost(keyBurst)));
const executed = burst.filter((response) => response.status === 201 && !response.headers.get("x-idempotent-replay")).length;
console.log(` [CONCURRENT] 3 simultaneous copies: ${executed} executed, ${burst.length - executed} replayed or refused with 409`);
const { rows: [after] } = await pool.query<{ balance_cents: string; transfers: string }>("SELECT balance_cents, (SELECT count(*) FROM pix_transfers WHERE account_id = $1) AS transfers FROM accounts WHERE id = $1", [account!.id]);
console.log(` [ACCOUNT] balance R$ ${(Number(after!.balance_cents) / 100).toFixed(2)}, ${after!.transfers} transfers: each PIX debited once`);
await pool.end();
Nível
intermediário
6/13
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
PostgreSQLbanco relacional
postgres:16-alpine:5432
Banco
sql/01_schema.sql
Variáveis de ambiente
Trilhapasso 1 de 7
Consistência sem transação distribuída
Parecidos
Relações
Onde ele se encaixa
Por que se relacionam
Próximo passo
Teste rápido
Qual é o próximo passo depois de Idempotency?
Compensa passos em vez de travar. Abrir Saga — Coreografia
Seu progresso
0/157 estudados
Fica salvo só neste navegador.