Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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: Stream delivery, ordering, replay, and recovery
description: Design Orleans streaming consumers for provider-specific delivery, ordering, replay, and failure behavior.
ms.date: 08/18/2026
ms.date: 08/24/2026
ms.topic: concept-article
---

Expand Down Expand Up @@ -51,6 +51,8 @@ A rewindable provider can start or resume a subscription from a provider sequenc
- Event Hubs and Redis Streams are rewindable over retained external data.
- Azure Queue, Amazon SQS, ADO.NET, and NATS JetStream providers aren't rewindable.

Explicit subscriptions can resume from retained positions according to the provider's token semantics. An implicit subscription accepts a recovery token when an activation attaches its observer, then advances monotonically for that attachment. Once a delivery call completes successfully, resuming the active implicit handle with a sequence token throws <xref:System.InvalidOperationException>; passing `null` replaces the observer at its current position.

See the [provider matrix](stream-providers.md#provider-matrix) for provider capabilities.

## Recovery checklist
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
title: Orleans streaming APIs
description: Work with stream identities, producers, consumers, and explicit or implicit subscriptions in Orleans.
ms.date: 08/19/2026
ms.date: 08/24/2026
ms.topic: concept-article
---

Expand Down Expand Up @@ -92,6 +92,8 @@ Use an implicit subscription when a stream item should activate a grain determin

<xref:Orleans.ImplicitStreamSubscriptionAttribute> selects stream namespaces. For each matching grain type, Orleans maps the stream key to the grain key. Implementing <xref:Orleans.Streams.Core.IStreamSubscriptionObserver> lets Orleans supply the implicit handle; call `ResumeAsync` once to attach processing logic.

An implicit subscription advances monotonically while its observer remains attached. After a delivery call completes successfully, `ResumeAsync` accepts `null` to replace the observer and rejects sequence tokens which would reposition that active subscription. A newly activated grain can attach its newly supplied handle using a persisted recovery token. Use an explicit subscription when application logic intentionally repositions delivery or replays previously acknowledged events.

Implicit subscriptions are declared in grain metadata. They aren't created through <xref:Orleans.Streams.IAsyncObservable`1.SubscribeAsync*>, can't be individually removed at runtime, and don't support multiple subscriptions for the same grain binding.

## Clients
Expand Down
6 changes: 6 additions & 0 deletions src/Orleans.Streaming/Core/StreamSubscriptionHandle.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ public abstract class StreamSubscriptionHandle<T> : IEquatable<StreamSubscriptio
/// <returns>
/// The new stream subscription handle.
/// </returns>
/// <exception cref="InvalidOperationException">
/// The active implicit subscription has already completed a delivery and <paramref name="token"/> is non-null.
/// </exception>
public abstract Task<StreamSubscriptionHandle<T>> ResumeAsync(IAsyncObserver<T> observer, StreamSequenceToken? token = null);

/// <summary>
Expand All @@ -56,6 +59,9 @@ public abstract class StreamSubscriptionHandle<T> : IEquatable<StreamSubscriptio
/// <returns>
/// The new stream subscription handle.
/// </returns>
/// <exception cref="InvalidOperationException">
/// The active implicit subscription has already completed a delivery and <paramref name="token"/> is non-null.
/// </exception>
public abstract Task<StreamSubscriptionHandle<T>> ResumeAsync(IAsyncBatchObserver<T> observer, StreamSequenceToken? token = null);

/// <inheritdoc/>
Expand Down
11 changes: 10 additions & 1 deletion src/Orleans.Streaming/Internal/StreamConsumer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -150,12 +150,21 @@ private async Task<StreamSubscriptionHandle<T>> ResumeAsyncImpl(
if (token != null && !IsRewindable)
throw new ArgumentNullException(nameof(token), "Passing a non-null token to a non-rewindable IAsyncObservable.");

oldHandleImpl.ValidateResumeToken(token);

LogDebugResumeToken(token);
await BindExtensionLazy();

LogDebugResumeRendezvous(pubSub, myGrainReference, token);

StreamSubscriptionHandle<T> newHandle = myExtension!.SetObserver(oldHandleImpl.SubscriptionId, stream, observer, batchObserver, token, null);
StreamSubscriptionHandle<T> newHandle = myExtension!.SetObserver(
oldHandleImpl.SubscriptionId,
stream,
observer,
batchObserver,
token,
oldHandleImpl.FilterData,
handshakeState: token is null ? oldHandleImpl.SharedHandshake : null);

// On failure caller should be able to retry using the original handle, so invalidate old handle only if everything succeeded.
oldHandleImpl.Invalidate();
Expand Down
6 changes: 4 additions & 2 deletions src/Orleans.Streaming/Internal/StreamConsumerExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ internal StreamSubscriptionHandleImpl<T> SetObserver<T>(
IAsyncObserver<T>? observer,
IAsyncBatchObserver<T>? batchObserver,
StreamSequenceToken? token,
string? filterData)
string? filterData,
StreamSubscriptionHandleImpl<T>.SharedHandshakeState? handshakeState = null)
{
if (null == stream) throw new ArgumentNullException(nameof(stream));
if (IsStatelessWorker && token is not null)
Expand All @@ -78,7 +79,8 @@ internal StreamSubscriptionHandleImpl<T> SetObserver<T>(
stream,
token,
filterData,
disableHandshake: IsStatelessWorker);
disableHandshake: IsStatelessWorker,
handshakeState: handshakeState);
allStreamObservers[subscriptionId] = handle;
return handle;
}
Expand Down
45 changes: 42 additions & 3 deletions src/Orleans.Streaming/Internal/StreamSubscriptionHandleImpl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,19 @@ internal class StreamSubscriptionHandleImpl<T> : StreamSubscriptionHandle<T>, IS
[NonSerialized]
private IAsyncBatchObserver<T>? batchObserver;
[NonSerialized]
private StreamHandshakeToken? expectedToken;
private SharedHandshakeState? handshakeState;
private StreamHandshakeToken? expectedToken
{
get => SharedHandshake.Token;
set => SharedHandshake.Token = value;
}

