pattern/messaging/sequential-convoy
- Apache Kafka
- Bun
- KafkaJS
- TypeScript
- Docker
Mantém a ordem só onde importa: mensagens da mesma entidade vão juntas pela mesma partição do Kafka; entidades diferentes seguem em paralelo.
pattern/messaging/sequential-convoy
Cenário
Crédito de R$ 1.000,00 processado antes do débito de R$ 700,00 da mesma conta; contas diferentes em paralelo.
Planta
Fluxo6 passos — reproduza para seguir o fluxo
Como funciona
4passos
Mensagens da mesma entidade vão pela mesma partição e entidades diferentes seguem em paralelo
Esconde cada passo: lembre antes de tocar para revelar.
Chave = contaMesma partição
Produtor idempotente com uma requisição em voo: reenvio não ultrapassa
Partições em paralelo; dentro de cada uma, uma mensagem por vez
O ledger aplica só a próxima sequência da conta
Trade-offs
O que se ganha, o que se paga
Vantagens
Ordem por entidade sem lock global
Contas diferentes em paralelo
Custos
Paralelismo limitado às partições
Conta muito ativa vira hot partition
Código
pattern/messaging/sequential-convoy
6 arquivos./
src/
Executar com Docker
./docker.shuntil docker exec sequential-convoy-broker /opt/kafka/bin/kafka-topics.sh --bootstrap-server localhost:9092 --list >/dev/null 2>&1; do sleep 1; donebun install# dependênciasbun run demo# roda o cenáriodocker rm -f sequential-convoy-brokerSaída: cada conta na sua partição, crédito R$ 1000.00 → débito R$ 700.00 → crédito R$ 200.00 em ordem; saldo final R$ 500.00 nas 2 contas.
Código
src/demo.ts// Demo: credits and debits of two accounts are published interleaved, keyed by account; each account's convoy stays in order on one partition.
import { Kafka, logLevel } from "kafkajs";
const ACCOUNT_TOPIC = "bank.account-events";
// Ceiling of consumer parallelism: sized by accounts active at once, not by message volume.
const ACCOUNT_PARTITIONS = 3;
type AccountEvent = { accountId: string; sequence: number; type: "credit" | "debit"; amountCents: number };
const kafka = new Kafka({ clientId: "bank-ledger", brokers: (Bun.env.SEQUENTIAL_CONVOY_KAFKA_BROKERS ?? "localhost:9092").split(","), logLevel: logLevel.ERROR });
const admin = kafka.admin();
await admin.connect();
await admin.createTopics({ waitForLeaders: true, topics: [{ topic: ACCOUNT_TOPIC, numPartitions: ACCOUNT_PARTITIONS }] });
await admin.disconnect();
// Ledger projection: applies only the next sequence of the account; a gap would mean the convoy broke.
const ledger = new Map<string, { balanceCents: number; lastSequence: number }>();
const stats = { applied: 0 };
const consumer = kafka.consumer({ groupId: `ledger-${Date.now()}` });
await consumer.connect();
await consumer.subscribe({ topics: [ACCOUNT_TOPIC], fromBeginning: true });
await consumer.run({
// One worker per partition: parallel across accounts, one message at a time within each account.
partitionsConsumedConcurrently: ACCOUNT_PARTITIONS,
eachMessage: async ({ partition, message }) => {
const event = JSON.parse(message.value!.toString()) as AccountEvent;
const account = ledger.get(event.accountId) ?? { balanceCents: 0, lastSequence: 0 };
if (event.sequence !== account.lastSequence + 1) throw new Error(`${event.accountId} sequence ${event.sequence} out of order`);
ledger.set(event.accountId, { balanceCents: account.balanceCents + (event.type === "credit" ? event.amountCents : -event.amountCents), lastSequence: event.sequence });
stats.applied++;
console.log(` [LEDGER p${partition}] ${event.accountId} #${event.sequence} ${event.type} R$ ${(event.amountCents / 100).toFixed(2)}`);
},
});
// Idempotent producer with one request in flight: a retried batch never overtakes the one behind it.
const producer = kafka.producer({ idempotent: true, maxInFlightRequests: 1 });
await producer.connect();
// The credit must come before the debit it covers; out of order, the debit would hit an empty account.
const statement = [{ type: "credit", amountCents: 100_000 }, { type: "debit", amountCents: 70_000 }, { type: "credit", amountCents: 20_000 }] as const;
const accounts = [`CC-${Date.now()}-A`, `CC-${Date.now()}-B`];
for (const [index, step] of statement.entries()) {
// Key = account id: same key, same partition, always.
for (const accountId of accounts) await producer.send({ topic: ACCOUNT_TOPIC, acks: -1, messages: [{ key: accountId, value: JSON.stringify({ accountId, sequence: index + 1, ...step }) }] });
}
for (let i = 0; i < 200 && stats.applied < statement.length * accounts.length; i++) await Bun.sleep(50);
for (const [accountId, account] of ledger) console.log(` [BALANCE] ${accountId}: R$ ${(account.balanceCents / 100).toFixed(2)}`);
await consumer.disconnect();
await producer.disconnect();
Nível
introdutório
3/13
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
Apache Kafkalog distribuído
apache/kafka:3.7.0:9092
Variáveis de ambiente
Parecidos
Por que se relacionam
Teste rápido
Qual destes combina com Sequential Convoy?
Grupo por conta mantém a ordem. Abrir SQS FIFO Bank Transfer
Seu progresso
0/157 estudados
Fica salvo só neste navegador.