Skip to content

API Reference

Quick reference for all public modules, types, and functions in Orleans.FSharp.

Quick reference for all public modules, types, and functions in Orleans.FSharp.


TypeDescription
GrainDefinition<'State, 'Message>Immutable record describing a grain’s behavior
GrainContextProvides access to grain factory, service provider, and named states
GrainRef<'TInterface, 'TKey>Type-safe reference to an Orleans grain
CompoundGuidKeyCompound key: GUID + string extension
CompoundIntKeyCompound key: int64 + string extension
PlacementStrategyDU: Default, PreferLocal, Random, HashBased, ActivationCountBased, ResourceOptimized, SiloRoleBased, Custom
AdditionalStateSpecNamed additional persistent state specification
Immutable<'T>Alias for Orleans.Concurrency.Immutable<'T> for zero-copy passing
FSharpIncomingFilterWraps an F# function as IIncomingGrainCallFilter
FSharpOutgoingFilterWraps an F# function as IOutgoingGrainCallFilter
Migration<'TOld, 'TNew>State migration definition from one version to another
AssemblyMarkerMarker type for assembly discovery
CEBuilderDescription
grain { }GrainBuilderDefine grain behavior declaratively
KeywordHandler SignatureDescription
defaultState'StateInitial state value
handle'State -> 'Msg -> Task<'State * obj>Register handler with manual box
handleState'State -> 'Msg -> Task<'State>Handler returning only state (no result value)
handleTyped'State -> 'Msg -> Task<'State * 'R>Handler with typed result — no box needed
handleWithContextGrainContext -> 'State -> 'Msg -> Task<'State * obj>Handler with DI/grain-to-grain access
handleStateWithContextGrainContext -> 'State -> 'Msg -> Task<'State>Context + state-only return
handleTypedWithContextGrainContext -> 'State -> 'Msg -> Task<'State * 'R>Context + typed result
handleCancellable'State -> 'Msg -> CancellationToken -> Task<'State * obj>Cancellation, manual box
handleStateCancellable'State -> 'Msg -> CancellationToken -> Task<'State>Cancellation, state-only return
handleTypedCancellable'State -> 'Msg -> CancellationToken -> Task<'State * 'R>Cancellation, typed result
handleWithContextCancellableGrainContext -> 'State -> 'Msg -> CancellationToken -> Task<'State * obj>Context + cancellation
handleStateWithContextCancellableGrainContext -> 'State -> 'Msg -> CancellationToken -> Task<'State>Context + cancellation, state-only return
handleTypedWithContextCancellableGrainContext -> 'State -> 'Msg -> CancellationToken -> Task<'State * 'R>Context + cancellation, typed result
persiststringName of the storage provider for state
onActivate'State -> Task<'State>Hook on grain activation; may modify state
onDeactivate'State -> Task<unit>Hook on grain deactivation; cleanup
onReminderstring * ('State -> string -> TickStatus -> Task<'State>)Named reminder with stateful handler
onTimerstring * TimeSpan * TimeSpan * ('State -> Task<'State>)Declarative timer: name, dueTime, period, handler
reentrantAllow concurrent message processing
statelessWorkerAllow multiple activations per silo

See Grain Definition guide for the full keyword list.

FunctionSignatureDescription
getService<'T>GrainContext -> 'TResolve a DI service
getState<'T>GrainContext -> string -> IPersistentState<'T>Get named additional persistent state
getGrainByString<'T>GrainContext -> string -> GrainRef<'T, string>Get grain ref by string key
getGrainByGuid<'T>GrainContext -> Guid -> GrainRef<'T, Guid>Get grain ref by GUID key
getGrainByInt64<'T>GrainContext -> int64 -> GrainRef<'T, int64>Get grain ref by int64 key
getGrainByGuidCompound<'T>GrainContext -> Guid -> string -> GrainRef<'T, CompoundGuidKey>Compound GUID key
getGrainByIntCompound<'T>GrainContext -> int64 -> string -> GrainRef<'T, CompoundIntKey>Compound int64 key
deactivateOnIdleGrainContext -> unitRequest grain deactivation when idle
delayDeactivationGrainContext -> TimeSpan -> unitDelay grain deactivation
grainIdGrainContext -> GrainIdGet the GrainId
primaryKeyStringGrainContext -> stringGet string primary key
primaryKeyGuidGrainContext -> GuidGet Guid primary key
primaryKeyInt64GrainContext -> int64Get int64 primary key
emptyGrainContextEmpty context for unit tests (all fields null/None)