internal bool IsValid { get { return streamImpl != null; } }
internal GuidId SubscriptionId { get { return subscriptionId; } }
internal bool IsRewindable { get { return isRewindable; } }
internal string? FilterData { get { return filterData; } }
internal bool HasObserver { get { return observer is not null || batchObserver is not null; } }
internal SharedHandshakeState SharedHandshake => handshakeState ??= new();

public override string ProviderName { get { return this.streamImpl!.ProviderName; } }
public override StreamId StreamId { get { return streamImpl!.StreamId; } }
Expand All @@ -57,17 +66,19 @@ public StreamSubscriptionHandleImpl(
StreamImpl<T> streamImpl,
StreamSequenceToken? token,
string? filterData,
bool disableHandshake = false)
bool disableHandshake = false,
SharedHandshakeState? handshakeState = null)
{
this.subscriptionId = subscriptionId ?? throw new ArgumentNullException(nameof(subscriptionId));
this.observer = observer;
this.batchObserver = batchObserver;
this.streamImpl = streamImpl ?? throw new ArgumentNullException(nameof(streamImpl));
this.filterData = filterData;
this.handshakeState = handshakeState;
this.isRewindable = streamImpl.IsRewindable && !disableHandshake;
if (IsRewindable)
{
expectedToken = StreamHandshakeToken.CreateStartToken(token);
expectedToken ??= StreamHandshakeToken.CreateStartToken(token);
}
}

Expand All @@ -83,6 +94,34 @@ public void Invalidate()
return expectedToken;
}

internal void ValidateResumeToken(StreamSequenceToken? token)
=> ValidateResumeToken(subscriptionId, HasObserver, expectedToken, token);

internal static void ValidateResumeToken(
GuidId subscriptionId,
bool hasObserver,
StreamHandshakeToken? expectedToken,
StreamSequenceToken? token)
{
// A DeliveryToken is recorded only after the complete delivery call succeeds.
if (token is null
|| !hasObserver
|| !SubscriptionMarker.IsImplicitSubscription(subscriptionId.Guid)
|| expectedToken is not DeliveryToken deliveryToken)
{
return;
}

throw new InvalidOperationException(
$"An active implicit stream subscription cannot resume from token {token} because it has already completed delivery through token {deliveryToken.Token}. "
+ "Implicit subscriptions advance monotonically within an activation.");
}

