引言
多数并发 bug 来自两段代码同时触碰同一状态。Actor 模型移除了共享状态:每个 Actor 私有拥有其状态且只有它触碰它,Actor 之间通过发送从邮箱一次一条处理的消息通信。因为 Actor 一次只处理一条消息,其状态转换被串行化,你靠构造而非靠加锁获得正确性。本教程用 TypeScript 构建一个小而类型化的 Actor 运行时。
Actor 契约
Actor 有私有状态、持有入站消息的邮箱,以及一次取一条消息并返回新状态的单线程处理循环。外部无人读写其状态;影响它的唯一方式是发消息。这就是整个模型,也是它移除数据竞争的原因。
消息是类型化的,意味着合法交互集合是编译器检查的可辨识联合。只接受 Deposit 与 Withdraw 的 Actor 无法被弄去做别的,而漏掉某消息类型的处理器无法通过类型检查。类型即协议。
邮箱与串行处理
邮箱是队列,Actor 一次一条地排空它。两条消息绝不并发运行在一个 Actor 内,因此 reduce 函数可假定对状态独占访问。Actor 忙时发送的消息被排队而非丢弃,除非邮箱有界且已满,此时告知发送者。
因处理被串行化,状态可就地安全修改,或建模为每个处理器返回的不可变值。不可变形式更易测试与推理:处理器是从 (状态, 消息) 到状态加副作用的纯函数,正是单元测试想要的形状。
用 Promise 实现请求—应答
即发即忘消息容易;请求—应答需要把结果返回给发送者的方式。模式是携带应答回调或 promise resolve 的消息。Actor 处理该消息时调用应答,发送者 await 它。即使失败也必须调用应答,否则发送者的 promise 永远挂起。
因应答是异步的,发送者不得假定其后续消息的顺序。若调用者发 Withdraw 再读余额,若经不同路径发送,读可能在取款完成前被处理。把需要顺序的操作建模为单条消息,或在发下一条前 await 应答。
监督与失败隔离
处理消息时抛错的 Actor 不应损坏其状态或停掉整个系统。在 drain 循环内捕获错误,决定消息是否可重试,并跳过、补偿或上报告监督者。状态应仅在处理器成功后更新,或失败时回滚。
监督是 Actor 模型对容错的答案:父级监视子级并在失败时重启。按 Actor 实现策略,带有限重启次数与退避,使永久坏掉的 Actor 被隔离而非永远重启循环、消耗资源。
模型的适用之处
当资源有天然归属与更新流时 Actor 出色:会话、连接、游戏房间、限流桶、每租户配额。它们不适合无状态请求处理(邮箱开销一无所获),也不适合大批量数据处理(吞吐比隔离更重要,worker 加队列更简单)。
在单线程运行时,Actor 模型主要是关于异步交错下的正确性而非真正并行。串行化邮箱移除了导致竞争的交错。当你还需要并行时,把 Actor 跑在 worker 线程上并跨边界发消息,保持每个 Actor 同样的“一次一条消息”契约。
常见陷阱与小结
不要让消息处理器阻塞循环;慢处理器会卡住该 Actor 的邮箱与等待它的每个发送者。保持处理器快并卸载阻塞工作。不要暴露 Actor 状态供直接访问,否则你重新引入了移除掉的共享状态。不要忘记总是调用应答。也不要假定跨 Actor 的消息顺序;只保证同一 Actor 内的顺序。
Actor 模型用消息队列换掉共享可变状态,作为交换你得到串行化的状态转换与隔离到单个 Actor 的失败。定义类型化消息协议、一次一条排空邮箱、用 promise 支持请求—应答、用有限重启监督失败。它是少量机制,却让一整类并发 bug 无法写出。
代码示例
type Message =
| { type: 'Deposit'; amount: number }
| { type: 'Withdraw'; amount: number; reply: (ok: boolean) => void }
| { type: 'GetBalance'; reply: (balance: number) => void };
interface AccountState { balance: number; }
function reduce(state: AccountState, msg: Message): AccountState {
switch (msg.type) {
case 'Deposit':
return { balance: state.balance + msg.amount };
case 'Withdraw': {
const ok = state.balance >= msg.amount;
msg.reply(ok);
return ok ? { balance: state.balance - msg.amount } : state;
}
case 'GetBalance':
msg.reply(state.balance);
return state;
}
}
class Actor<S, M> {
private queue: M[] = [];
private running = false;
constructor(private state: S, private reduce: (s: S, m: M) => S) {}
send(msg: M): void {
this.queue.push(msg);
void this.drain(); // schedule if idle
}
private async drain(): Promise<void> {
if (this.running) return; // already draining
this.running = true;
try {
while (this.queue.length > 0) {
const msg = this.queue.shift()!;
this.state = this.reduce(this.state, msg); // exclusive access
}
} finally {
this.running = false;
}
}
}
function ask<S, M extends { reply: (v: T) => void }, T>(
actor: Actor<S, M>,
build: (reply: (v: T) => void) => M,
): Promise<T> {
return new Promise<T>((resolve) => msgs.push(build(resolve)));
}
// usage
const ok = await ask(account, (reply) => ({ type: 'Withdraw', amount: 50, reply }));
if (!ok) throw new Error('insufficient funds');
private async drain(): Promise<void> {
if (this.running) return;
this.running = true;
while (this.queue.length > 0) {
const msg = this.queue.shift()!;
const snapshot = this.state; // for rollback on failure
try {
this.state = this.reduce(this.state, msg);
} catch (err) {
this.state = snapshot; // keep state consistent
this.onError?.(err, msg); // note/ escalate/ quarantine
}
}
this.running = false;
}
# good fits for actors
session store one owner per session, serialised updates
connection registry one owner per connection, ordered events
rate-limit buckets per-key state, no locks
game/room state ordered messages per room
# poor fits
stateless HTTP handlers (no shared state to protect)
bulk ETL (throughput-bound, workers + queue is simpler)