Skip to content
Merged
Show file tree
Hide file tree
Changes from 26 commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
aec5e64
feat(runtime): add RunRequestAsync
ReubenBond Oct 14, 2026
4139c42
fix(runtime): complete RunRequestAsync when call filters end the invo…
ReubenBond Oct 14, 2026
98d945f
fix(runtime): honor queue limits and late cancellation in RunRequestA…
ReubenBond Oct 14, 2026
15872b9
fix(runtime): admit requests atomically against the enqueued request …
ReubenBond Oct 15, 2026
260f3e5
fix(runtime): keep warning when cancellation masks a call filter failure
ReubenBond Oct 15, 2026
94d62a5
refactor(runtime): add RunRequestAsync options and share local reques…
ReubenBond Oct 15, 2026
dbbcb58
docs: add RunRequestAsync usage examples
ReubenBond Oct 15, 2026
e0290ad
refactor(runtime): add IGrainContext.ReceiveLocalRequest and LocalReq…
ReubenBond Oct 15, 2026
5bddd50
docs(runtime): scope RunRequestAsync behavior list to default options
ReubenBond Oct 15, 2026
1e37ad6
feat(runtime): add synchronous RunRequestAsync overloads
ReubenBond Oct 15, 2026
843dbad
refactor(runtime): remove RunRequestAsync methodName parameter
ReubenBond Oct 15, 2026
97fe83f
fix(runtime): complete rejected local requests outside the activation…
ReubenBond Oct 15, 2026
fee59da
fix(runtime): keep caller grain cancellation tokens on local requests
ReubenBond Oct 15, 2026
05916de
Revert "fix(runtime): keep caller grain cancellation tokens on local …
ReubenBond Oct 15, 2026
1c7acde
refactor(runtime): make ILocalRequest the local request and its compl…
ReubenBond Oct 15, 2026
353f88b
refactor(runtime): make ILocalRequest.Complete void and remove Enforc…
ReubenBond Oct 15, 2026
a6479b9
refactor(runtime): leave the local request interface type unset
ReubenBond Oct 15, 2026
3083802
chore(runtime): assert local-only messages never reach responses or r…
ReubenBond Oct 16, 2026
bfda2f0
fix(runtime): isolate local request completion failures and dispose a…
ReubenBond Oct 16, 2026
eb55c18
fix(runtime): log timer tick failures until the timer is disposed
ReubenBond Oct 16, 2026
e7e8fec
docs(runtime): explain LocalRequestOptions keep-alive storage
ReubenBond Oct 16, 2026
d688e34
docs(runtime): keep KeepAlive summary concise
ReubenBond Oct 16, 2026
a0876f6
test(runtime): deliver late stateless worker requests as local requests
ReubenBond Oct 16, 2026
a668fd7
refactor(runtime): reject and forward unprocessed requests outside th…
ReubenBond Oct 16, 2026
a5ef07c
refactor(runtime): decide invalid request handling at the call site
ReubenBond Oct 16, 2026
4f14396
refactor(runtime): rename invalid activation dequeue to TryDequeueUnp…
ReubenBond Oct 16, 2026
38d1664
refactor(runtime): simplify rejecting and forwarding unprocessable re…
ReubenBond Oct 16, 2026
0818b63
refactor(runtime): return unprocessable requests directly
ReubenBond Oct 16, 2026
c05c006
refactor(runtime): complete and reject local requests from their mess…
ReubenBond Oct 16, 2026
24c8a59
fix(runtime): pass local request responses by reference
ReubenBond Oct 16, 2026
01549a1
fix(runtime): give local requests a constant interface type
ReubenBond Oct 16, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
title: External tasks and grain scheduling
description: Safely use asynchronous libraries, CPU work, and blocking APIs from Orleans grains.
ms.date: 08/21/2026
ms.date: 10/15/2026
ms.topic: concept-article
---

Expand Down Expand Up @@ -41,6 +41,8 @@ Don't use `ConfigureAwait(false)` directly in grain methods. It can resume the c
If an advanced integration passes an async delegate to <xref:System.Threading.Tasks.TaskFactory.StartNew*>, unwrap the nested task:

