pattern/transactions/offline-locking
- Bun
- PostgreSQL
- TypeScript
- node-postgres
- Docker
Protege edição de minutos que nenhuma transação cobre: lock otimista grava a versão lida e detecta no save quem salvou antes. Sem ele, o último save apaga o outro.
pattern/transactions/offline-locking
Cenário
Dois operadores editam a mesma cliente e salvam ao mesmo tempo: um sobe o limite, outro corrige o e-mail; quem perde recarrega e nenhuma mudança some.
Planta
Estados5 passos — reproduza para seguir o fluxo
Como funciona
4passos
Lock otimista grava a versão lida e detecta no save quem salvou antes, em edições de minutos
Esconde cada passo: lembre antes de tocar para revelar.
Vocabulário compartilhado
Toda leitura devolve version
SaveUPDATE ... WHERE version = $2 e incrementa
Zero linhasConflito
O operador recarrega e reaplica
Trade-offs
O que se ganha, o que se paga
Vantagens
Sem lock durante a edição
Escala com conflito raro
Custos
Segundo editor refaz o trabalho
Conflito frequente pede lock pessimista com TTL
Código
pattern/transactions/offline-locking
7 arquivos./
sql/
src/
Executar com Docker
./docker.shuntil docker exec offline-locking-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 offline-locking-dbSaída: os dois leem a versão 1; um dos saves simultâneos grava e o outro recebe conflito; quem perdeu recarrega a versão 2 e grava; resultado versão 3, e-mail marina.costa@bank.com e limite R$ 18000.00.
Código
src/demo.ts// Demo: two back-office operators edit the same customer for minutes; the version check on save keeps either change from being lost.
import pg from "pg";
const pool = new pg.Pool({ connectionString: Bun.env.OFFLINE_LOCKING_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/offline_locking_db" });
type Customer = { email: string; credit_limit_cents: string; version: number };
const customerGet = async (id: string) => (await pool.query<Customer>("SELECT email, credit_limit_cents, version FROM customers WHERE id = $1", [id])).rows[0]!;
// Optimistic save: passes only if nobody saved since this operator read the record; zero rows means a newer version exists.
async function customerSave(id: string, expectedVersion: number, patch: { email?: string; creditLimitCents?: number }): Promise<boolean> {
const { rowCount } = await pool.query(
`UPDATE customers SET email = coalesce($3, email), credit_limit_cents = coalesce($4, credit_limit_cents), version = version + 1, updated_at = now()
WHERE id = $1 AND version = $2`,
[id, expectedVersion, patch.email ?? null, patch.creditLimitCents ?? null],
);
return rowCount === 1;
}
const { rows: [created] } = await pool.query<{ id: string }>("INSERT INTO customers (full_name, email, credit_limit_cents) VALUES ('Marina Costa', 'marina@bank.com', 1500000) RETURNING id");
const id = created!.id;
// Both operators open the edit screen and read the same version; minutes pass with no database transaction open.
const screenA = await customerGet(id);
const screenB = await customerGet(id);
console.log(` [READ] A and B open the customer at version ${screenA.version}`);
const edits = [
{ operator: "A", label: "raises the limit", version: screenA.version, patch: { creditLimitCents: 1_800_000 } },
{ operator: "B", label: "fixes the e-mail", version: screenB.version, patch: { email: "marina.costa@bank.com" } },
];
// Both save at the same instant from the same version: WHERE version = $2 lets exactly one of them through.
const saved = await Promise.all(edits.map((edit) => customerSave(id, edit.version, edit.patch)));
for (const [index, edit] of edits.entries()) console.log(` [${edit.operator}] ${edit.label} on version ${edit.version} → ${saved[index] ? "saved" : "conflict: someone saved first"}`);
// The loser reloads and reapplies its change on fresh data instead of overwriting the winner's.
for (const [index, edit] of edits.entries()) {
if (saved[index]) continue;
const fresh = await customerGet(id);
console.log(` [${edit.operator}] reapplies on version ${fresh.version} → ${(await customerSave(id, fresh.version, edit.patch)) ? "saved" : "conflict"}`);
}
const final = await customerGet(id);
console.log(` [RESULT] version ${final.version}, e-mail ${final.email}, limit R$ ${(Number(final.credit_limit_cents) / 100).toFixed(2)}: no update lost`);
await pool.end();
Nível
introdutório
3/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
Por que se relacionam
Combina com
Teste rápido
Qual destes combina com Offline Locking?
Versão nova detecta o conflito. Abrir Persistent Data Structure
Seu progresso
0/157 estudados
Fica salvo só neste navegador.