Dev48
Language
  • About
  • Services
  • Industries
  • Technologies
  • Articles
  • Contacts
Book a call
    Home/Articles/Geographic failover for net with seredis
Dev48
info@dev48.org+375 29 320-40-96WhatsApp@isky_by

© 2026 · All rights reserved.

Geographic failover for .NET with SE.Redis

Source: Redis•November 25, 2026 at 07:45 PM

Geographic failover for .NET with SE.Redis

StackExchange.Redis, or SE.Redis is the main .NET client for Redis. It provides an API for the core Redis data types, commands and messaging like pub/sub. It only takes a few instructions to connect your .NET application to a Redis database. Modern a...

StackExchange.Redis, or SE.Redis is the main .NET client for Redis. It provides an API for the core Redis data types, commands and messaging like pub/sub. It only takes a few instructions to connect your .NET application to a Redis database.

Modern apps run Redis across regions so global users don’t need to face punishing latency, and a single outage doesn’t take the application down. Sounds simple in principle, but in practice it brings some challenges when a region fails. Take a command like INCR. When it times out, did it run? Retry blindly and you can count twice. In our tests, redis-py, Jedis’s MultiDbClient, go-redis and ioredis all did. Choose not to retry, and even a harmless GET command fails. From corrupted counters to duplicated orders, this issue can easily cause a wide range of real-world problems. To mitigate this, SE.Redis 3.1.0 tags every command with what a replay would do, so it retries what’s safe and leaves the rest alone.In this article we explain how to set up SE.Redis using this feature and avoid a compromise between operational quality, stability and reliability.

Let’s start with a single region

When you're dealing with a single geographic region, connecting to Redis with SE.Redis is trivial:

However, limiting ourselves to a single region doesn't protect us in the event of a major geographic problem. When a region goes down, you are in one of two setups:

  • independent (disconnected) regional databases, common for pure caching scenarios where data loss is not a concern
  • tightly coupled Active-Active servers, with a copy of your data in each region, converging changes between regions

Either way, the remaining region is probably still reachable. What is left is the client's job: notice that the region you are talking to has gone, move traffic somewhere healthy, and move it back when things recover.

Redis recently described how redis-py handles this, in Stay up when a region goes down, and the general model is covered in client-side geographic failover for Active-Active.

SE.Redis supports the same model from version 3.1.0

From 3.1.0, we can use the same approach described in the redis-py post, using connection groups. A failover-capable connection is a group of members, each of which is an ordinary SE.Redis connection:

A member takes either a configuration string or a full ConfigurationOptions, so each region can have its own credentials, TLS settings and timeouts. There is no separate switch for cluster mode: each member works out for itself whether it is talking to a standalone server or a cluster, exactly as a normal connection does.

IConnectionGroup is an IConnectionMultiplexer, so GetDatabase() and GetSubscriber() hand back the same IDatabase and ISubscriber you already use. Code written against a single connection keeps working; it just talks to whichever member is currently active.

If you want to see this run, the redis-py post's demo (two local Redis containers, one of which gets stopped and restarted while traffic flows) has a .NET port at seredis/geofailoverdemo; it is the same scenario, phase for phase.

If you are coming from the Python article, the concepts map across directly:

In many cases, just telling the library about the different endpoints is enough, but if we want more control, we have access to a wide range of configuration settings to control how failure is detected and handled.

One configuration pattern to rule them all

There are three policies to configure: HealthCheck, CircuitBreaker and RetryPolicy. They all follow the same shape. Each policy is immutable, has a static Default and None, and has a nested Builder that starts from the default values. A builder converts implicitly to its policy, so you only write the values you want to change:

Values are validated when the builder is turned into a policy, so a bad setting fails where you wrote it rather than at 3am. Because the policies are immutable they can be shared freely, and there is never a question of whether a change "took effect" after connecting. MultiGroupOptions holds the group-wide defaults, and the same properties on ConnectionGroupMember override them for one member: a remote archive region that you never want to probe, say, or a flaky one that should stay out of rotation for longer.

Deciding where traffic goes

This part works much as it does in other clients:

