Pular para o conteúdo

Actor Model

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

passos
5
arquivos
4
testes
0
tecnologias
3

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

Fluxo
4/4
Débito 1Mailbox CC-2002Débito 2Débito 3Ledger HTTP: lê,espera, gravauma mensagem por vez
4

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

  1. 1

    Sem o ator, os cinco débitos leem o mesmo saldo e um sobrescreve o outro

  2. 2

    O ator tem uma fila e um laço drain()

  3. 3

    Cada mensagem termina antes da próxima

  4. 4

    Um ator por conta

  5. 5

    Contas diferentes rodam em paralelo

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

  • package.jsoninfra
  • README.md
  • tsconfig.jsoninfra

src/

  • demo.tsdemo

Executar só Bun

  1. bun install# dependências
  2. bun run demo# roda o cenário

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

Requisitos
Bun

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

Linhas de TypeScript
57
Tipo
A — código puro

Domínio financeiro

  • Conta corrente
  • Saldo

Padrões do catálogo que implementa

  • Actor Model

Por que se relacionam

Teste rápido

Qual destes combina com Actor Model?

Próximo projeto, Concorrência & CoordenaçãoLeader Election
Esc

↑ ↓ navegarEnter abrir239 resultados