Skip to content

The search box knows all the secrets -- try it!

Polecat is part of the Critter Stack ecosystem.

JasperFx Logo JasperFx provides formal support for Polecat and other Critter Stack libraries. Please check our Support Plans for more details.

Resiliency Policies ​

Polecat executes every database command through a Polly resilience pipeline on StoreOptions.ResiliencePipeline, which you can replace or extend.

Default behaviour: nothing is retried ​

WARNING

Polecat's default pipeline adds no strategy at all. It does not retry deadlocks, lock timeouts, or anything else. This page previously claimed the opposite — that Polecat "retries on transient SQL Server errors (deadlocks, timeouts, connection failures) with an exponential backoff strategy" — and that was wrong in the most unhelpful direction, because it implied a retry was already in place and had been thought through.

Two separate things are easy to conflate here:

what retries itwhich errors
Connection openMicrosoft.Data.SqlClient's own SqlConnection.RetryLogicProviderSqlClient's transient baseline, minus 1205 and 1222
Command executionnothing, by default—

The connection-open list excludes the deadlock victim (1205) and lock request timeout (1222) deliberately: neither can happen while a connection opens. Nor are they the same failure once one is open. A deadlock rolls the transaction back, so nothing worth calling a retry is possible at the command level — it would have to be a replay of the whole unit of work. A lock timeout aborts the statement and leaves the transaction open. Either way, on the exclusive append paths you get a StreamLockedException and retry at the application layer, e.g. with a Wolverine OnException<StreamLockedException>().RetryWithCooldown(...) policy. If a strategy on this pipeline retries the deadlock first, you get SessionTransactionUnusableException instead, because the replay is refused. PolecatRetryPredicates.IsUnsafeToReplay tells a strategy not to, so compose it in, handle that exception too, or leave 1205 out of the strategy.

Before you add a retry ​

A retry here replays one command, not the code that computed it

The pipeline wraps each command, not the unit of work. By the time it sees a failure, your application code has already read, decided, and handed the session a set of operations. A retry re-issues the command that failed. It does not re-run the method that produced it, so it cannot recompute anything against fresh data, and it does not re-run the commands before it in the same transaction.

For most failures that is fine. For a snapshot update conflict it is a silent lost update, because such a conflict means precisely that the snapshot those operations were derived from is no longer a valid basis for them. The replay opens a fresh snapshot in which the conflict no longer exists, and the second write lands over the first.

This is not hypothetical: it is marten#5528, where a Serializable session lost a committed write exactly this way.

Both preconditions are reachable in Polecat — SessionOptions.IsolationLevel is public and sets the level of every transaction a document session runs (see below), and the hooks below invite the retry — so the rule is:

errormeaningwhat happens to the transactionsafe to replay?
3960snapshot isolation update conflictrolled backnever — only the application can resolve it, by re-reading and recomputing
1205deadlock victimrolled backnever inside a transaction, at any level: the work before this command is gone, and replaying the command cannot bring it back. Outside one (a plain read), yes at ReadCommitted; no under Snapshot / Serializable
1222lock request timeoutstays open, only the statement is abortedyes at ReadCommitted; no under Snapshot / Serializable, where it replays stale-snapshot work
no numberconnection pool timeout, raised as a plain InvalidOperationExceptionthere isn't one: no connection was obtained, so nothing ranyes at every level, but think about it first

PolecatRetryPredicates encodes that table so you do not have to carry the numbers. An error number cannot tell the two rows of 1205 apart, so at ReadCommitted the predicate answers "safe" for a deadlock and the protection sits below it, as described next. That costs one attempt: the replay is refused, the predicate answers "unsafe" for the refusal, and the retry stops there.

Connection pool timeouts ​

When every pooled connection is in use and Connect Timeout runs out, SqlClient raises a plain InvalidOperationException with no SqlException or TimeoutException inside it. A strategy that handles only SqlException will not retry it, and the connection-open retry in the table at the top of this page does not see it either.

