The Actor Pattern is a concurrency model where each actor maintains an isolated state and processes events sequentially. In Vercel Workflows, an actor is implemented as a workflow run that uses a hook as an async iterator to process incoming messages in a loop.
Core Workflow Logic
- Initialize State: Start the workflow with an initial state.
- Create a Hook: Use
defineHook to create a type-safe hook. The hook should be created outside the loop using a deterministic token (e.g., `actor_name:${actorId}`) to allow the workflow to resume and process events sequentially. - Event Loop: Use a
for await...of loop on the hook to process events one by one. Inside the loop, fetch the current state, compute the new state based on the event, and persist the new state.
// 1. Define the hook type once
const counterActorHook = defineHook<CounterEvent>();
// 2. Inside the workflow, create the hook outside the loop
const receiveEvent = counterActorHook.create({
token: `counter_actor:${actorId}`,
});
// 3. Use the hook as an async iterator to process events sequentially
for await (const event of receiveEvent) {
const state = await getState(actorId);
const newState = await computeNewState(state, event);
await setState(actorId, newState);
}