Repository navigation
Stop waiting on Redis operations when cancelled - #740
Conversation
StackExchange.Redis does not accept a CancellationToken, so a stuck command only ends when the AsyncTimeout (default 5s, checked once per heartbeat) expires. RedisFacade now uses Task.WaitAsync (with a net48 polyfill) so callers stop waiting as soon as their token or the facade's lifetime token is cancelled. The abandoned Redis task has its exceptions observed. SubscribeToChannel also stops waiting on cancellation, unsubscribes if the abandoned subscription completes later, and no longer logs a misleading "retrying" message when cancelled. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Remove the "when (!task.IsCompleted)" filters on the cancellation catches. The operation can complete between WaitAsync cancelling and the filter running, which left its exception unobserved, or in SubscribeToChannel left a successful subscription that was never unsubscribed. - ListLeftPopAsync and the delete in TryGetAndDeleteFromHash wait for Redis even when cancelled, so an item removed on the server is not lost. - Drop ExecuteSynchronously on the abandoned-subscription cleanup, and pass TaskScheduler.Default explicitly in IgnoreUnobservedExceptions. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| /// StackExchange.Redis does not accept a CancellationToken; commands only end when redis responds | ||
| /// or the AsyncTimeout (default 5s, checked once per heartbeat) expires. This lets callers stop | ||
| /// waiting as soon as they are cancelled. The redis command itself is abandoned, not cancelled, | ||
| /// so it may still take effect on the server. Destructive reads (e.g. pops) should not use this, |
There was a problem hiding this comment.
Destructive reads (e.g. pops) should not use this,
All comms with redis are not atomic. You can only know if it completed and you can't know if it failed (within a single call). The queue has to work on this assumption, throughout. So I don't think this comment is of value its just more of the same which could be called out again. e.g. "Cancellation may not stop the operation from occurring on Redis".
There was a problem hiding this comment.
Per above, maybe we shouldn't attempt to treat mutations differently
There was a problem hiding this comment.
Updated accordingly
| } | ||
|
|
||
| async Task<T> ExecuteWithRetry<T>(Func<Task<T>> operation, CancellationToken cancellationToken) | ||
| async Task<T> ExecuteWithRetry<T>(Func<Task<T>> operation, CancellationToken cancellationToken, bool stopWaitingOnCancellation = true) |
There was a problem hiding this comment.
Maybe we should make stopWaitingOnCancellation required. If we use this for a destructive read later, it will silently give up while waiting.
There was a problem hiding this comment.
Claude was keen on treating writes differently from reads, but per @LukeButters comment below and my "this is not a new problem" in the PR description, on second thought maybe we shouldn't do that at all, because you can always cancel just after the mutation has already taken place
There was a problem hiding this comment.
🤖 Claude: Resolved. Commit 6e6dc65 removed stopWaitingOnCancellation entirely. Every operation now stops waiting on cancellation, as agreed in this thread, so no carve-out can be forgotten later. The stale comments that still mention a carve-out (the WaitForOperation doc and the pop comment) are tracked in their own threads.
| public async Task<string?> ListLeftPopAsync(string key, CancellationToken cancellationToken) | ||
| { | ||
| var listKey = ToListKey(key); | ||
| // Wait for the pop even if cancelled: if it succeeds on the server, abandoning it would lose the item. |
There was a problem hiding this comment.
Claude found that waiting for the pop doesn't save the item.
TryRemoveNextItemFromQueue passes the popped ID to TryGetAndRemoveRequest with the same cancelled token, which throws straight away, so the request is still lost.
This isn't new, but the comment suggests otherwise.
We could either finish the read and delete under their own token, or reword the comment?
There was a problem hiding this comment.
I removed the comment, it was wrong.
// if it succeeds on the server, abandoning it would lose the item.
Claude is losing sight of the fact that if cancelled, there's almost certainly going to be a TaskCancelledException thrown, and we'd lose it regardless
There was a problem hiding this comment.
🤖 Claude-Round2: This comment ("Wait for the pop even if cancelled...") is still on line 434 at 6e6dc65, which matches origin/orion/redis-cancelling. The WaitForOperation doc comment on lines 181-182 is also unchanged: it still says "Destructive reads (e.g. pops) should not use this", but ListLeftPopAsync now uses it. Maybe the edit is local and not pushed yet? The PR description has the same problem: it still says ListLeftPopAsync and the delete in TryGetAndDeleteFromHash keep waiting for Redis.
There was a problem hiding this comment.
I think this is safe.
Failed comms with Redis is like Dr Pepper; we must remain agnostic about what happened.
Cancellation, I think, already means we don't know if it arrived or not.
And the queue must already work under that assumption.
So I think making all calls respect the CT is ok.
The downside here is that it probably adds CPU load to the queue by having all these extra tasks for every single call. I think this shouldn't matter, and instead we ought to make use of k8s scaling.
@LukeButters the CPU and memory overhead of task.Wait(CancellationToken) is basically zero. It's a small C# object with minimal state, we're talking 100 bytes or less, and they only exist while the network call is in place. Put it this way, serilog logging costs about 1000x what this would add |
| return await operation(); | ||
| return stopWaitingOnCancellation | ||
| ? await WaitForOperation(operation(), combinedToken) | ||
| : await operation(); |
There was a problem hiding this comment.
The operation will likely have a call to the lazy `Connection, which is a blocking operation. This will get hit the first time we use it, and could block this thread (it's one of the reasons for blocking Claude found for the original test flakiness).
We could replace the Lazy with a one-time async connect that callers can stop waiting for.
We can do that later if we want.
There was a problem hiding this comment.
Hmmm ok, may as well kill that one too, I'll get on it
There was a problem hiding this comment.
🤖 Claude: Resolved in dd359fe. The blocking Lazy<ConnectionMultiplexer> + ConnectionMultiplexer.Connect has been replaced by AsyncLazy + ConnectAsync. No operation path blocks a thread on the connect now. (IsConnected still calls GetResult(), but only after HasValue is true, when the task has already completed.) There's one leftover edge case: the caller that runs the factory doesn't stop waiting when cancelled. It's covered in the thread on the old line 437 and in a new comment on SubscribeToChannel.
|
|
||
| async Task<T> ExecuteWithRetry<T>(Func<Task<T>> operation, CancellationToken cancellationToken) | ||
| async Task<T> ExecuteWithRetry<T>(Func<Task<T>> operation, CancellationToken cancellationToken, bool stopWaitingOnCancellation = true) | ||
| { |
There was a problem hiding this comment.
Should we add some tests?
There was a problem hiding this comment.
🤖 Claude: Partially addressed. a0e35fb adds AsyncLazyFixture, which covers the lazy-init semantics well: failure not cached, waiter cancellation, and factory-holder cancellation. There are still no RedisFacade tests for the behaviour this PR is about:
- a cancelled caller returns promptly while Redis is unresponsive;
- a cancelled first connect doesn't break later calls;
- no command is sent after cancellation.
The existing PortForwarder setup in RedisFacadeWhenRedisGoesDownAwayTests could drive these without depending on timing: pause the forwarder, call GetString with a token you then cancel, resume the forwarder, and check that a call with a fresh token succeeds.
sburmanoctopus
left a comment
There was a problem hiding this comment.
Nice.
Some comments to consider.
borland
left a comment
There was a problem hiding this comment.
🤖 Claude-Round2: The per-call WaitAsync approach from round 1 looks fine to me now. The new async GetConnection in 6e6dc65 has a blocker, though, so I would not approve until it's fixed. If the first caller to connect is cancelled while the connection is being made, the facade caches a cancelled task forever and every later Redis call fails. I reproduced the exact ContinueWith/token pattern in a small console app.
Findings (inline):
- Blocker,
RedisFacade.cs:60: a cancelled first connect is never cleared, so the facade stays broken until disposed.ExecuteWithRetryretries for 30s and then throwsTaskCanceledException, andSubscribeToChannelretries every 2s forever. - Major,
RedisFacade.cs:79: the cleanup path for an abandoned connect never runs, becausemultiplexeris still null whenWaitAsyncthrows. The multiplexer thatConnectAsynccreates later is never disposed, and withAbortOnConnectFail = falseit keeps reconnecting in the background. - Major,
RedisFacade.cs:437(affects every lambda): callers that join an in-progress connect wait on the first caller's task, not their own token. If they're cancelled, the abandoned lambda still sends its command (pop, push, delete) once the connection arrives, after the caller has already returned.
One fix covers all three: start the connect without any caller's token, cache it, decide at read time whether a faulted/cancelled task should be replaced, and give each caller cachedTask.WaitAsync(callerToken). Snippet on the first comment.
Earlier threads:
- Stop-waiting carve-out: resolved.
stopWaitingOnCancellationwas removed in 6e6dc65, and every operation now stops waiting on cancellation, as Luke and Orion agreed. - The stale pop comment (line 434) and the
WaitForOperationdoc (lines 181-182): the replies say these were removed or updated, but both are still there at 6e6dc65, which matches origin. Maybe not pushed yet? The PR description also still saysListLeftPopAsyncand the delete inTryGetAndDeleteFromHashkeep waiting for Redis. That's no longer true. - Blocking
Lazyconnect: addressed by 6e6dc65, apart from the issues above. - Tests: still none. Finding 1 can get a deterministic test with the existing
PortForwardersupport (seeRedisFacadeWhenRedisGoesDownAwayTests): pause the forwarder, callGetStringwith a token cancelled after ~100ms, resume, then check that a call with a fresh token succeeds. It doesn't depend on timing, because the bug is a cached task state.
Not checked: I did not build the branch or run the Redis test suite. The poisoning behaviour was confirmed with a stand-alone repro of the same ContinueWith pattern, not against real Redis.
| ConnectionMultiplexer? multiplexer = null; | ||
| try | ||
| { | ||
| multiplexer = await ConnectionMultiplexer.ConnectAsync(redisOptions).WaitAsync(ct); |
There was a problem hiding this comment.
🤖 Claude-Round2: Major: the abandoned multiplexer leaks, and the cleanup in the catch block can never run.
When WaitAsync(ct) throws, the assignment to multiplexer hasn't happened, so multiplexer is always null in the catch (OperationCanceledException) block. The dispose branch is dead code. My repro hit that catch with multiplexer == null.
Meanwhile the real ConnectAsync task keeps running and returns a ConnectionMultiplexer that nothing references or disposes. Because AbortOnConnectFail = false, that multiplexer keeps its sockets, heartbeat timer and reconnect loop alive for the life of the process. Its exception is also never observed if it faults.
Scenarios:
DisposeAsynccancelsobjectLifetimeCtswhile a connect is in progress. That cancelscombinedToken, which is the token this connect was started with.- Any first caller is cancelled during the connect.
If this happens repeatedly, for example caller cancellations while Redis is unreachable, each attempt leaks another multiplexer.
Suggestion: let the shared connect run to completion, as in the snippet on line 60, so DisposeAsync always gets a multiplexer it can dispose. If you do want to abandon the connect, attach the cleanup to the ConnectAsync task itself, not to a local that's never assigned:
var connectTask = ConnectionMultiplexer.ConnectAsync(redisOptions);
try { multiplexer = await connectTask.WaitAsync(ct); }
catch (OperationCanceledException)
{
_ = connectTask.ContinueWith(t => Try.IgnoringError(async () => await t.Result.DisposeAsync()),
CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default);
connectTask.IgnoreUnobservedExceptions();
throw;
}There was a problem hiding this comment.
🤖 Claude: Partially fixed in dd359fe. When a caller is cancelled, the multiplexer no longer leaks. The factory now always awaits ConnectAsync to completion and caches the result, so DisposeAsync can dispose it.
Still open: the first scenario above, where DisposeAsync runs while the connect is in progress. connectionMultiplexer.HasValue is still false at that point (RedisFacade.cs:179), so DisposeAsync skips the dispose. When ConnectAsync finishes, the factory caches the new multiplexer, and nothing ever disposes it. With AbortOnConnectFail = false, it keeps reconnecting in the background for the life of the process. Also, SubscribeToChannel doesn't use objectLifeTimeCancellationToken, so calling it after dispose can still start a brand-new connect.
Possible fix: in the factory, after ConnectAsync returns, check objectLifeTimeCancellationToken.IsCancellationRequested. If it's set, dispose the multiplexer and throw ObjectDisposedException. That still leaves a very small window. To close it completely, DisposeAsync would need to wait for an in-progress factory call without starting a new one, for example through a method on AsyncLazy that waits on the semaphore but never runs the factory.
| return await ExecuteWithRetry<string?>(async ct => | ||
| { | ||
| var database = Connection.GetDatabase(); | ||
| var connection = await GetConnection(ct); |
There was a problem hiding this comment.
🤖 Claude-Round2: Major: commands can be sent after the caller was cancelled and has returned. This applies to every ExecuteWithRetry lambda. It matters most here because a pop is destructive.
GetConnection(ct) only respects ct for the caller that created connectionSource. Any other caller that arrives while the connect is in progress gets the first caller's task, which doesn't watch its token. When that second caller is cancelled, WaitForOperation stops waiting and ExecuteWithRetry throws OperationCanceledException, which is correct. But the abandoned lambda is still waiting on the shared connect. When the connect finishes, it carries on and runs database.ListLeftPopAsync(listKey). The item is popped on the server and the result is thrown away.
The round-1 discussion accepted that a command in flight when cancellation happens may still be applied. This case is different. The command hasn't been sent when the caller gives up, and it can be sent up to ConnectTimeout (seconds) later. Pushes, deletes and TTL changes are affected the same way.
Scenario: on startup, several TryRemoveNextItemFromQueue loops for different tentacles call ListLeftPopAsync while the first connect is still running. One of those tentacles disconnects (its token is cancelled). When the connection comes up, its pending pop still runs, and a queued request is dequeued with nobody to receive it.
Suggestion: have GetConnection return sharedTask.WaitAsync(cancellationToken) (see line 60). Each lambda then throws at the await GetConnection(ct) line and never sends the command after cancellation.
There was a problem hiding this comment.
🤖 Claude: Partially fixed in dd359fe. Callers that join an in-progress connect now wait on semaphore.WaitAsync(ct) with their own token. When cancelled, they throw at await connectionMultiplexer.Value(ct) and never send their command.
Still open, but now for the other caller: the caller that runs the factory. AsyncLazy.Value awaits factoryFunc(ct) directly, and the factory only checks ct before ConnectAsync, which takes no token. If that caller is cancelled during the connect, WaitForOperation stops waiting and ExecuteWithRetry returns. The lambda is still waiting inside Value(), though. When ConnectAsync finishes (up to ConnectTimeout, 5s by default), Value() returns and the lambda goes on to send ListLeftPopAsync (or a push or delete). The popped item is then discarded.
Scenario: a dequeue loop is the first Redis user after startup, Redis is slow to connect, and that tentacle's token is cancelled. One queued request is popped and lost.
Fix: ExecuteWithRetry disposes its CancelOnDisposeCancellationToken on the way out, so ct is always cancelled by the time this happens. A check after getting the connection is therefore enough. The cleanest place is AsyncLazy.Value, after the factory has finished, so the value is still cached:
value = await factoryFunc(cancellationToken);
hasValue = true;
cancellationToken.ThrowIfCancellationRequested(); // value is cached; this caller just doesn't use it
return value;(Alternatively, add ct.ThrowIfCancellationRequested(); after each await connectionMultiplexer.Value(ct) in the lambdas.)
| { | ||
| // NitoEx.AsyncLazy doesn't allow us to pass a CancellationToken to the GetValue method; we build our own | ||
| // equivalent here. | ||
| lock (this) |
There was a problem hiding this comment.
Why not use a Lock object. If we put that next to connectionSource, it makes it clear that accessing connectionSource should be done using that lock.
There was a problem hiding this comment.
net48 doesn't have System.Threading.Lock
There was a problem hiding this comment.
🤖 Claude: Now moot. dd359fe removed the lock (this) / connectionSource code. AsyncLazy guards initialisation with a private SemaphoreSlim.
| connection = new Lazy<ConnectionMultiplexer>(() => | ||
|
|
||
| connectionMultiplexer = new AsyncLazy<ConnectionMultiplexer>(async ct => |
There was a problem hiding this comment.
🤖 Claude: Prior issue, now fixed. There was a blocker here: a cancelled first connect (ContinueWith with the caller's token) left a cancelled task cached in connectionSource, which broke the facade until it was disposed.
Fixed in dd359fe by AsyncLazy<ConnectionMultiplexer>. A failed or cancelled factory call is not cached: hasValue stays false and the semaphore is released in finally, so the next caller runs the factory again. AsyncLazyFixture.WhenTheFactoryThrows_TheFailureIsNotCached... and ...WhenTheCallerRunningTheFactoryCancels... cover this. Because the factory awaits ConnectAsync directly, callers also see the real exception instead of AggregateException, and the old continuation ordering race is gone.
| { | ||
| // This can throw if we are unable to connect to redis. | ||
| var channel = await Connection.GetSubscriber() | ||
| var connection = await this.connectionMultiplexer.Value(cancellationToken); |
There was a problem hiding this comment.
🤖 Claude: Minor: SubscribeToChannel doesn't stop waiting when its caller runs the connect.
ExecuteWithRetry wraps the whole lambda in WaitForOperation. This Value(cancellationToken) call is awaited directly. If this call is the one running the AsyncLazy factory, the factory checks ct once and then awaits ConnectAsync, which takes no token. Cancelling the token therefore has no effect until the connect finishes, which can take up to ConnectTimeout (5s by default). That's the delay this PR is meant to remove. Callers that are waiting on the semaphore are fine, because semaphore.WaitAsync(ct) stops waiting when they're cancelled.
Scenario: a subscription is the first thing that touches Redis, Redis is slow or unreachable, and the subscriber is cancelled (for example, during shutdown or when a request is abandoned). The cancellation takes several seconds to take effect.
Suggestion: stop waiting here the same way the other paths do, and observe the abandoned task:
var connectionTask = connectionMultiplexer.Value(cancellationToken);
ConnectionMultiplexer connection;
try { connection = await connectionTask.WaitAsync(cancellationToken); }
catch (OperationCanceledException) { connectionTask.IgnoreUnobservedExceptions(); throw; }(Or fix it once in AsyncLazy by keeping the in-progress factory task and having each caller WaitAsync(ct) on it, so that no caller's cancellation is tied to the factory.)
| /// <summary> | ||
| /// A Lazy implementation with CancellationToken support. | ||
| /// </summary> | ||
| public class AsyncLazy<T> |
There was a problem hiding this comment.
🤖 Claude: Nit: AsyncLazy<T> is public, so it becomes part of the Halibut NuGet package's public API. Its sibling in this folder, TaskExtensions, is internal, and Halibut.Tests already has InternalsVisibleTo, so AsyncLazyFixture would still compile. If it's public, consumers can start depending on it, and later changes (for example, to fix the cancellation behaviour in the SubscribeToChannel comment) become breaking changes. Suggest internal class AsyncLazy<T>.
| } | ||
| } | ||
|
|
||
| public bool IsConnected => connectionMultiplexer.HasValue && connectionMultiplexer.Value(CancellationToken.None).GetAwaiter().GetResult().IsConnected; |
There was a problem hiding this comment.
🤖 Claude: Nit: sync-over-async that is only safe because of how AsyncLazy is currently written. GetResult() never blocks today, because Value takes the if (hasValue) return value; fast path and returns a completed task. If Value changes later (for example, an await before the check), IsConnected could block a thread or deadlock. A synchronous accessor on AsyncLazy, such as bool TryGetValue(out T value), would make that guarantee explicit:
public bool IsConnected => connectionMultiplexer.TryGetValue(out var conn) && conn.IsConnected;DisposeAsync (lines 179-183) could use the same accessor.
|
🤖 Claude: Round 3 review (dd359fe). Moving to Status of earlier comments:
New findings (inline):
Cross-cutting: a note on the Not checked: I didn't build or run the tests ( |
🤖 Claude (with tweaks from 👨 Orion)
Background
StackExchange.Redis doesn't accept a
CancellationTokenon commands likeStringGetAsync.There's no other available token either (for example how aspnet core has HttpContext.RequestAborted as a proxy cancellation token).
A stuck command only ends when Redis responds, or when
AsyncTimeoutexpires.AsyncTimeoutfalls back toSyncTimeout(5s) and is only checked once per 1s heartbeat.While the connection is down, backlogged commands time out using
SyncTimeout. As a result, cancelling a caller ofRedisFacadedidn't take effect until roughly 5–6s later, once for each retry attempt.Changes
ExecuteWithRetry(both versions) awaits each Redis operation withWaitAsyncusing the combined token (caller's token plus the facade's lifetime token). Cancellation now takes effect immediately. The abandoned Redis task has its exceptions observed, so its later timeout doesn't surface as an unobserved task exception.ListLeftPopAsyncand the delete inTryGetAndDeleteFromHash. These still wait for Redis to respond, because if we abandoned them and Redis applied them anyway, the popped or deleted item would be lost. They can still take up to the Redis timeout to return after cancellation.SubscribeToChannelalso stops waiting on cancellation. If the abandonedSubscribeAsynccompletes later, it is unsubscribed, so no orphaned subscription is left behind. Cancellation is no longer caught and logged as "Failed to subscribe… retrying in 2 seconds". A Redis error that coincides with cancellation now propagates as itself rather than as anOperationCanceledException, matchingExecuteWithRetry.Task.WaitAsync(CancellationToken)inTaskExtensionMethods. net10.0 uses the built-in version.IgnoreUnobservedExceptionsnow passesTaskScheduler.Defaultexplicitly, instead of picking upTaskScheduler.Current.Notes
SetStringorListRightPushAsynccan still be applied in Redis after the caller has given up. The retry loop already had a similar risk.👨 Orion: This is not a new problem, in any network-based system there is always a race condition where you
Send the command to change something
The remote server receives and applies the change
The remote server is sending it's response back but you haven't got it yet
CANCEL
This just extends the timing on the same behaviour
No timing-based test was added, because it would be flaky on slow CI agents.
🤖 Generated with Claude Code