Helpers for the behavior pattern — grains whose state includes a phase discriminated union.

FunctionSignatureDescription
run('S -> 'M -> Task<BehaviorResult<'S>>) -> 'S -> 'M -> Task<'S>Adapter for handleState: unwraps result, Stop returns original state
runWithContext(GrainContext -> 'S -> 'M -> Task<BehaviorResult<'S>>) -> GrainContext -> 'S -> 'M -> Task<'S>Adapter for handleStateWithContext: Stop calls DeactivateOnIdle
unwrap'S -> BehaviorResult<'S> -> 'SExtract state from Stay/Become; fallback to original for Stop
map('S -> 'S) -> BehaviorResult<'S> -> BehaviorResult<'S>Map over state inside a BehaviorResult
isTransitionBehaviorResult<'S> -> boolTrue if result is Become
isStoppedBehaviorResult<'S> -> boolTrue if result is Stop
toHandlerResult'S -> BehaviorResult<'S> -> 'S * objConvert to state * obj for use with raw handle
FunctionSignatureDescription
hasAnyHandlerGrainDefinition -> boolTrue if any handler is registered
getHandlerGrainDefinition -> 'State -> 'Message -> Task<'State * obj>Get plain handler
getContextHandlerGrainDefinition -> GrainContext -> 'State -> 'Message -> Task<'State * obj>Get context-aware handler
getCancellableContextHandlerGrainDefinition -> GrainContext -> 'State -> 'Message -> CT -> Task<'State * obj>Get cancellable context handler
invokeHandlerGrainDefinition -> 'State -> 'Message -> Task<'State * obj>Invoke handler (C# interop)
invokeContextHandlerGrainDefinition -> GrainContext -> 'State -> 'Message -> Task<'State * obj>Invoke context handler (C# interop)
invokeCancellableContextHandlerGrainDefinition -> GrainContext -> 'State -> 'Message -> CT -> Task<'State * obj>Invoke cancellable (C# interop)
invokeOnActivateGrainDefinition -> 'State -> Task<'State>Run activation hook directly
invokeOnDeactivateGrainDefinition -> 'State -> TaskRun deactivation hook directly
FunctionSignatureDescription
ofString<'T>IGrainFactory -> string -> GrainRef<'T, string>Create ref by string key
ofGuid<'T>IGrainFactory -> Guid -> GrainRef<'T, Guid>Create ref by GUID key
ofInt64<'T>IGrainFactory -> int64 -> GrainRef<'T, int64>Create ref by int64 key
ofGuidCompound<'T>IGrainFactory -> Guid -> string -> GrainRef<'T, CompoundGuidKey>Compound GUID key
ofIntCompound<'T>IGrainFactory -> int64 -> string -> GrainRef<'T, CompoundIntKey>Compound int64 key
invokeGrainRef -> ('T -> Task<'R>) -> Task<'R>Call a grain method
invokeOneWayGrainRef -> ('T -> Task) -> TaskFire-and-forget call
invokeWithTimeoutGrainRef -> TimeSpan -> ('T -> Task<'R>) -> Task<'R>Call with timeout
unwrapGrainRef -> 'TGet the underlying grain proxy
keyGrainRef -> 'TKeyGet the primary key
FunctionSignatureDescription
incoming(IIncomingGrainCallContext -> Task<unit>) -> IIncomingGrainCallFilterCreate incoming filter
outgoing(IOutgoingGrainCallContext -> Task<unit>) -> IOutgoingGrainCallFilterCreate outgoing filter
incomingWithAroundbefore -> after -> IIncomingGrainCallFilterBefore/after incoming filter
outgoingWithAroundbefore -> after -> IOutgoingGrainCallFilterBefore/after outgoing filter
FunctionSignatureDescription
methodNameIIncomingGrainCallContext -> stringGet called method name
interfaceTypeIIncomingGrainCallContext -> TypeGet grain interface type
grainInstanceIIncomingGrainCallContext -> obj optionGet grain instance
FunctionSignatureDescription
setstring -> obj -> unitSet a request context value
get<'T>string -> 'T optionGet a typed context value
getOrDefault<'T>string -> 'T -> 'TGet with fallback
removestring -> unitRemove a context value
withValue<'T>string -> obj -> (unit -> Task<'T>) -> Task<'T>Scoped context value
FunctionSignatureDescription
logInfoILogger -> string -> obj[] -> unitLog informational message
logWarningILogger -> string -> obj[] -> unitLog warning message
logErrorILogger -> exn -> string -> obj[] -> unitLog error with exception
logDebugILogger -> string -> obj[] -> unitLog debug message
withCorrelationstring -> (unit -> Task<'T>) -> Task<'T>Scoped correlation ID
currentCorrelationIdunit -> string optionGet current correlation ID
FunctionSignatureDescription
read<'T>IPersistentState<'T> -> Task<'T>Read from storage
write<'T>IPersistentState<'T> -> 'T -> Task<unit>Write to storage
clear<'T>IPersistentState<'T> -> Task<unit>Clear storage
current<'T>IPersistentState<'T> -> 'TGet in-memory value
FunctionSignatureDescription
registerGrain -> string -> TimeSpan -> TimeSpan -> Task<IGrainReminder>Register/update reminder
unregisterGrain -> string -> Task<unit>Unregister reminder
getGrain -> string -> Task<IGrainReminder option>Get reminder by name
FunctionSignatureDescription
registerGrain -> (CT -> Task<unit>) -> TimeSpan -> TimeSpan -> IGrainTimerRegister timer
registerWithState<'T>Grain -> ('T -> CT -> Task<unit>) -> 'T -> TimeSpan -> TimeSpan -> IGrainTimerTimer with state
FunctionSignatureDescription
createRef<'T>IGrainFactory -> 'T -> 'TCreate observer reference
deleteRef<'T>IGrainFactory -> 'T -> unitDelete observer reference
subscribe<'T>IGrainFactory -> 'T -> IDisposableSubscribe with auto-cleanup
Constant/FunctionValue/SignatureDescription
runtimeActivitySourceName"Microsoft.Orleans.Runtime"Runtime tracing source
applicationActivitySourceName"Microsoft.Orleans.Application"App tracing source
meterName"Microsoft.Orleans"Metrics meter name
activitySourceNamesstring listBoth source names
enableActivityPropagationISiloBuilder -> ISiloBuilderEnable tracing propagation
FunctionSignatureDescription
configureGracefulShutdownTimeSpan -> IHostBuilder -> IHostBuilderSet drain timeout
stopHostIHost -> Task<unit>Stop host gracefully
onShutdown(CT -> Task<unit>) -> IHostBuilder -> IHostBuilderRegister shutdown handler
FunctionSignatureDescription
migration<'TOld, 'TNew>int -> int -> ('TOld -> 'TNew) -> Migration<obj, obj>Define a migration
applyMigrations<'T>Migration list -> int -> obj -> 'TApply migration chain (throws on invalid chain)
tryApplyMigrations<'T>Migration list -> int -> obj -> Result<'T, string list>Validate and apply; returns Ok or Error with messages
validateMigration list -> string listValidate migration chain; empty list means valid
FunctionSignatureDescription
fsharpJsonOptionsJsonSerializerOptionsPre-configured F# JSON options
addFSharpConvertersJsonSerializerOptions -> JsonSerializerOptionsAdd F# converters
withConvertersJsonConverter list -> JsonSerializerOptionsCreate options with extras
FunctionSignatureDescription
taskResult'T -> Task<Result<'T, 'E>>Wrap as Ok
taskError'E -> Task<Result<'T, 'E>>Wrap as Error
taskMap('T -> 'U) -> Task<Result<'T, 'E>> -> Task<Result<'U, 'E>>Map Ok value
taskBind('T -> Task<Result<'U, 'E>>) -> Task<Result<'T, 'E>> -> Task<Result<'U, 'E>>Bind Ok value

Zero C# stubs. Register once with AddFSharpGrain, call from anywhere with FSharpGrain.ref.

TypeDescription
FSharpGrainHandle<'S,'M>Zero-alloc struct handle for a string-keyed grain
FSharpGrainGuidHandle<'S,'M>Zero-alloc struct handle for a GUID-keyed grain
FSharpGrainIntHandle<'S,'M>Zero-alloc struct handle for an int64-keyed grain
FunctionSignatureDescription
FSharpGrain.ref<'S,'M>IGrainFactory -> string -> FSharpGrainHandle<'S,'M>Handle for string-keyed grain
FSharpGrain.refGuid<'S,'M>IGrainFactory -> Guid -> FSharpGrainGuidHandle<'S,'M>Handle for GUID-keyed grain
FSharpGrain.refInt<'S,'M>IGrainFactory -> int64 -> FSharpGrainIntHandle<'S,'M>Handle for int64-keyed grain
FSharpGrain.send<'S,'M>'M -> FSharpGrainHandle<'S,'M> -> Task<'S>Send command, return typed state
FSharpGrain.post<'S,'M>'M -> FSharpGrainHandle<'S,'M> -> TaskFire-and-forget command
FSharpGrain.ask<'S,'M,'R>'M -> FSharpGrainHandle<'S,'M> -> Task<'R>Send command, return typed result (can differ from state)
FSharpGrain.sendGuid<'S,'M>'M -> FSharpGrainGuidHandle<'S,'M> -> Task<'S>Send to GUID-keyed grain
FSharpGrain.postGuid<'S,'M>'M -> FSharpGrainGuidHandle<'S,'M> -> TaskPost to GUID-keyed grain
FSharpGrain.askGuid<'S,'M,'R>'M -> FSharpGrainGuidHandle<'S,'M> -> Task<'R>Ask GUID-keyed grain for typed result
FSharpGrain.sendInt<'S,'M>'M -> FSharpGrainIntHandle<'S,'M> -> Task<'S>Send to int64-keyed grain
FSharpGrain.postInt<'S,'M>'M -> FSharpGrainIntHandle<'S,'M> -> TaskPost to int64-keyed grain
FSharpGrain.askInt<'S,'M,'R>'M -> FSharpGrainIntHandle<'S,'M> -> Task<'R>Ask int64-keyed grain for typed result

DI registration (call once per grain definition at silo startup):

// Automatically registers FSharpBinaryCodec (idempotent)
services.AddFSharpGrain<CounterState, CounterCommand>(counterGrain) |> ignore

GrainResilience — Polly v8 resilience wrappers

Section titled “GrainResilience — Polly v8 resilience wrappers”

Wrap any grain call in retry, circuit-breaker, and timeout strategies. See Resilience guide.

TypeDescription
ResilienceOptionsRecord: MaxRetryAttempts, RetryDelay, CircuitBreakerThreshold, CircuitBreakerDuration, Timeout
FunctionSignatureDescription
GrainResilience.defaultOptionsResilienceOptions3 retries · 1s delay · no circuit breaker · no timeout
GrainResilience.retry<'T>int -> TimeSpan -> (unit -> Task<'T>) -> Task<'T>Retry N times with delay
GrainResilience.withTimeout<'T>TimeSpan -> (unit -> Task<'T>) -> Task<'T>Enforce per-call deadline
GrainResilience.execute<'T>ResilienceOptions -> (unit -> Task<'T>) -> Task<'T>Full options: retry + circuit breaker + timeout
GrainResilience.buildPipeline<'T>ResilienceOptions -> ResiliencePipeline<'T>Build reusable Polly pipeline
GrainResilience.circuitBreakerint -> TimeSpan -> ResiliencePipelineShared circuit breaker (non-generic, long-lived)
FunctionSignatureDescription
GrainBatch.map<'TG,'TR>'TG seq -> ('TG -> Task<'TR>) -> Task<'TR list>Fan-out; fails if any call throws
GrainBatch.tryMap<'TG,'TR>'TG seq -> ('TG -> Task<'TR>) -> Task<Result<'TR, exn> list>Fan-out; captures individual failures
GrainBatch.aggregate<'TG,'TR,'TA>'TG seq -> ('TG -> Task<'TR>) -> ('TR list -> 'TA) -> Task<'TA>Fan-out then reduce
GrainBatch.iter<'TG>'TG seq -> ('TG -> Task) -> TaskConcurrent fire-and-forget; fails if any throws
GrainBatch.tryIter<'TG>'TG seq -> ('TG -> Task) -> Task<Result<unit, exn> list>Concurrent fire-and-forget; captures failures
GrainBatch.choose<'TG,'TR>'TG seq -> ('TG -> Task<'TR option>) -> Task<'TR list>Fan-out; filters out None results
GrainBatch.partition<'TG,'TR>'TG seq -> ('TG -> Task<'TR>) -> Task<'TR list * exn list>Fan-out; separates successes from failures

Tip: For 2–4 fixed grain calls, prefer the F# and! applicative keyword inside task {} — it is more ergonomic and compiles to the same Task.WhenAll pattern. Use GrainBatch when the number of grains is dynamic.

ModuleKey FunctionDescription
GrainExtension.getExtension<'T>IAddressable -> 'TGet grain extension reference
GrainServices.addGrainService<'T>ISiloBuilder -> ISiloBuilderRegister grain service
FSharpSerialization.addFSharpSerializationISiloBuilder -> ISiloBuilderOrleans native F# serializer
FSharpBinaryCodecRegistration.addToSerializerBuilderISerializerBuilder -> ISerializerBuilderRegister FSharpBinaryCodec manually
immutable'T -> Immutable<'T>Wrap as immutable
unwrapImmutableImmutable<'T> -> 'TUnwrap immutable

TypeDescription
StreamRef<'T>Typed reference to an Orleans stream
StreamSubscription<'T>Active stream subscription handle
FunctionSignatureDescription
getStream<'T>IStreamProvider -> string -> string -> StreamRef<'T>Get stream reference
publish<'T>StreamRef<'T> -> 'T -> Task<unit>Publish event
subscribe<'T>StreamRef<'T> -> ('T -> Task<unit>) -> Task<StreamSubscription<'T>>Subscribe with callback
asTaskSeq<'T>StreamRef<'T> -> TaskSeq<'T>Pull-based consumption
subscribeFrom<'T>StreamRef<'T> -> StreamSequenceToken -> ('T -> Task<unit>) -> Task<StreamSubscription<'T>>Subscribe from token
unsubscribe<'T>StreamSubscription<'T> -> Task<unit>Cancel subscription
getSubscriptions<'T>StreamRef<'T> -> Task<StreamSubscription<'T> list>List subscriptions
resumeAll<'T>StreamRef<'T> -> ('T -> Task<unit>) -> Task<unit>Resume all subscriptions
getSequenceToken<'T>StreamSubscription<'T> -> StreamSequenceToken optionGet current token

TypeDescription
BroadcastChannelRef<'T>Typed reference to a broadcast channel
FunctionSignatureDescription
getChannel<'T>IBroadcastChannelProvider -> string -> string -> BroadcastChannelRef<'T>Get channel reference
publish<'T>BroadcastChannelRef<'T> -> 'T -> Task<unit>Publish to all subscribers

FunctionSignatureDescription
addEventHubStreamsstring -> string -> string -> ISiloBuilder -> ISiloBuilderEvent Hubs provider
addAzureQueueStreamsstring -> string -> ISiloBuilder -> ISiloBuilderAzure Queue provider

TypeDescription
CompatibilityStrategyBackwardCompatible, StrictVersion, AllVersions
VersionSelectorStrategyAllCompatibleVersions, LatestVersion, MinimumVersion
FunctionSignatureDescription
compatibilityStrategyNameCompatibilityStrategy -> stringConvert to Orleans name
versionSelectorStrategyNameVersionSelectorStrategy -> stringConvert to Orleans name

TypeDescription
GrainDirectoryProviderDefault, Redis, AzureStorage, Custom
FunctionSignatureDescription
configureGrainDirectoryProvider -> ISiloBuilder -> ISiloBuilderConfigure grain directory

FunctionSignatureDescription
useKubernetesClusteringISiloBuilder -> ISiloBuilderEnable K8s clustering
useKubernetesClusteringWithNamespacestring -> ISiloBuilder -> ISiloBuilderK8s with custom namespace

TypeDescription
TransactionOptionCreate, Join, CreateOrJoin, Supported, NotAllowed, Suppress
FunctionSignatureDescription
read<'T>ITransactionalState<'T> -> Task<'T>Read transactional state
update<'T>('T -> 'T) -> ITransactionalState<'T> -> Task<unit>Update transactional state
performRead<'T, 'R>('T -> 'R) -> ITransactionalState<'T> -> Task<'R>Read with projection

TypeDescription
SiloConfigImmutable silo configuration record
ClientConfigImmutable client configuration record
ClusteringModeLocalhost, RedisClustering, AzureTableClustering, AdoNetClustering, CustomClustering
ClientClusteringModeLocalhost, StaticGateway, Custom
StorageProviderMemory, RedisStorage, AzureBlobStorage, AzureTableStorage, AdoNetStorage, CosmosStorage, DynamoDbStorage, CustomStorage
StreamProviderMemoryStream, PersistentStream, CustomStream
ReminderProviderMemoryReminder, RedisReminder, CustomReminder
TlsConfigTlsSubject, TlsCertificate, MutualTlsSubject, MutualTlsCertificate
DashboardConfigDashboardDefaults, DashboardWithOptions
TransactionalGrainDefinition<'State>Record of pure functions describing transactional grain behaviour (Deposit, Withdraw, GetBalance, CopyState)
AtmGrainDefinition<'TAccountGrain>Record containing a Transfer function for orchestrating cross-grain atomic transfers
FSharpTransactionalGrain<'State>Generic base class that bridges a TransactionalGrainDefinition to Orleans ACID transactions
FSharpAtmGrain<'TAccountGrain>Generic base class for ATM grains that create and coordinate transactions across multiple account grains
MethodSignatureDescription
AddFSharpTransactionalGrain<'State>IServiceCollection -> TransactionalGrainDefinition<'State> -> IServiceCollectionRegister a transactional grain definition as a singleton
AddFSharpAtmGrain<'TAccountGrain>IServiceCollection -> AtmGrainDefinition<'TAccountGrain> -> IServiceCollectionRegister an ATM grain definition as a singleton
CEBuilderDescription
siloConfig { }SiloConfigBuilderConfigure an Orleans silo
clientConfig { }ClientConfigBuilderConfigure an Orleans client
FunctionSignatureDescription
DefaultSiloConfigEmpty default configuration
validateSiloConfig -> string listValidate configuration
applyToSiloBuilderSiloConfig -> ISiloBuilder -> unitApply to silo builder
applyToHostSiloConfig -> HostApplicationBuilder -> unitApply to host
FunctionSignatureDescription
DefaultClientConfigEmpty default configuration
validateClientConfig -> string listValidate configuration
applyToBuilderClientConfig -> IClientBuilder -> unitApply to client builder
applyToHostClientConfig -> HostApplicationBuilder -> unitApply to host
buildClientConfig -> IHost * IClusterClientBuild and return client

TypeDescription
EventSourcedGrainDefinition<'State, 'Event, 'Command>Event-sourced grain specification
IEventStoreContext<'Event>Event store abstraction for C# CodeGen bridge
CEBuilderDescription
eventSourcedGrain { }EventSourcedGrainBuilderDefine event-sourced grain behavior
FunctionDescription
foldEvents def state eventsReplay events through apply to rebuild state
handleCommand def state cmdProcess command: returns (newState, events)
applyEvent def state eventApply a single event to state

ModuleKey FunctionsDescription
TestHarnesscreateTestCluster, getGrainByString, getGrainByInt64, getGrainByGuid, captureLogs, reset, disposeWrap TestCluster with log capture
GrainMockcreate, withGrain, withFSharpGrain, withFSharpGrainGuid, withFSharpGrainIntMock IGrainFactory for unit tests
GrainArbitraryforState<'T>, forCommands<'T>FsCheck Arbitrary generators for DUs
FsCheckHelpersstateMachineProperty, commandSequenceArbProperty-based testing helpers
LogCapturecreate, captureLogsIn-memory log capture for assertions

Compile-time checks for common Orleans + F# mistakes.

Rule CodeDescriptionFix
OF0001Warns on async { } usage in production codeUse task { } instead

Opt-out with [<AllowAsync>] attribute on a module or function.


Programmatic silo start/shutdown for F# scripts and REPL sessions.

FunctionSignatureDescription
Scripting.startOnPortsSiloConfig -> int -> int -> Task<SiloHandle>Start silo on given ports
Scripting.quickStartunit -> Task<SiloHandle>Start with defaults
Scripting.shutdownSiloHandle -> TaskStop the silo
Scripting.getGrain<'T>SiloHandle -> string -> 'TGet grain by string key
Scripting.getGrainByString<'T>SiloHandle -> string -> 'TAlias for getGrain