Stateful Actors with Event Sourcing
Actors maintain per-entity state with single-writer guarantees — only one operation runs at a time for a given actor ID, preventing race conditions. Combined with event sourcing, every state change is recorded as an event in the actor's journal. You can rebuild the full state of any entity by replaying its event history, and the journal serves as a complete audit trail.
How it works
The overview showed that same-entity operations serialize. The refinement is that not every operation is a writer: mark the ones that mutate state exclusive, and let read-only operations run concurrently. It's a reader/writer lock scoped to one actor ID — but you never write the lock.
add_item, remove_item. One at a time for this actor; each sees the previous write. Nothing else — reader or writer — runs meanwhile.
Read-only views can run together for the same actor. They still wait for an in-flight writer, so a read never sees a half-applied change.
Example: an event-sourced shopping cart
1import {2 Actor,3 Operation,4 Tasks,5 Task,6 ActorContext,7 createTaskRefs,8} from '@orcher/sdk';910@Tasks()11class CartTasks {12 @Task()13 async calculateShipping(items: CartItem[]): Promise<number> {14 return await shippingCalculator.estimate(items);15 }1617 @Task()18 async applyDiscount(input: DiscountInput): Promise<number> {19 return await pricingEngine.applyDiscount(input.subtotal, input.code);20 }21}2223const tasks = createTaskRefs(CartTasks);2425// Actor: Shopping cart with event-sourced state26@Actor({ name: 'shopping_cart' })27class ShoppingCart {28 @Operation({ exclusive: true })29 async addItem(ctx: ActorContext, item: CartItem): Promise<CartState> {30 const state = (await ctx.state().get<CartState>('cart')) ?? {31 items: [], subtotal: 0, updatedAt: new Date(),32 };3334 state.items.push(item);35 state.subtotal += item.price * item.quantity;36 state.updatedAt = new Date();3738 await ctx.state().set('cart', state);39 return state;40 }4142 @Operation({ exclusive: true })43 async removeItem(ctx: ActorContext, itemId: string): Promise<CartState> {44 const state = (await ctx.state().get<CartState>('cart')) ?? {45 items: [], subtotal: 0, updatedAt: new Date(),46 };4748 const index = state.items.findIndex((i) => i.id === itemId);49 if (index !== -1) {50 const removed = state.items.splice(index, 1)[0];51 state.subtotal -= removed.price * removed.quantity;52 }53 state.updatedAt = new Date();5455 await ctx.state().set('cart', state);56 return state;57 }5859 @Operation()60 async checkout(61 ctx: ActorContext,62 payment: PaymentMethod,63 ): Promise<CheckoutResult> {64 const state = (await ctx.state().get<CartState>('cart')) ?? {65 items: [], subtotal: 0, updatedAt: new Date(),66 };6768 if (state.items.length === 0) {69 throw new Error('Cart is empty');70 }7172 // Calculate shipping (task within actor)73 const shipping = await ctx.executeTask(74 tasks.calculateShipping, state.items,75 );7677 // Start checkout workflow78 const orderId = await ctx.startChildWorkflow(ProcessCheckout, {79 items: state.items,80 subtotal: state.subtotal,81 shipping,82 payment,83 });8485 // Clear cart86 await ctx.state().set('cart', { items: [], subtotal: 0, updatedAt: new Date() });8788 return { orderId };89 }90}Each actor instance is identified by a key (e.g., shopping_cart:user_123). The exclusive flag ensures that add_item and remove_item operations are serialized — no two exclusive operations run concurrently for the same actor ID, eliminating race conditions on the cart state. Non-exclusive operations like checkout can read state concurrently with other non-exclusive operations.
State is the fold of its events
Event sourcing stores the changes, not just the latest snapshot. The current cart is what you get by replaying its events in order — which means the journal isn't only crash recovery, it's the source of truth and a complete audit trail in one.
Design notes
- Mutations belong in
exclusiveoperations. Any operation that callsstate().setis a writer and should beexclusive— otherwise it can interleave with another writer and lose an update. Audit each operation by whether it mutates, not by what it's named. (Acheckoutthat clears the cart mutates, so it needs the same protection asadd_item.) - Keep exclusive operations short. An exclusive op holds the actor's writer slot until it returns, so every other write to that entity waits behind it. Do the fast state change in the operation and offload slow work — payment, shipping — to a child workflow, exactly as
checkoutstartsprocess_checkoutrather than charging inline. - Snapshot when the history gets long. Rebuilding from thousands of events is slow. Periodically persist a snapshot of the folded state and replay only the events since — the same journal-growth pressure as a long scheduled-job loop, solved by checkpointing the fold.
- Actors partition; they don't parallelize one entity. Throughput scales with the number of distinct actors, because same-ID operations are serial by design. If one entity is a hotspot (a viral product's inventory counter), that single actor is your ceiling — shard it into sub-counters if you must.