Orleans
Orleans lets you write distributed systems as single-threaded objects called grains, while the runtime handles where each grain runs, how it's activated on demand, and how it recovers after a failure.
Overview
A grain is addressed by stable identity rather than location. Orleans activates it on a silo when called, routes later calls to that activation, deactivates idle activations, and recreates them after loss. Its turn-based execution simplifies ownership of mutable entity state, but distributed calls can still fail, duplicate work, interleave when reentrancy is enabled, and lose unpersisted activation state. Production design therefore includes clustering, persistence, serializers, timeouts, idempotency, reminders, placement, telemetry, upgrades, and recovery.
What you will learn
- Recognize domains that fit virtual actors and stable single-owner identities.
- Define grain contracts, keys, serialized messages, implementations, and client calls.
- Reason about activation lifecycle, turn-based execution, reentrancy, and call cycles.
- Choose clustering, membership, placement, gateway, and silo configuration for each environment.
- Persist recoverable state with provider-aware consistency and schema evolution.
- Use timers, reminders, streams, and observers according to durability and delivery requirements.
- Test grains, multi-silo behavior, failure, recovery, serialization, and rolling upgrades.
- Secure, observe, scale, deploy, and operate Orleans clusters in production.
Prerequisites
- C# async programming, dependency injection, hosted services, and serialization.
- Distributed-system basics: partial failure, retries, idempotency, partitioning, and eventual consistency.
- A shared production storage or membership provider appropriate to the target platform.
- A .NET 10 SDK to run the dedicated Orleans shopping-cart sample.
When to use Orleans
Good fit
- Use Orleans for large numbers of addressable entities with clear single-owner state and behavior.
- Use it for devices, accounts, carts, games, sessions, workflows, or tenants that map naturally to stable keys.
- Use reminders when work must survive activation loss and streams when event flows fit actor processing.
- Use stateless workers or placement strategies when work is computational rather than entity-state ownership.
Choose another approach when
- Do not model every repository row or stateless request as a grain.
- Do not use grains as a general analytical query store or hide unbounded collections inside one hot actor.
- Do not depend on in-memory fields when state must survive deactivation or silo loss.
- Do not enable reentrancy or build cyclic grain call graphs without explicit interleaving and deadlock analysis.
Key concepts
A grain is a single-threaded, addressable unit of distributed state and behavior, identified by a stable key rather than a physical location.
Grains always logically exist; the runtime activates them on demand and deactivates them when idle, so callers never manage a grain's lifecycle directly.
A cluster of silos hosts grains; Orleans decides where to activate each grain and can reactivate it elsewhere automatically if a silo fails.
A grain normally processes one turn at a time; awaits and reentrancy rules determine when other calls can interleave.
Storage providers recover selected grain state across activation loss; writes, versioning, concurrency, and provider failure remain application concerns.
Timers are activation-scoped scheduling; reminders are durable registrations that can reactivate a grain after failure or idleness.
Orleans streams connect producers and grain consumers with provider-specific delivery, ordering, persistence, and replay behavior.
Version-tolerant grain interfaces and generated serializers allow clients and silos from compatible versions to coexist during upgrades.
Architecture
A client calls a grain by its identity; the runtime activates it on an available silo, and that grain processes messages one at a time, persisting state as needed.
Conceptual architecture · Adapt to your system context
Implementation walkthrough
Build the critical path deliberately, then verify its observable behavior.
- 01
- 02
- 03
- 04
- 05
- 06
- 07
Code example
A grain interface and implementation define addressable, single-threaded state; Orleans handles activation and placement.
public interface IOrderGrain : IGrainWithGuidKey
{
Task<OrderStatus> GetStatusAsync();
Task PlaceAsync(IReadOnlyList<OrderLine> lines);
}
public sealed class OrderGrain(
[PersistentState("order")] IPersistentState<OrderState> state)
: Grain, IOrderGrain
{
public Task<OrderStatus> GetStatusAsync() => Task.FromResult(state.State.Status);
public async Task PlaceAsync(IReadOnlyList<OrderLine> lines)
{
state.State = state.State with { Lines = lines, Status = OrderStatus.Placed };
await state.WriteStateAsync();
}
}Testing strategy
Test domain behavior quickly, then prove the runtime semantics that only appear with real activations, silos, storage, and failure.
- Unit-test pure policies extracted from grains, including validation, state transitions, idempotency, and message compatibility.
- Use the Orleans test cluster to call real grains through IGrainFactory and reset state between tests.
- Run multi-silo tests for placement, concurrent callers, activation loss, silo shutdown, and recovery from persisted state.
- Verify serializers and contracts across old and new versions used during rolling deployment.
- Exercise storage outage, slow calls, duplicate commands, reminder recovery, stream redelivery, and cancellation.
- Load-test hot keys, activation count, memory, storage calls, queueing, latency percentiles, and cluster rebalance.
Security considerations
Orleans simplifies location and lifecycle, not trust; protect gateways, APIs, providers, contracts, and administrative surfaces independently.
- Authenticate external callers at the application edge and authorize grain operations using trusted tenant and subject context.
- Restrict silo and gateway networking, use encrypted transport where required, and never expose cluster internals directly to untrusted clients.
- Give cluster identities least-privilege access to membership, grain storage, reminders, streams, secrets, and telemetry.
- Validate grain keys, arguments, collection sizes, payload types, and tenant ownership before allocating work or state.
- Treat grain call filters and serializers as security-sensitive extension points; pin and audit packages and generated contracts.
- Redact state and identifiers in logs, encrypt sensitive persisted state, rotate credentials, and audit operator changes.
Performance and scalability
Scale across identities while detecting hot grains, slow turns, excess activation churn, and provider bottlenecks.
- Choose keys that distribute naturally; split or redesign identities that concentrate unrelated work in one grain.
- Keep turns short, asynchronous, bounded, and free of blocking I/O or CPU-heavy loops.
- Batch persistence deliberately, but define acceptable state-loss and consistency behavior before reducing writes.
- Avoid chatty grain call chains; colocate cohesive behavior, use fan-out carefully, and measure serialization overhead.
- Track activation count, working-set memory, turn queue time, call latency, timeouts, rejects, storage latency, and silo load.
- Capacity-test rebalancing and failure because surviving silos must absorb activations and replay without collapse.
Deployment and operations
Deploy Orleans as a coordinated cluster while keeping application contracts and state compatible across mixed silo versions.
- Provision a shared production membership provider, durable grain storage where needed, reminder and stream providers, identity, networking, and telemetry with IaC.
- Use stable cluster and service IDs per environment and prevent accidental cross-environment membership.
- Ship additive interfaces, serializers, and state schema changes before removing fields or methods.
- Roll silos gradually with readiness, graceful shutdown, activation migration, capacity headroom, and rollback criteria.
- Back up and restore durable providers, test regional or zone failure, and document how reminders, streams, and clients recover.
- Monitor cluster membership, silo restarts, activation churn, provider errors, hot grains, latency, and version distribution throughout release.
Common problems and fixes
Clients cannot reach grains
Likely cause: No gateway is reachable, cluster and service IDs differ, membership is unhealthy, or network rules block discovery.
Fix: Compare client and silo clustering configuration, inspect membership, gateway endpoints, DNS, identity, ports, and cluster logs.
A grain call times out
Likely cause: The grain has a long or blocked turn, a call cycle, a slow dependency, a hot identity, or a failed silo is being detected.
Fix: Trace the call chain, inspect turn queue and silo load, remove blocking work, break cycles, bound dependencies, and review placement.
State disappears after restart
Likely cause: The grain used activation memory, wrote to the wrong provider, failed before WriteStateAsync completed, or storage configuration differs.
Fix: Use the intended persistent state provider, verify write success and keys, test reactivation, and inspect provider access and errors.
A reminder or stream handler runs twice
Likely cause: Delivery is retried after failure or ownership changes and the handler is not idempotent.
Fix: Use stable operation identity, store completion with the business effect, and test redelivery and recovery semantics.
One grain becomes a throughput bottleneck
Likely cause: Its key owns too much unrelated state or all callers serialize through one activation.
Fix: Measure queue time, partition the domain by stable child keys, move stateless work out, or redesign aggregation consistency.
Rolling upgrade produces serialization errors
Likely cause: Grain contracts, serializer field IDs, or state types changed incompatibly while versions coexist.
Fix: Restore compatibility, use additive contracts and stable field IDs, migrate state deliberately, and test the mixed-version window.
Best practices
- Keep grain calls single-purpose and short-lived; a grain is a unit of state and behavior, not a place for long synchronous blocking work.
- Persist only the state a grain actually needs to recover, and choose a storage provider that matches your durability requirements.
- Design grain identities deliberately—they determine how work and state are partitioned across the cluster.
- Avoid grain-to-grain call chains that form cycles; they can deadlock or time out under turn-based execution.
- Treat every grain call as a fallible distributed call and make retryable operations idempotent.
- Use durable reminders only when scheduling must survive activation loss; use timers for activation-local work.
- Keep serializer field IDs stable and evolve contracts additively across rolling upgrades.
- Observe hot identities and provider latency before adding silos or changing placement.
Production checklist
- Grain candidates have stable keys, cohesive behavior, bounded state, and a documented reason for actor ownership.
- Interfaces, serializer field IDs, state schemas, reminders, streams, and deprecation rules are version-compatible.
- Production cluster membership, gateways, cluster and service IDs, placement, storage, reminders, and stream providers are configured and tested.
- External authorization, workload identity, least privilege, network restrictions, encryption, validation, redaction, and audits are enforced.
- Grain turns are async, bounded, nonblocking, cycle-aware, and explicit about reentrancy and idempotency.
- Metrics, traces, logs, health, membership, provider telemetry, hot-grain detection, dashboards, alerts, and runbooks are operational.
- Multi-silo load, failure, recovery, provider outage, duplicate delivery, rolling upgrade, backup, and restore tests pass.
- Deployments preserve capacity headroom, compatibility, graceful shutdown, rollback, and disaster-recovery objectives.
Common interview questions
What does 'virtual actor' mean in Orleans, and why does it matter?
A grain logically always exists at its identity, whether or not it's currently activated in memory; callers never create or destroy it explicitly, and the runtime transparently activates, deactivates, and relocates it, which removes a whole class of lifecycle and placement code the application would otherwise have to write.
How does Orleans avoid the need for locks inside a grain?
Each grain processes incoming calls one at a time, single-threaded, so there's never concurrent access to a grain's own state from within—concurrency exists between grains, not within one.
What happens to a grain's in-memory state if the silo hosting it fails?
The in-memory activation is lost, but if the grain persists its state through a storage provider, Orleans can reactivate it—with that persisted state restored—on another silo when the next call arrives.
What is the difference between an Orleans timer and reminder?
A timer belongs to the current activation and disappears with it. A reminder is a durable registration that can trigger future work and reactivate the grain.
Can a grain process more than one call at a time?
Normally it executes one turn at a time. Reentrancy and interleaving controls can allow other calls during awaits, so invariants must be reviewed before enabling them.
How do you scale a hot grain?
First reduce or bound its work. If one identity owns too much state, partition the domain into stable child grains or move stateless computation out; adding silos alone does not parallelize one single-activation key.
Dedicated GitHub sample
Clone, run, test, and modify the focused implementation created for this guide.
Orleans Shopping Cart
A .NET 10 and Orleans 10.2 API demonstrating stable grain identity, turn-based cart ownership, localhost clustering, bounded commands, health, focused tests, and production persistence infrastructure.
- Run
dotnet run --project src/OrleansShoppingCart- Test
dotnet test OrleansShoppingCart.slnx