internal sealed class SharedHandshakeState
{
public StreamHandshakeToken? Token { get; set; }
}

public override Task UnsubscribeAsync()
{
if (!IsValid) throw new InvalidOperationException("Handle is no longer valid. It has been used to unsubscribe or resume.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ public interface IImplicitSubscriptionCounterGrain : IGrainWithGuidKey
Task Deactivate();

Task DeactivateOnEvent(bool deactivate);

Task ReplaceObserverOnNextEvent();

Task RewindToFirstToken();
}

public interface IFastImplicitSubscriptionCounterGrain : IImplicitSubscriptionCounterGrain
Expand Down
63 changes: 45 additions & 18 deletions test/Grains/TestGrains/ImplicitSubscriptionCounterGrain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ public class ImplicitSubscriptionCounterGrain : Grain<ImplicitSubscriptionCounte
{
private readonly ILogger logger;
private bool deactivateOnEvent;
private bool replaceObserverOnEvent;
private StreamSubscriptionHandle<byte[]>? streamHandle;

[GenerateSerializer]
public class MyState
Expand All @@ -20,6 +22,8 @@ public class MyState
public int ErrorCounter { get; set; }
[Id(2)]
public StreamSequenceToken? Token { get; set; }
[Id(3)]
public StreamSequenceToken? FirstToken { get; set; }
}

public ImplicitSubscriptionCounterGrain(ILoggerFactory loggerFactory)
Expand Down Expand Up @@ -57,35 +61,58 @@ public async Task OnSubscribed(IStreamSubscriptionHandleFactory handleFactory)
{
this.logger.LogInformation($"OnSubscribed: {handleFactory.ProviderName}/{handleFactory.StreamId}");

await handleFactory.Create<byte[]>().ResumeAsync(OnNext, OnError, OnCompleted, this.State.Token);
this.streamHandle = await handleFactory.Create<byte[]>().ResumeAsync(OnNext, OnError, OnCompleted, this.State.Token);
}

public Task DeactivateOnEvent(bool deactivate)
{
this.deactivateOnEvent = deactivate;
return Task.CompletedTask;
}

public Task ReplaceObserverOnNextEvent()
{
this.replaceObserverOnEvent = true;
return Task.CompletedTask;
}

async Task OnNext(byte[] value, StreamSequenceToken? token)
public async Task RewindToFirstToken()
{
if (this.streamHandle is null || this.State.FirstToken is null)
{
this.logger.LogInformation("Received: [{Value} {Token}]", value, token);
this.State.EventCounter++;
this.State.Token = token;
await this.WriteStateAsync();
if (this.deactivateOnEvent)
{
this.DeactivateOnIdle();
}
throw new InvalidOperationException("The stream must deliver an event before it can rewind.");
}

async Task OnError(Exception ex)
this.streamHandle = await this.streamHandle.ResumeAsync(OnNext, OnError, OnCompleted, this.State.FirstToken);
}

private async Task OnNext(byte[] value, StreamSequenceToken? token)
{
this.logger.LogInformation("Received: [{Value} {Token}]", value, token);
this.State.EventCounter++;
this.State.Token = token;
this.State.FirstToken ??= token;
await this.WriteStateAsync();
if (this.replaceObserverOnEvent)
{
this.logger.LogError("Error: {Exception}", ex);
this.State.ErrorCounter++;
await this.WriteStateAsync();
this.replaceObserverOnEvent = false;
this.streamHandle = await this.streamHandle!.ResumeAsync(OnNext, OnError, OnCompleted);
}

Task OnCompleted() => Task.CompletedTask;
if (this.deactivateOnEvent)
{
this.DeactivateOnIdle();
}
}

public Task DeactivateOnEvent(bool deactivate)
private async Task OnError(Exception ex)
{
this.deactivateOnEvent = deactivate;
return Task.CompletedTask;
this.logger.LogError("Error: {Exception}", ex);
this.State.ErrorCounter++;
await this.WriteStateAsync();
}

private static Task OnCompleted() => Task.CompletedTask;
}