Health checks probe each member on a timer (every five seconds by default). The built-in probes are Ping, IsConnected (no traffic at all) and StringSet (a real write, skipped on replicas). Several probes can be combined with AnySuccess, AllSuccess or MajoritySuccess, or with a policy of your own. Custom probes that touch a key can use server.InventKey(prefix) to get a key that routes to the server being probed, which matters on a cluster.

Circuit breakers watch the traffic that is already flowing and trip when the failure rate over a rolling window crosses a threshold. Faults are classified by kind rather than by exception type: a timeout or a dropped connection counts against the breaker, while WRONGTYPE or an unknown command does not, since neither says anything about the health of the connection. A tripped breaker drops the connection and marks the member unhealthy straight away, without waiting for the next health check. Breakers also work on a plain single connection, via ConfigurationOptions.CircuitBreaker.

Selection picks the highest-weighted member that is connected and not marked unhealthy (measured latency breaks ties between equal weights). When nothing else separates two members, the one already active wins, so traffic does not bounce between them.

Failback is governed by FailbackDelay, measured from a member's most recent failure. A member that keeps failing keeps resetting its own clock, so it stays out of rotation until it has been stable for the whole delay. The default is zero (fail back as soon as a health check passes), and TimeSpan.MaxValue turns automatic failback off entirely, leaving it to you.

The awkward question: what can we retry?

Here is the problem. Failovers do not wait for a gap between commands; they happen while commands are on the wire. Say the client has sent INCR page:views, and then the connection drops, or the reply does not arrive before the timeout. Did the increment happen? There is no way to know. The server might never have seen the command, or it might have applied it and been unable to reply.

For some commands that does not matter. Sending GET again is harmless. Sending SET key value again is usually fine, because the end state is the same either way. Sending INCR or LPUSH again may count twice. During a failover the retry also goes somewhere new: a different region, which may or may not have received the first attempt through replication yet.

There are really two questions here:

  • Do we know whether the server could have applied the command?
  • If we don't, what would sending it again do to the data?

Redis clients answer these in quite different ways, and each answer is a reasonable trade-off.

The most common approach is to decide by the kind of error. A connection error or a timeout is treated as retryable, whatever the command was. This is simple and predictable, and keeps the common case of a read-heavy workload running through a blip. The cost is that an INCR that timed out can be applied twice. That is not hypothetical: by putting a proxy in front of a Redis server that forwards a single INCR and then either drops the connection or sits on the reply, we can see what the current release of each client does at default settings. redis-py (and so MultiDBClient), Jedis's MultiDbClient, go-redis and ioredis all reported the INCR as a success, and the server's counter read 2.

node-redis takes the opposite position: a command that has already been sent is never replayed, because it might have run. Nothing is ever applied twice, but a GET that could safely have been retried fails as well. Plain Jedis, without the failover client, behaves the same way. In the same test both report a connection error and the counter stays at 1.

Some clients answer part of question 1. go-redis retries a fixed list of server errors that are only ever returned before a command runs, such as LOADING, READONLY and CLUSTERDOWN. Lettuce, for question 2, lets you supply a replayFilter that decides per command whether to replay it after a reconnect. It only sees commands that were queued while the connection was down or whose write failed; a command that was fully sent and still waiting for a reply when the socket dropped is always replayed, and that is exactly the ambiguous case. Both are useful, but in each case the rest of the problem is left to you.

SE.Redis's answer: retry categories

SE.Redis answers both questions, separately.

Retries are opt-in, and you ask for them by wrapping a database:

The wrapper only exposes the async API - this is intentional since a retry can involve waiting, either for a delay or for the group to fail over, and blocking a thread for that is not something we want to encourage.

Did it run? Known-not-applied faults

Some faults tell us for certain that nothing happened. If the command was still waiting to be written when the connection failed, the server never saw it. If the server replied with LOADING, MOVED, ASK, READONLY, CLUSTERDOWN, TRYAGAIN, MASTERDOWN, BUSY and a few others, it rejected the command because of its own state, before running anything. In these cases sending the command again is a first attempt, not a repeat, and it is retried whatever it is. Even an INCR.

