pattern/persistence/batch-processing
- Bun
- PostgreSQL
- TypeScript
- node-postgres
- Docker
Lote em janela de corte com checkpoint por bloco: caiu no meio, retoma do último bloco commitado sem duplicar efeito.
pattern/persistence/batch-processing
Cenário
O fechamento do dia aplica as transações nos saldos; a execução cai após dois blocos e a seguinte retoma do checkpoint.
Planta
Sequência4 passos — reproduza para seguir o fluxo
Como funciona
4passos
Lote em janela de corte com checkpoint por bloco, retomado sem duplicar efeito
Esconde cada passo: lembre antes de tocar para revelar.
Execução em batch_runs pela chave job + data
Bloco = transaçãoTrava o checkpoint, lê id > checkpoint ORDER BY id LIMIT 10, aplica
Checkpoint commita junto com o efeito
Reinício continua do último bloco commitado
Trade-offs
O que se ganha, o que se paga
Vantagens
Crash custa só o bloco em andamento
Transações curtas, sem lock longo
Custos
Resultado só no fim da janela
Exige chave monotônica
Código
pattern/persistence/batch-processing
7 arquivos./
sql/
src/
Executar com Docker
./docker.shuntil docker exec batch-processing-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 batch-processing-dbSaída: a execução 1 para no checkpoint 20 (20 processadas); a execução 2 retoma e chega a 50; Eduardo Lima e Marina Costa fecham com R$ 250.00 cada.
Código
src/demo.ts// Demo: the end-of-day close applies the day's transactions in chunks, each committed with its checkpoint; a crash resumes, never restarts.
import pg from "pg";
const pool = new pg.Pool({ connectionString: Bun.env.BATCH_PROCESSING_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/batch_processing_db" });
const JOB = { name: "eod-position-close", date: new Date().toISOString().slice(0, 10), chunkSize: 10 };
// One chunk, one transaction: the effect and the new checkpoint commit together, or neither does.
async function chunkProcess(): Promise<number> {
const client = await pool.connect();
try {
await client.query("BEGIN");
// FOR UPDATE: a second runner of the same job waits here and continues after this chunk instead of applying it again.
const { rows: [run] } = await client.query<{ last_processed_id: string }>("SELECT last_processed_id FROM batch_runs WHERE job_name = $1 AND statement_date = $2 FOR UPDATE", [JOB.name, JOB.date]);
const { rows } = await client.query<{ id: string; account_id: string; amount_cents: string }>(
"SELECT id, account_id, amount_cents FROM transactions WHERE booked_on = $1 AND id > $2 ORDER BY id LIMIT $3",
[JOB.date, run!.last_processed_id, JOB.chunkSize],
);
for (const row of rows) await client.query("UPDATE accounts SET balance_cents = balance_cents + $2 WHERE id = $1", [row.account_id, row.amount_cents]);
if (rows.length > 0) await client.query("UPDATE batch_runs SET last_processed_id = $3, total_processed = total_processed + $4 WHERE job_name = $1 AND statement_date = $2", [JOB.name, JOB.date, rows.at(-1)!.id, rows.length]);
await client.query("COMMIT");
return rows.length;
} catch (error) {
await client.query("ROLLBACK");
throw error;
} finally {
client.release();
}
}
// chunksMax stands in for the process dying after a few chunks.
async function eodRun(chunksMax = Infinity): Promise<void> {
await pool.query("INSERT INTO batch_runs (job_name, statement_date) VALUES ($1, $2) ON CONFLICT DO NOTHING", [JOB.name, JOB.date]);
for (let chunk = 0; chunk < chunksMax && (await chunkProcess()) > 0; chunk++);
const { rows: [run] } = await pool.query<{ last_processed_id: string; total_processed: number }>("SELECT last_processed_id, total_processed FROM batch_runs WHERE job_name = $1 AND statement_date = $2", [JOB.name, JOB.date]);
console.log(` [BATCH] checkpoint at transaction ${run!.last_processed_id}, ${run!.total_processed} processed`);
}
await pool.query("TRUNCATE batch_runs, transactions RESTART IDENTITY; UPDATE accounts SET balance_cents = 0");
// The day's movement: 25 credits of R$ 10.00 per account.
await pool.query("INSERT INTO transactions (account_id, amount_cents) SELECT a.id, 1000 FROM accounts a CROSS JOIN generate_series(1, 25)");
console.log("--- run 1: dies after 2 chunks ---");
await eodRun(2);
console.log("--- run 2: resumes from the checkpoint ---");
await eodRun();
const { rows } = await pool.query<{ owner_name: string; balance_cents: string }>("SELECT owner_name, balance_cents FROM accounts ORDER BY owner_name");
for (const row of rows) console.log(` [LEDGER] ${row.owner_name}: R$ ${(Number(row.balance_cents) / 100).toFixed(2)}`);
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
Parecidos
Por que se relacionam
Combina com
Teste rápido
Qual destes combina com Batch Processing?
Fechamento por partição de data. Abrir Partition Table
Seu progresso
0/157 estudados
Fica salvo só neste navegador.