:::code language="csharp" source="../snippets/compiled/Grains/GeneralSnippets.cs" id="start_async_worker":::
To apply the result of a background callback to grain state, use <xref:Orleans.GrainBaseExtensions.RunRequestAsync*>. It runs the callback as a request on the activation. See [Run background work as a grain request](request-scheduling.md#run-background-work-as-a-grain-request).

Keep background work under an observed runtime mechanism. Use [grain timers](timers.md), [reminders](reminders.md), a durable job abstraction, or a hosted service according to the required lifetime and reliability.

## Reentrancy still applies
Expand Down
32 changes: 31 additions & 1 deletion docs/site/src/content/docs/grains/request-scheduling.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
title: Grain request scheduling
description: Understand Orleans turn-based execution, interleaving, and reentrancy.
ms.date: 08/02/2026
ms.date: 10/15/2026
ms.topic: concept-article
---

Expand Down Expand Up @@ -62,4 +62,34 @@ The scope permits callbacks associated with that call chain until it is disposed

Grain timer callbacks participate in scheduling. Callbacks don't interleave by default; configure `GrainTimerCreationOptions.Interleave` when intentional.

To run work from another thread under the activation's scheduling, see [Run background work as a grain request](#run-background-work-as-a-grain-request).

Use <xref:System.Threading.Tasks.Task.Run*> only to isolate unavoidable synchronous blocking or CPU work from the Orleans scheduler. Don't access grain state from the thread-pool delegate. Await it and update grain state after execution resumes on the activation scheduler. See [External tasks and grains](external-tasks-and-grains.md).

## Run background work as a grain request

<xref:Orleans.GrainBaseExtensions.RunRequestAsync*> runs a callback as a request on the activation. Call it from any thread, such as a stream, messaging, or library callback, to apply results to grain state under the same scheduling as grain calls:

:::code language="csharp" source="../snippets/compiled/Grains/RequestsAndVersioningSnippets.cs" id="run_request_from_callback":::
With the default <xref:Orleans.Runtime.LocalRequestOptions>, the request:

- Follows the grain's reentrancy rules and queues behind the current request on a non-reentrant grain.
- Passes through incoming grain call filters, which observe it as `IGrainRequestInvoker.RunRequestAsync` with no arguments.
- Starts a new call chain. <xref:Orleans.Runtime.RequestContext> values from the calling thread don't flow into the callback.
- Restarts the activation's idle collection period.
- Bypasses <xref:Orleans.Configuration.SiloMessagingOptions.MaxEnqueuedRequestsHardLimit>.

The callback can be synchronous, as in this example, or return a `Task` or `Task<TResult>`. The returned task completes with the callback's result or exception. The callback receives the cancellation token passed to `RunRequestAsync`, and cancelling it while the request is queued cancels the request. If the activation deactivates before the request runs, the task faults with <xref:Orleans.Runtime.OrleansMessageRejectionException>.

Pass the grain and other values through the `state` argument and use a `static` lambda, so the call doesn't allocate a closure. On a non-reentrant grain, awaiting the returned task from another request on the same activation deadlocks, because the queued request waits for the current one to complete.

### Configure the request

Pass <xref:Orleans.Runtime.LocalRequestOptions> to change how the request is scheduled. Set <xref:Orleans.Runtime.LocalRequestOptions.KeepAlive> to `false` for frequent background work that shouldn't keep an otherwise idle activation in memory. Set <xref:Orleans.Runtime.LocalRequestOptions.Interleave> to `true` to run the request between the turns of other requests, as with an `[AlwaysInterleave]` method:

:::code language="csharp" source="../snippets/compiled/Grains/RequestsAndVersioningSnippets.cs" id="run_request_options":::
### Deliver a custom request

<xref:Orleans.Runtime.IGrainContext.ReceiveLocalRequest*> delivers an <xref:Orleans.Runtime.ILocalRequest> to the activation with the same scheduling as `RunRequestAsync`. Call filters, logs, and traces observe the request's own interface name, method name, and arguments, so a custom request can describe the work to them. The activation passes the request's response to <xref:Orleans.Runtime.ILocalRequest.Complete*>, or an exception if the activation rejects the request. The request reports that outcome, including any failure, to its observers:

:::code language="csharp" source="../snippets/compiled/Grains/RequestsAndVersioningSnippets.cs" id="receive_local_request":::
4 changes: 3 additions & 1 deletion docs/site/src/content/docs/grains/timers.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
title: Grain timers
description: Schedule activation-scoped periodic work as Orleans grain turns.
ms.date: 08/21/2026
ms.date: 10/15/2026
ms.topic: concept-article
---

Expand All @@ -11,6 +11,8 @@ A grain timer schedules periodic work for one grain activation. Each callback ex

Use a grain timer for frequent work whose lifetime and state belong to the current activation. Use a [reminder](reminders.md) when the schedule belongs to the logical grain and must survive activation or cluster lifecycle changes.

To run a callback once as a grain request, use <xref:Orleans.GrainBaseExtensions.RunRequestAsync*>. See [Request scheduling](request-scheduling.md#run-background-work-as-a-grain-request).

## Register a grain timer

Register timers with <xref:Orleans.GrainBaseExtensions.RegisterGrainTimer*>. <xref:Orleans.Grain.RegisterTimer*> is obsolete.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -225,3 +225,158 @@ public async Task JoinRoom(string roomName)
// </call_chain_reentrancy>
}
}

