pattern/resilience/scheduler-agent-supervisor
- Bun
- PostgreSQL
- TypeScript
- node-postgres
- Docker
Três papéis coordenados pelo banco: Scheduler dispara, Agent executa com heartbeat, Supervisor reinicia a etapa com heartbeat parado — sem reprocessar o que já foi feito.
pattern/resilience/scheduler-agent-supervisor
Cenário
Fechamento noturno credita 0,5% de juros; o processo morre logo após disparar e o juro não pode ser creditado duas vezes.
Planta
Sequência7 passos — reproduza para seguir o fluxo
Como funciona
4passos
Scheduler dispara, Agent executa com heartbeat e Supervisor reinicia a etapa parada, coordenados pelo banco
Esconde cada passo: lembre antes de tocar para revelar.
Vocabulário compartilhado
Scheduler cria a etapa running, tentativa 1
Agent atualiza heartbeat_at; efeito e completed commitam juntos
Supervisor reivindica, num UPDATE, etapas com heartbeat vencido e incrementa a tentativa
Tentativa = token de fencing; crédito com chave (step_id, account_id)
Trade-offs
O que se ganha, o que se paga
Vantagens
Etapa travada recuperada sozinha
Papéis coordenados pelo banco
Custos
Detecção atrasa até o limiar
Toda etapa idempotente
Código
pattern/resilience/scheduler-agent-supervisor
7 arquivos./
sql/
src/
Executar com Docker
./docker.shuntil docker exec scheduler-agent-supervisor-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 scheduler-agent-supervisor-dbSaída: a tentativa 1 morre; o supervisor vê o heartbeat parado há mais de 1000 ms e reinicia na tentativa 2, que conclui; saldos de R$ 10050.00 (Ana) e R$ 2512.50 (Bruno), juro creditado uma vez.
Código
src/demo.ts// Demo: the agent applying monthly interest dies mid-step; the supervisor sees its heartbeat stop and restarts only that step.
import pg from "pg";
const pool = new pg.Pool({ connectionString: Bun.env.SCHEDULER_AGENT_SUPERVISOR_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/settlement_batch_db" });
// Several heartbeats wide, so a latency spike is not taken for a dead agent.
const HEARTBEAT_MS = 200;
const STALE_MS = 1_000;
const ATTEMPTS_MAX = 3;
const SUPERVISOR_INTERVAL_MS = 300;
const STATUS_POLL_MS = 100;
const INTEREST_BPS = 50;
const agents: Promise<void>[] = [];
// Agent: heartbeats while it works; effect and completion commit together, and only while its attempt is still the current one.
async function agentRun(stepId: string, attempt: number): Promise<void> {
const heartbeat = setInterval(() => void pool.query("UPDATE batch_steps SET heartbeat_at = now() WHERE id = $1 AND attempt_count = $2", [stepId, attempt]), HEARTBEAT_MS);
const client = await pool.connect();
try {
await client.query("BEGIN");
// 0.5% on positive balances; keyed by (step, account), so a rerun credits nothing twice.
await client.query(
`WITH credited AS (INSERT INTO interest_credits (step_id, account_id, amount_cents) SELECT $1, id, balance_cents * $2 / 10000 FROM accounts WHERE balance_cents > 0 ON CONFLICT DO NOTHING RETURNING account_id, amount_cents)
UPDATE accounts a SET balance_cents = a.balance_cents + c.amount_cents FROM credited c WHERE a.id = c.account_id`,
[stepId, INTEREST_BPS],
);
const { rowCount } = await client.query("UPDATE batch_steps SET status = 'completed', completed_at = now() WHERE id = $1 AND attempt_count = $2", [stepId, attempt]);
await client.query(rowCount === 1 ? "COMMIT" : "ROLLBACK"); // superseded attempt: its effect is undone
console.log(` [AGENT] attempt ${attempt} ${rowCount === 1 ? "completed" : "superseded, rolled back"}`);
} finally {
clearInterval(heartbeat);
client.release();
}
}
// Supervisor: one UPDATE claims silent steps and bumps the attempt — two supervisors cannot restart the same step.
async function supervisorCycle(): Promise<void> {
const { rows } = await pool.query<{ id: string; attempt_count: number; status: string }>(
`UPDATE batch_steps SET attempt_count = attempt_count + 1, heartbeat_at = now(), status = CASE WHEN attempt_count + 1 > $2 THEN 'failed' ELSE 'running' END
WHERE status = 'running' AND heartbeat_at < now() - make_interval(secs => $1 / 1000.0) RETURNING id, attempt_count, status`,
[STALE_MS, ATTEMPTS_MAX],
);
for (const step of rows) {
console.log(` [SUPERVISOR] heartbeat silent for over ${STALE_MS} ms → ${step.status === "failed" ? "escalated to a person" : `restart, attempt ${step.attempt_count}`}`);
if (step.status === "running") agents.push(agentRun(step.id, step.attempt_count));
}
}
await pool.query("INSERT INTO accounts (owner_name, balance_cents) VALUES ('Ana Lima', 1000000), ('Bruno Costa', 250000)");
// Scheduler: starts the step at attempt 1 and dispatches the agent — which crashes at once: no heartbeat, no completion.
const { rows: [step] } = await pool.query<{ id: string }>("INSERT INTO batch_steps (name) VALUES ('interest_apply') RETURNING id");
if (!step) throw new Error("batch step not created");
console.log(" [SCHEDULER] interest_apply dispatched; [AGENT] attempt 1 crashed");
const supervisor = setInterval(() => void supervisorCycle(), SUPERVISOR_INTERVAL_MS);
for (let status = "running"; status === "running"; await Bun.sleep(STATUS_POLL_MS)) {
status = (await pool.query<{ status: string }>("SELECT status FROM batch_steps WHERE id = $1", [step.id])).rows[0]?.status ?? "failed";
}
clearInterval(supervisor);
await Promise.all(agents);
const { rows: balances } = await pool.query<{ owner_name: string; balance_cents: string }>("SELECT owner_name, balance_cents FROM accounts ORDER BY balance_cents DESC LIMIT 2");
console.log(` [ACCOUNTS] ${balances.map((row) => `${row.owner_name} R$ ${(Number(row.balance_cents) / 100).toFixed(2)}`).join(", ")}: interest credited once`);
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
Teste rápido
Qual destes combina com Scheduler Agent Supervisor?
Um supervisor ativo por vez. Abrir Leader Election
Seu progresso
0/157 estudados
Fica salvo só neste navegador.