Pular para o conteúdo

Offline Locking

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.

passos
4
arquivos
7
testes
0
tecnologias
5

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

Estados
5/5
LidoSalvoConflitooperador lê oregistro com a versãoUPDATE WHERE version= lida, versão + 1outro salvouantes, zero linhasrecarrega ereaplica a mudança
5

5 passos — reproduza para seguir o fluxo

  • chamada
  • resposta ou assíncrono
  • falha
  • passo
  • toque num nó para focar
  • repouso ou sucesso
  • transição
  • falha ou recusa
  • Outras plantas de estados

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

version+1
  1. 1

    Toda leitura devolve version

  2. 2

    SaveUPDATE ... WHERE version = $2 e incrementa

  3. 3

    Zero linhasConflito

  4. 4

    O operador recarrega e reaplica

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

  • .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 offline-locking-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 offline-locking-db

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

Requisitos
BunDocker
Sobe junto
PostgreSQL

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

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

Domínio financeiro

  • Limite

Padrões do catálogo que implementa

Infraestrutura

  • PostgreSQLbanco relacional

    postgres:16-alpine:5432

Banco

sql/01_schema.sql

  • customers

Variáveis de ambiente

OFFLINE_LOCKING_DATABASE_URL
postgres://postgres:postgres@localhost:5432/offline_locking_db
PostgreSQL of the customer records.

Por que se relacionam

Teste rápido

Qual destes combina com Offline Locking?

Próximo projeto, Transações & ConsistênciaOutbox
Esc

↑ ↓ navegarEnter abrir239 resultados