We are deliberately conservative about this. An ordinary error reply is not enough: a Lua script can write something and then fail, passing the inner error (WRONGTYPE, OOM) back verbatim, so those stay ambiguous. Timeouts, and connection loss after a command was sent, are always ambiguous.

What would a replay do? Categories

For the ambiguous cases, every command carries a retry category describing what a replay would do to the keyspace, in increasing order of impact:

A policy retries ambiguous faults only for commands at or below its MaxCommandRetryCategory. The default is CommandRetryWriteLastWins: reads and overwrites are retried, accumulating writes are not.

If the attempts run out, the caller gets the exception from the final attempt, unwrapped. The retry decision is made in an exception filter, so nothing is caught and rethrown and the stack trace is the real one.

The category depends on the arguments as well as the command name. A plain SET is "last wins", but SET with NX, XX or IFEQ is a checked write. CONFIG GET is not treated as though it were CONFIG SET. The typed methods (StringSetAsync, HashSetAsync and so on) take care of this for you.

If you want more categories to be retried, raise the cap for a policy rather than tagging individual calls:

Commands the library can't see into

Commands sent with Execute, and Lua scripts, are opaque: their effect depends on arguments or code that the library does not understand. They default to CommandRetryNever. Execute does recognise command names it knows, so Execute("get", key) is treated as the read it is. For everything else, tell the library what the command does, using the same CommandFlags you already pass:

When specifying a retry category: be honest about it. The category describes what a replay would do. A script that increments a counter is accumulating, however simple it looks.

One subtlety. The category describes the effect on the data, not on the reply. If a SET ... IFEQ succeeds but the reply is lost, the retry finds the value has already changed and reports "not set". The data ends up correct, but code that branches on the return value should be aware of the possibility.

Following a failover

Retries know about the group. With the defaults, the first retry after a failure is allowed to wait, up to FailoverDelay (five seconds), for the group to move to another member, and is then sent there. MaxAttemptsBeforeFailover controls how many attempts go to the current member before that happens.

And if none of this fits, the decision itself can be replaced. RetryPolicy.CanRetry(in FaultContext) is virtual, and the context carries the classified error kind, whether the fault is known not to have applied, and the command's flags, including its category:

Looking ahead: the same metadata decides what v4 can cache

These categories turn out to be useful beyond retries. SE.Redis v4, now in alpha, adds client-side caching, with the library negotiating CLIENT TRACKING itself. The first test for whether a reply may be cached is the retry category: the command must declare one, and it must be at or below CommandRetryReadOnly. A command with no declared category is never cached, so commands the library knows nothing about are excluded by default. A module command sent through an extension library like NRedisStack can't appear in any list of command names compiled into SE.Redis, but it can carry a category, and the flag you set today so it can be retried is the one that will let it be cached.

Read-only is necessary but not sufficient, which is a nice illustration that these are related questions and not the same one. TTL changes with the clock without any write to invalidate it. SRANDMEMBER is supposed to be random. TOUCH exists for its side effect on eviction state, and PFCOUNT quietly writes a cached cardinality back into the HyperLogLog. All of them are safe to retry and wrong to cache, so v4 keeps a short exclusion list alongside the categories. The direction is set out in the v4 roadmap discussion and the tracking PR.

Transactions during a failover

Transactions get the same treatment, as a unit. A transaction created from a retrying database is replayed in full on a retry: the conditions, the MULTI, the queued commands and the EXEC, sent to whichever member is active at the time. The tasks you got back when queuing each operation complete from whichever attempt wins.

For the category check, a transaction counts as its most side-effecting operation. The one above contains an RPUSH, so it is accumulating, and an ambiguous fault such as a timeout on the EXEC is not retried under the default policy. In practice that matters less than it sounds: the faults a transaction most often hits are the server rejecting the whole MULTI/EXEC (during a cluster reshard, or while a replica is promoted), and those are known not to have applied anything.

There is one more failure that is not really a fault at all. A transaction with conditions uses WATCH, and if another client changes a watched key before the EXEC arrives, the server refuses it. ExecuteAsync returns false in that case, and also when one of your conditions simply wasn't true; WasWatchConflict tells you which. The two call for different responses. A false condition will be just as false next time, so retrying is pointless. Losing a race with another writer is exactly the case WATCH expects you to retry, and a retrying transaction does that, up to MaxAttemptsOnWatchConflict times (three by default). It has its own budget, separate from MaxAttempts, because nothing has gone wrong and nothing could be double-applied.

