Defining Actors & Operations
Defining an Actor
An actor is a class (or struct) with operation methods. Use the @Actor() decorator (TypeScript), @actor decorator (Python), or #[actor] attribute (Rust) to register it.
1import { Actor, Operation, ActorContext } from '@orcher/sdk';23interface CartItem {4 name: string;5 price: number;6 quantity: number;7}89interface Cart {10 items: CartItem[];11 updatedAt: string;12}1314@Actor()15export class ShoppingCart {16 @Operation()17 async addItem(ctx: ActorContext, item: CartItem): Promise<Cart> {18 const cart = await ctx.state.get<Cart>('cart') ?? { items: [], updatedAt: '' };19 const existing = cart.items.find(i => i.name === item.name);20 if (existing) {21 existing.quantity += item.quantity;22 } else {23 cart.items.push(item);24 }25 cart.updatedAt = new Date().toISOString();26 await ctx.state.set('cart', cart);27 return cart;28 }2930 @Operation()31 async removeItem(ctx: ActorContext, itemName: string): Promise<Cart> {32 const cart = await ctx.state.get<Cart>('cart') ?? { items: [], updatedAt: '' };33 cart.items = cart.items.filter(i => i.name !== itemName);34 cart.updatedAt = new Date().toISOString();35 await ctx.state.set('cart', cart);36 return cart;37 }3839 @Operation({ mode: 'shared' })40 async getTotal(ctx: ActorContext): Promise<number> {41 const cart = await ctx.state.get<Cart>('cart') ?? { items: [] };42 return cart.items.reduce((sum, i) => i.price * i.quantity + sum, 0);43 }4445 @Operation({ mode: 'shared' })46 async getCart(ctx: ActorContext): Promise<Cart> {47 return await ctx.state.get<Cart>('cart') ?? { items: [], updatedAt: '' };48 }49}Operations
Operations are the methods that callers invoke on an actor. Each operation receives an ActorContext as its first parameter, which provides access to the actor's identity, metadata, and state.
Exclusive Operations (Mutations)
Exclusive is the default mode. Only one exclusive operation runs at a time per actor key. Use this for any operation that modifies state.
1@Operation() // exclusive by default2async increment(ctx: ActorContext, delta: number): Promise<number> {3 const count = await ctx.state.get<number>('count') ?? 0;4 const newCount = count + delta;5 await ctx.state.set('count', newCount);6 return newCount;7}Shared Operations (Reads)
Shared operations can run concurrently with other shared operations on the same key. Use this for read-only operations — and read-only is enforced: while a key is executing shared operations, the engine rejects state writes (FAILED_PRECONDITION), because a write racing concurrent readers would break their isolation. Anything that modifies state belongs in an exclusive operation.
1@Operation({ mode: 'shared' })2async getCount(ctx: ActorContext): Promise<number> {3 return await ctx.state.get<number>('count') ?? 0;4}Concurrency Rules
| Executing \ Incoming | Exclusive | Shared |
|---|---|---|
| Exclusive | Queued | Queued |
| Shared | Queued | Runs concurrently |
When an exclusive operation is running, all other operations for that key wait in a per-key queue. When only shared operations are running, additional shared operations execute immediately. An incoming exclusive operation waits for all running shared operations to finish first — and shared operations that arrive while it waits queue behind it, so a continuous stream of reads can never starve a write.
The mode is part of the operation's declaration, resolved from worker registrations — callers cannot choose it. If workers temporarily disagree about an operation's mode (a rolling deploy where old and new code declare it differently), Orcher conservatively runs the operation as exclusive until the fleet agrees.
Actor State
Actor state is stored on the server and accessed via RPC calls from the worker. The actor instance itself is transient — if a worker restarts, the actor is recreated and its state is loaded from the server. This means you should never store important data in instance fields; always use ctx.state.
State API
The state API provides key-value operations scoped to the actor instance (actor name + key).
1@Operation()2async manageState(ctx: ActorContext): Promise<void> {3 // Get a value (returns undefined if not set)4 const name = await ctx.state.get<string>('name');56 // Set a value (JSON-serialized automatically)7 await ctx.state.set('name', 'Alice');89 // Delete a key (returns true if it existed)10 const existed = await ctx.state.delete('name');1112 // List all keys, optionally filtered by prefix13 const allKeys = await ctx.state.listKeys();14 const cartKeys = await ctx.state.listKeys('cart:');15}State Design Tips
Use structured keys for related data. Prefix keys to group related state, making it easy to query with listKeys("prefix:").
1// Group by entity type2await ctx.state.set('item:widget', { name: 'Widget', qty: 3 });3await ctx.state.set('item:gadget', { name: 'Gadget', qty: 1 });45// List all items6const itemKeys = await ctx.state.listKeys('item:');Keep state values small. Each get and set is an RPC call. Store only what you need, and consider splitting large objects into separate keys.
Don't store derived data. Compute totals, counts, and aggregates on read rather than storing them separately, to avoid consistency issues between keys.
ActorContext
Every operation receives an ActorContext that provides the actor's identity and state access.
| Property | Type | Description |
|---|---|---|
actorName | string | Actor type name (e.g., "ShoppingCart") |
key | string | Instance key (e.g., "user-123") |
operationName | string | Operation being executed (e.g., "addItem") |
operationId | string | Unique ID for this operation execution |
executionId | string | Execution ID for tracing and idempotency |
mode | OperationMode | exclusive or shared |
state | ActorState | Server-backed state access (get/set/delete/listKeys) |
metadata | Record<string, string> | Optional metadata from the invocation request |