pattern/concurrency/actor-model
- Bun
- ElysiaJS
- TypeScript
Cada entidade é um ator com caixa de mensagens processada uma por vez: sem lock, a mesma entidade nunca se sobrepõe, entidades diferentes em paralelo (Akka, Erlang/OTP).
pattern/concurrency/actor-model
Cenário
Cinco débitos simultâneos de R$ 100,00 numa conta de R$ 1.000,00: direto no ledger, saldo final R$ 900,00 e quatro débitos perdidos; com o ator, R$ 500,00.
Planta
Fluxo4 passos — reproduza para seguir o fluxo
Como funciona
5passos
Cada entidade é um ator com caixa de mensagens processada uma por vez, sem lock
Esconde cada passo: lembre antes de tocar para revelar.
Sem o ator, os cinco débitos leem o mesmo saldo e um sobrescreve o outro
O ator tem uma fila e um laço drain()
Cada mensagem termina antes da próxima
Um ator por conta
Contas diferentes rodam em paralelo
Trade-offs
O que se ganha, o que se paga
Vantagens
Sem lock nem deadlock
Contas em paralelo
Custos
Mensagem lenta atrasa a fila da conta
Serialização só dentro do processo
Código
pattern/concurrency/actor-model
4 arquivos./
src/
Executar só Bun
bun install# dependênciasbun run demo# roda o cenárioSaída: direto no ledger, os cinco débitos devolvem R$ 900,00 e quatro se perdem; pelo ator, R$ 900,00 → R$ 800,00 → R$ 700,00 → R$ 600,00 → R$ 500,00, nenhum perdido.
Código
src/demo.ts// Demo: five concurrent debits on one account, first straight to the ledger (lost updates), then through the account's actor, whose mailbox lets one in at a time.
import { Elysia, t } from "elysia";
const ACCOUNT_ID = "CC-2002";
const BALANCE_OPENING_CENTS = 100_000;
const DEBIT_CENTS = 10_000;
const DEBIT_COUNT = 5;
const LEDGER_ROUND_TRIP_MS = 30;
// Ledger over HTTP: reads the balance, waits like a database round trip, then writes — the window where concurrent debits collide.
const balances = new Map([[ACCOUNT_ID, BALANCE_OPENING_CENTS]]);
const ledger = new Elysia()
.post(
"/accounts/:id/debits",
async ({ params, body }) => {
const current = balances.get(params.id)!;
await Bun.sleep(LEDGER_ROUND_TRIP_MS);
balances.set(params.id, current - body.amountCents);
return { balanceCents: current - body.amountCents };
},
{ body: t.Object({ amountCents: t.Integer({ minimum: 1 }) }) },
)
.listen(0);
async function ledgerDebit(accountId: string, amountCents: number): Promise<number> {
const response = await fetch(`http://localhost:${ledger.server!.port}/accounts/${accountId}/debits`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ amountCents }) });
return ((await response.json()) as { balanceCents: number }).balanceCents;
}
// The actor: a mailbox drained by one loop, each message run to completion before the next — no lock, no semaphore.
class ActorAccount {
private readonly mailbox: (() => Promise<void>)[] = [];
private draining = false;
constructor(private readonly accountId: string) {}
debit(amountCents: number): Promise<number> {
return new Promise((resolve, reject) => {
// A failed call rejects only its own caller; the loop goes on to the next message.
this.mailbox.push(() => ledgerDebit(this.accountId, amountCents).then(resolve, reject));
void this.drain();
});
}
private async drain(): Promise<void> {
if (this.draining) return;
this.draining = true;
while (this.mailbox.length > 0) await this.mailbox.shift()!();
this.draining = false;
}
}
const brl = (cents: number) => `R$ ${(cents / 100).toFixed(2)}`;
// Without the actor: the five debits hit the ledger at once, all read the same balance and overwrite each other.
const resultsDirect = await Promise.all(Array.from({ length: DEBIT_COUNT }, () => ledgerDebit(ACCOUNT_ID, DEBIT_CENTS)));
console.log(` [DIRECT] balances after each debit: ${resultsDirect.map(brl).join(" → ")}`);
const balanceDirectCents = balances.get(ACCOUNT_ID)!;
console.log(` [LEDGER] final ${brl(balanceDirectCents)}: ${DEBIT_COUNT - (BALANCE_OPENING_CENTS - balanceDirectCents) / DEBIT_CENTS} debits lost`);
// One actor per account: two callers of the same account share one mailbox; other accounts would run in parallel.
balances.set(ACCOUNT_ID, BALANCE_OPENING_CENTS);
const actor = new ActorAccount(ACCOUNT_ID);
const results = await Promise.all(Array.from({ length: DEBIT_COUNT }, () => actor.debit(DEBIT_CENTS)));
console.log(` [ACTOR] balances after each debit: ${results.map(brl).join(" → ")}`);
console.log(` [LEDGER] final ${brl(balances.get(ACCOUNT_ID)!)}: no debit lost`);
await ledger.stop(true);
Nível
introdutório
1/13
Domínio financeiro
Padrões do catálogo que implementa
Por que se relacionam
Teste rápido
Qual destes combina com Actor Model?
Só troca mensagens assíncronas. Abrir Async Messaging
Seu progresso
0/157 estudados
Fica salvo só neste navegador.