The race is less likely than in redis-cli style usage, because SE.Redis sends the WATCH, the condition reads and the MULTI/EXEC as one dispatch. The window is small, but on a busy key it is not zero.

Pub/Sub

Subscriptions are made on every member of the group, not just the active one, and the library filters incoming messages so that you only see those from the active member. Publishing goes to the active member only. The effect is that subscriptions behave as though you were connected to one server, and after a failover there is no gap while the client resubscribes, because it is already

Operating a group

ConnectionChanged reports when members connect, disconnect, are added or removed, and when the active member changes:

group.ActiveMember and group.GetMembers() give you the current state, and each member reports IsConnected, IsUnhealthy, Weight and Latency.

You can also take control. TryFailoverTo(member) pins traffic to one member, for example while another region is being serviced, and TryFailoverTo(null) hands control back to automatic selection. member.ResetIsUnhealthy() returns a member to rotation without waiting for its FailbackDelay. Weights can be changed at runtime, and members can be added and removed, which makes it possible to move to a new region without downtime:

OpenTelemetry metrics for failover are planned. Until then, ConnectionChanged is the place to hook your own counters. The intention is to align the counters with the ones other clients emit, so dashboards line up across platforms.

Limits worth knowing

  • The group does not replicate data; Active-Active does. A group can be built over servers that are not replicated to each other, and that is reasonable for a cache that can be repopulated, but a failover then moves you to a different dataset, and writes made before it will not be visible after it.
  • A write that succeeded on the old member just before a failover may not be visible on the new one until replication catches up. This is true of every client.
  • Server maintenance notifications are not yet supported inside a group. Work to combine the two is in progress.
  • Cursor-based scans (HashScanAsync and friends) run against the active member and are not replayed. A cursor does not carry over to another member.
  • WithRetry refuses a database that carries an asyncState, since a retried operation can't carry it.

Wrapping up

Moving traffic between regions is the part of geo failover that every client has to do, and the SE.Redis version will look familiar if you have read about redis-py's. The part we think is worth your attention is what happens to the commands that were in flight: SE.Redis knows, for each command, what sending it again would do, and it uses that to retry what is safe and to leave alone what is not. The same knowledge is what will tell the v4 client what it can cache.

The full reference is in the failover documentation, the runnable demo is at , and the feature is available in StackExchange.Redis 3.1.0 and later.

← All articles

What this article says

More in Software Development

All →
Live at World Tour NYC: Meet the People Building Salesforce on Salesforce
Salesforce Commerce

Live at World Tour NYC: Meet the People Building Salesforce on Salesforce

The End of CRM Busywork: How Agentforce Coworker Helps Run Your Small Business
Salesforce Commerce

The End of CRM Busywork: How Agentforce Coworker Helps Run Your Small Business

Understanding Salesforce Connected App or External Client App Suspension
Salesforce Commerce

Understanding Salesforce Connected App or External Client App Suspension

How to Write a Welcome Email That Turns New Customers into Loyal Fans
Salesforce Commerce

How to Write a Welcome Email That Turns New Customers into Loyal Fans

Datablazer Roundup: November
Salesforce Commerce

Datablazer Roundup: November

AI Lead Qualification: A Complete Guide to How It Works
Salesforce Commerce

AI Lead Qualification: A Complete Guide to How It Works

More from Redis

What is agent memory?
Redis

What is agent memory?

Which AI agent memory should you use?
Redis

Which AI agent memory should you use?

How I made Muse less forgetful
Redis

How I made Muse less forgetful

Redis Cloud remote MCP server now available for your AI agents
Redis

Redis Cloud remote MCP server now available for your AI agents

Stop repeating yourself: integrate Azure Managed Redis with your databases
Redis

Stop repeating yourself: integrate Azure Managed Redis with your databases

Run RediSearch, vector sets, & RedisJSON natively on Windows with Memurai
Redis

Run RediSearch, vector sets, & RedisJSON natively on Windows with Memurai