Pular para o conteúdo

Scheduler Agent Supervisor

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.

passos
4
arquivos
7
testes
0
tecnologias
5

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ência
7/7
etapa interest_apply running, tentativa 11dispara2processo morre, heartbeat para3running com heartbeat além do limiar?4UPDATE atômico: tentativa 25reinicia a etapa6efeito e conclusão na mesma transação, só se a tentativa ainda é 27SchedulerPostgreSQLAgent tentativa 1SupervisorAgent tentativa 2
7

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

  1. 1

    Scheduler cria a etapa running, tentativa 1

  2. 2

    Agent atualiza heartbeat_at; efeito e completed commitam juntos

  3. 3

    Supervisor reivindica, num UPDATE, etapas com heartbeat vencido e incrementa a tentativa

  4. 4

    Tentativa = token de fencing; crédito com chave (step_id, account_id)

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

  • .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 scheduler-agent-supervisor-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 scheduler-agent-supervisor-db

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

Requisitos
BunDocker
Sobe junto
PostgreSQL

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

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

Domínio financeiro

  • Crédito/Empréstimo
  • Juros

Padrões do catálogo que implementa

  • Scheduler Agent Supervisor

Infraestrutura

  • PostgreSQLbanco relacional

    postgres:16-alpine:5432

Banco

sql/01_schema.sql

  • accounts
  • batch_steps
  • interest_credits

Variáveis de ambiente

SCHEDULER_AGENT_SUPERVISOR_DATABASE_URL
postgres://postgres:postgres@localhost:5432/settlement_batch_db
PostgreSQL of the batch steps and their outputs.

Parecidos

Por que se relacionam

Teste rápido

Qual destes combina com Scheduler Agent Supervisor?

Próximo projeto, ResiliênciaThrottling
Esc

↑ ↓ navegarEnter abrir239 resultados