Pular para o conteúdo

Batch Processing (Fechamento de Posição EOD)

Lote em janela de corte com checkpoint por bloco: caiu no meio, retoma do último bloco commitado sem duplicar efeito.

passos
4
arquivos
7
testes
0
tecnologias
5

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ência
4/4
loop[cada bloco]BEGIN, SELECT checkpoint FOR UPDATE1SELECT transações id > checkpoint LIMIT 102UPDATE saldos e checkpoint, COMMIT3processo cai após 2 blocosnova execução lê o checkpoint e continua dali4Fechamento EODPostgreSQL
4

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

  1. 1

    Execução em batch_runs pela chave job + data

  2. 2

    Bloco = transaçãoTrava o checkpoint, lê id > checkpoint ORDER BY id LIMIT 10, aplica

  3. 3

    Checkpoint commita junto com o efeito

  4. 4

    Reinício continua do último bloco commitado

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

  • .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 batch-processing-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 batch-processing-db

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

Requisitos
BunDocker
Sobe junto
PostgreSQL

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

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

Domínio financeiro

  • Saldo

Padrões do catálogo que implementa

Infraestrutura

  • PostgreSQLbanco relacional

    postgres:16-alpine:5432

Banco

sql/01_schema.sql

  • accounts
  • transactions
  • batch_runs

Variáveis de ambiente

BATCH_PROCESSING_DATABASE_URL
postgres://postgres:postgres@localhost:5432/batch_processing_db
PostgreSQL of the ledger and the batch runs.

Parecidos

Esc

↑ ↓ navegarEnter abrir239 resultados