[ImplicitStreamSubscription("FastSlowImplicitSubscriptionCounterGrain")]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
using Microsoft.Extensions.Configuration;
using Orleans.Configuration;
using Orleans.Providers;
using Orleans.Runtime;
using Orleans.Streams;
using Orleans.TestingHost;
using Orleans.TestingHost.Utils;
using TestExtensions;
using UnitTests.GrainInterfaces;
using Xunit;

namespace Tester.StreamingTests
{
Expand Down Expand Up @@ -33,6 +39,94 @@ public override async ValueTask InitializeAsync()
await WaitForStreamProviderReadyAsync();
}

[Fact]
public async Task ActiveImplicitSubscriptionRejectsRewindAndContinuesForward()
{
using var observer = StreamingDiagnosticObserver.Create();
using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var streamProvider = this.Client.GetStreamProvider(StreamProviderName);
var key = Guid.NewGuid();
var stream = streamProvider.GetStream<byte[]>(nameof(IImplicitSubscriptionCounterGrain), key);
var grain = this.Client.GetGrain<IImplicitSubscriptionCounterGrain>(key);
var streamId = StreamId.Create(nameof(IImplicitSubscriptionCounterGrain), key);

for (var i = 0; i < 5; i++)
{
await stream.OnNextAsync([1]);
}

await observer.WaitForItemDeliveryCountAsync(streamId, 5, StreamProviderName, cancellation.Token);
await WaitForEventCount(5);
await observer.WaitForStreamInactiveAsync(streamId, StreamProviderName, cancellation.Token);

var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => grain.RewindToFirstToken());
Assert.Contains("Implicit subscriptions advance monotonically", exception.Message);

await stream.OnNextAsync([1]);
await observer.WaitForItemDeliveryCountAsync(streamId, 6, StreamProviderName, cancellation.Token);
await WaitForEventCount(6);
Assert.Equal(0, await grain.GetErrorCounter());

Task WaitForEventCount(int expected)
{
return TestingUtils.WaitUntilAsync(
async (lastTry, cancellationToken) =>
{
var actual = await grain.GetEventCounter(cancellationToken);
if (lastTry)
{
Assert.Equal(expected, actual);
}

return actual == expected;
},
TimeSpan.FromSeconds(30),
delayOnFail: TimeSpan.FromMilliseconds(100),
cancellationToken: cancellation.Token);
}
}

[Fact]
public async Task ObserverReplacementDuringFirstDeliveryPreservesRewindRejection()
{
using var observer = StreamingDiagnosticObserver.Create();
using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var streamProvider = this.Client.GetStreamProvider(StreamProviderName);
var key = Guid.NewGuid();
var stream = streamProvider.GetStream<byte[]>(nameof(IImplicitSubscriptionCounterGrain), key);
var grain = this.Client.GetGrain<IImplicitSubscriptionCounterGrain>(key);
var streamId = StreamId.Create(nameof(IImplicitSubscriptionCounterGrain), key);

await grain.ReplaceObserverOnNextEvent();
await stream.OnNextAsync([1]);
await observer.WaitForItemDeliveryCountAsync(streamId, 1, StreamProviderName, cancellation.Token);
await WaitForEventCount(1);

await Assert.ThrowsAsync<InvalidOperationException>(() => grain.RewindToFirstToken());

await stream.OnNextAsync([1]);
await observer.WaitForItemDeliveryCountAsync(streamId, 2, StreamProviderName, cancellation.Token);
await WaitForEventCount(2);

Task WaitForEventCount(int expected)
{
return TestingUtils.WaitUntilAsync(
async (lastTry, cancellationToken) =>
{
var actual = await grain.GetEventCounter(cancellationToken);
if (lastTry)
{
Assert.Equal(expected, actual);
}

return actual == expected;
},
TimeSpan.FromSeconds(30),
delayOnFail: TimeSpan.FromMilliseconds(100),
cancellationToken: cancellation.Token);
}
}

#region Configuration stuff
private class MySiloBuilderConfigurator : ISiloConfigurator
{
Expand Down
Loading
Loading