A retry is safe, because nothing ran. It may still not be what you want: every attempt has already waited out the whole Connect Timeout, 15 seconds by default, and a pool timeout means the application is out of capacity, which a retry adds to rather than relieves. If you do retry one, keep the attempts few and the delay long.

The async daemon does not retry it. A projection that hits a pool timeout does not dead-letter the event, whatever SkipApplyErrors says. The shard pauses with ShardFailure.IsTransient set, so a supervisor knows it is worth restarting, and a restart picks up from the shard's persisted progress without losing anything. If nothing in your application supervises the daemon, the shard stays paused until something restarts it, as it does after any other failure. Wolverine's managed subscription distribution is one such supervisor. Several slices timing out together are the exception: the daemon gets them as a group with no single event to blame, and builds the batch again in place.

cs
using Polecat.Resilience;

opts.ExtendPolly(builder =>
{
    builder.AddRetry(new RetryStrategyOptions
    {
        MaxRetryAttempts = 3,
        BackoffType = DelayBackoffType.Exponential,
        Delay = TimeSpan.FromMilliseconds(200),

        // The important line. Without it, a 3960 is replayed and a committed write is lost.
        ShouldHandle = args => ValueTask.FromResult(
            args.Outcome.Exception is not null
            && !PolecatRetryPredicates.IsUnsafeToReplay(args.Outcome.Exception))
    });
});

Pass the isolation level your sessions use if it is not ReadCommitted — it is a per-session setting, so the predicate cannot read it for you:

cs
ShouldHandle = args => ValueTask.FromResult(
    args.Outcome.Exception is not null
    && !PolecatRetryPredicates.IsUnsafeToReplay(
        args.Outcome.Exception, IsolationLevel.Snapshot))

Polecat does not override a strategy you configured. A store that quietly refused to honour an explicit policy would be a worse surprise than the one it prevents, so the predicate is yours to compose.

The predicate knows when a failure ended the transaction its command was in, so a strategy that asks stops at the failure itself, at any isolation level, and the caller sees what happened.

The one thing Polecat will not do is run a command outside a transaction the session believes it is inside. A strategy that retries a command whose transaction has gone without asking the predicate has the replay refused with SessionTransactionUnusableException, which carries the original failure as its InnerException. Without that refusal the replay would autocommit: every later statement in the save would be durable, and the commit would then report that the save failed.

When SQL Server ends the transaction ​

A deadlock (1205), a snapshot update conflict (3960) and a handful of rarer errors roll the transaction back on the server while the connection stays open. What happens next depends on what the session was relying on that transaction for:

the transaction was...what is gone with itwhat the session does
holding an exclusive lock (FetchForExclusiveWriting, AppendExclusive, natural-key exclusive fetches)the lock the caller made decisions underfinished
any transaction of a session at another isolation level, such as Snapshot or Serializablethe view of the data the caller readfinished
only the failed save's own, in a ReadCommitted sessionnothing the caller has seenkeeps working: that save failed atomically, nothing is durable, and the next save begins a clean transaction with the work still pending

A finished session refuses everything from then on, reads included, with SessionTransactionUnusableException, and writes nothing. Dispose it, open a new session and redo the work from its inputs. Under Wolverine a message retry does exactly that.

A lock timeout (1222) is not on this list. The statement failed, the transaction and every lock it holds are still there, and the session carries on.

When a failed save rolls the transaction back ​

A save that fails on the client, with a ConcurrencyException, a cancelled token or an exception from a listener, rolls its transaction back itself. If the caller was relying on that transaction, what it was relying on has gone just as surely, so the session stops writing rather than carry on without it:

the transaction was...what the session does
holding an exclusive lock, in a ReadCommitted sessionrefuses to write, and goes on reading
any transaction of a session at another isolation levelfinished: it refuses reads as well
only the failed save's own, in a ReadCommitted sessionkeeps working: the next save begins a clean transaction with the work still pending

