Pular para o conteúdo

Idempotency

A mesma requisição repetida tem um só efeito: chave, efeito e resposta gravados juntos; retentativas recebem a resposta gravada.

passos
4
arquivos
7
testes
0
tecnologias
6

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ência
7/7
POST /pix (Idempotency-Key K)1INSERT chave K2BEGIN, debita, grava PIX e resposta em K, COMMIT3201 (resposta perdida na rede)4POST /pix (mesma K)5chave K já existe, lê a resposta gravada6201 + X-Idempotent-Replay, sem novo débito7AppAPI PIXPostgreSQL
7

7 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.

  1. 1

    Idempotency-Key UUID obrigatória, uma por operação

  2. 2

    A chave primária deixa só uma requisição inserir, mesmo simultâneas

  3. 3

    Quem insere debita e grava PIX e resposta na mesma transação

  4. 4

    As demais recebem a resposta gravada; corpo diferente com a mesma chave → 422

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

  • .env.exampleinfra
  • docker.shinfra
  • package.jsoninfra
  • README.md
  • tsconfig.jsoninfra

sql/

  • 01_schema.sqlschema

src/

  • demo.tsdemo

Executar com Docker

  1. ./docker.sh
  2. until docker exec idempotency-db pg_isready -h 127.0.0.1 -U postgres >/dev/null 2>&1; do sleep 1; done
  3. bun install# dependências
  4. bun run demo# roda o cenário
  5. docker rm -f idempotency-db

Saí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.

Requisitos
BunDocker
Sobe junto
PostgreSQL

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

Linhas de TypeScript
57
Tipo
B — um serviço (docker.sh)

Domínio financeiro

  • PIX

Padrões do catálogo que implementa

Infraestrutura

  • PostgreSQLbanco relacional

    postgres:16-alpine:5432

Banco

sql/01_schema.sql

  • accounts
  • pix_transfers
  • idempotency_keys

Variáveis de ambiente

IDEMPOTENCY_DATABASE_URL
postgres://postgres:postgres@localhost:5432/idempotency_db
PostgreSQL of accounts, PIX transfers and idempotency keys.

Trilhapasso 1 de 7

Consistência sem transação distribuída

  1. 1Idempotency
  2. 2Outbox
  3. 3Inbox
  4. 4Saga — Coreografia
  5. 5Saga — Orquestração
  6. 6Process Orchestrator
  7. 7Two-Phase Commit (2PC)

Parecidos

Esc

↑ ↓ navegarEnter abrir239 resultados