namespace Documentation.Grains.RequestScheduling.BackgroundWork
{
public interface IPriceFeed
{
IDisposable Subscribe(string symbol, Func<decimal, CancellationToken, Task> onPrice);
}

public interface IQuoteGrain : IGrainWithStringKey
{
ValueTask<decimal> GetPrice();
}

// <run_request_from_callback>
public sealed class QuoteGrain(IPriceFeed feed) : Grain, IQuoteGrain
{
private IDisposable? _subscription;
private decimal _price;

public override Task OnActivateAsync(CancellationToken cancellationToken)
{
// The feed invokes OnPrice on its own threads.
_subscription = feed.Subscribe(this.GetPrimaryKeyString(), OnPrice);
return Task.CompletedTask;
}

public override Task OnDeactivateAsync(DeactivationReason reason, CancellationToken cancellationToken)
{
_subscription?.Dispose();
return Task.CompletedTask;
}

public ValueTask<decimal> GetPrice() => ValueTask.FromResult(_price);

// Runs the update as a request on this activation, where it can safely access grain state.
private Task OnPrice(decimal price, CancellationToken cancellationToken) =>
this.RunRequestAsync(
static (state, _) => state.Grain._price = state.Price,
(Grain: this, Price: price),
cancellationToken);
}
// </run_request_from_callback>

public interface IConnectionMonitor
{
IDisposable Subscribe(string sessionId, Func<DateTimeOffset, CancellationToken, Task> onHeartbeat);
}

public interface ISessionGrain : IGrainWithStringKey
{
ValueTask<DateTimeOffset> GetLastSeen();
}

public sealed class SessionGrain(IConnectionMonitor monitor) : Grain, ISessionGrain
{
private IDisposable? _subscription;
private DateTimeOffset _lastSeen;

public override Task OnActivateAsync(CancellationToken cancellationToken)
{
_subscription = monitor.Subscribe(this.GetPrimaryKeyString(), OnHeartbeat);
return Task.CompletedTask;
}

public override Task OnDeactivateAsync(DeactivationReason reason, CancellationToken cancellationToken)
{
_subscription?.Dispose();
return Task.CompletedTask;
}

public ValueTask<DateTimeOffset> GetLastSeen() => ValueTask.FromResult(_lastSeen);

// <run_request_options>
// Heartbeats don't extend the activation's lifetime, and they run between the turns of other requests.
private Task OnHeartbeat(DateTimeOffset timestamp, CancellationToken cancellationToken) =>
this.RunRequestAsync(
static (state, _) => state.Grain._lastSeen = state.Timestamp,
(Grain: this, Timestamp: timestamp),
new LocalRequestOptions { KeepAlive = false, Interleave = true },
cancellationToken);
// </run_request_options>
}

public interface IIngestGrain : IGrainWithStringKey
{
ValueTask<int> GetCount();
}

public sealed class IngestGrain : Grain, IIngestGrain
{
private int _count;

public ValueTask<int> GetCount() => ValueTask.FromResult(_count);

internal void Increment() => _count++;
}

// <receive_local_request>
// A request which increments IngestGrain's counter. Call filters observe it as IIngestRequests.Increment.
internal sealed class IncrementRequest : Request, ILocalRequest
{
private readonly TaskCompletionSource _completion = new(TaskCreationOptions.RunContinuationsAsynchronously);
private IngestGrain? _grain;

public Task Completion => _completion.Task;

// Receives the outcome once the request and its call filters complete, or when the activation rejects the request.
// The task keeps the first outcome.
public void Complete(Response response)
{
if (response.Exception is { } exception)
{
_completion.TrySetException(exception);
}
else
{
_completion.TrySetResult();
}
}

public override object GetTarget() => _grain!;

public override void SetTarget(ITargetHolder holder) => _grain = (IngestGrain?)holder.GetTarget();

protected override ValueTask InvokeInner()
{
_grain!.Increment();
return default;
}

public override string GetInterfaceName() => "IIngestRequests";

public override string GetMethodName() => "Increment";

public override string GetActivityName() => "IIngestRequests/Increment";

public override Type GetInterfaceType() => typeof(IIngestGrain);

public override System.Reflection.MethodInfo GetMethod() => typeof(IIngestGrain).GetMethod(nameof(IIngestGrain.GetCount))!;

public override void Dispose() { }
}

public static class IngestRequests
{
// Delivers the request to the activation and returns a task which completes with the request's outcome.
public static Task Increment(IGrainContext activation)
{
var request = new IncrementRequest();
activation.ReceiveLocalRequest(request, default);
return request.Completion;
}
}
// </receive_local_request>
}
Loading
Loading