Refused means SessionTransactionUnusableException, carrying the original failure as its InnerException, from SaveChangesAsync, FetchForExclusiveWriting and AppendExclusive. Taking the lock again on the same session is refused too, because the work queued under the first lock is still pending and a second lock would cover it falsely. EjectAllPendingChanges does not lift the refusal either: whatever the caller stores next was decided under the same lock.

Reads go on working in the first case because a ReadCommitted read runs outside any transaction and reports what is there, which is true whatever the session has lost. At any other level the next read would begin a new transaction, and with it a different view of the data from the one the caller has been reading.

Recovery is the same as for a finished session: dispose it, open a new one and redo the work from its inputs.

What the isolation level covers ​

SessionOptions.IsolationLevel applies to every document session, however it was opened, and to every transaction that session runs, not just the first. At anything but ReadCommitted the session also runs its reads inside a transaction, beginning one with the first command and the next one with the first command after each commit, so a read and the save that follows it are one transaction. That transaction stays open between commands, so keep these sessions short.

A query session never opens a transaction, so the option does nothing there: each read takes its own connection and runs in autocommit at ReadCommitted. For several reads against one snapshot, use a document session at that level.

Document writes at Snapshot ​

In a Snapshot session, Store and Update on a document with no concurrency check raise a snapshot update conflict (3960) over a concurrent write, as event appends and your own queued SQL do. So does Store over a row inserted or deleted since the session's snapshot. Two sessions truly racing to write the same new id can get a duplicate key (2627) instead, as a plain INSERT would. Either way nothing is overwritten, and the save fails. A document using numeric revisions counts as having no check when its revision is 0, because that asks for the next revision and has nothing to fail.

At every other level those writes are MERGE ... WITH (HOLDLOCK), which is what makes concurrent first writes of one id safe. SQL Server raises no conflict for a statement carrying that hint, so a Snapshot session uses UPDLOCK for them instead.

The rest of what a Snapshot session writes reads the current row, and so reports differently:

writewhat it reports over a concurrent write
a document using optimistic concurrencyConcurrencyException from the version check, because that check has to see the current row
a document using numeric revisions, with an explicit revisionConcurrencyException, the same way
InsertDocumentAlreadyExistsException

These Snapshot writes still overwrite

Documents written by an inline projection do not raise 3960, and a concurrent write to the same row is silently replaced. An append to the same stream raises 3960 first, so this only reaches a document that other streams or writers also change.

Flat table projections also keep HOLDLOCK, but lose nothing by it: each statement is computed by SQL from the current row, so Increment on a concurrently changed row gives the right total.

Custom Polly configuration ​

Replace the default pipeline ​

cs
opts.ConfigurePolly(builder =>
{
    builder.AddRetry(new RetryStrategyOptions
    {
        MaxRetryAttempts = 5,
        BackoffType = DelayBackoffType.Exponential,
        Delay = TimeSpan.FromMilliseconds(200),
        ShouldHandle = args => ValueTask.FromResult(
            args.Outcome.Exception is not null
            && !PolecatRetryPredicates.IsUnsafeToReplay(args.Outcome.Exception))
    });
});

Extend the default pipeline ​

The defaults are applied first, then your additions — which, since the defaults are empty, means your additions are the whole pipeline.

cs
opts.ExtendPolly(builder =>
{
    builder.AddTimeout(TimeSpan.FromSeconds(30));
});

Circuit breaker ​

A circuit breaker has none of the replay hazard above — it fails fast rather than re-issuing work:

cs
opts.ExtendPolly(builder =>
{
    builder.AddCircuitBreaker(new CircuitBreakerStrategyOptions
    {
        FailureRatio = 0.5,
        MinimumThroughput = 10,
        SamplingDuration = TimeSpan.FromSeconds(30),
        BreakDuration = TimeSpan.FromSeconds(15)
    });
});

Released under the MIT License.