Guides

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.

1
import { Actor, Operation, ActorContext } from '@orcher/sdk';
2
3
interface CartItem {
4
name: string;
5
price: number;
6
quantity: number;
7
}
8
9
interface Cart {
10
items: CartItem[];
11
updatedAt: string;
12
}
13
14
@Actor()
15
export 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
}
29
30
@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
}
38
39
@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
}
44
45
@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 default
2
async 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' })
2
async getCount(ctx: ActorContext): Promise<number> {
3
return await ctx.state.get<number>('count') ?? 0;
4
}

Concurrency Rules

Executing \ IncomingExclusiveShared
ExclusiveQueuedQueued
SharedQueuedRuns 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()
2
async manageState(ctx: ActorContext): Promise<void> {
3
// Get a value (returns undefined if not set)
4
const name = await ctx.state.get<string>('name');
5
6
// Set a value (JSON-serialized automatically)
7
await ctx.state.set('name', 'Alice');
8
9
// Delete a key (returns true if it existed)
10
const existed = await ctx.state.delete('name');
11
12
// List all keys, optionally filtered by prefix
13
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 type
2
await ctx.state.set('item:widget', { name: 'Widget', qty: 3 });
3
await ctx.state.set('item:gadget', { name: 'Gadget', qty: 1 });
4
5
// List all items
6
const 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.

PropertyTypeDescription
actorNamestringActor type name (e.g., "ShoppingCart")
keystringInstance key (e.g., "user-123")
operationNamestringOperation being executed (e.g., "addItem")
operationIdstringUnique ID for this operation execution
executionIdstringExecution ID for tracing and idempotency
modeOperationModeexclusive or shared
stateActorStateServer-backed state access (get/set/delete/listKeys)
metadataRecord<string, string>Optional metadata from the invocation request

Next Steps