# Geographic failover for .NET with SE.Redis

**Tagline:** News & Media | **Authors:** Marc Gravell | **Categories:** Engineering & AI | **Published:** 2026-11-24 | **Updated:** 2026-11-25

[StackExchange.Redis](https://github.com/StackExchange/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](https://redis.io/docs/latest/develop/clients/dotnet/).

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:

```csharp
using StackExchange.Redis;

await using ConnectionMultiplexer muxer = await ConnectionMultiplexer.ConnectAsync(
    "redis-east.example.com:6379,password=...,ssl=true");

IDatabase db = muxer.GetDatabase();
await db.StringSetAsync("greeting", "hello");

```

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](https://redis.io/docs/latest/operate/rc/databases/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](https://redis.io/blog/stay-up-when-a-region-goes-down-highly-available-redis-for-python-applications/), and the general model is covered in [client-side geographic failover for Active-Active](https://redis.io/blog/client-side-geographic-failover-for-redis-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:

```csharp
using StackExchange.Redis;
using StackExchange.Redis.Availability;

ConnectionGroupMember[] members =
[
    new("redis-east.example.com:6379,password=...,ssl=true", name: "East") { Weight = 10 },
    new("redis-west.example.com:6379,password=...,ssl=true", name: "West") { Weight = 5 },
];

await using IConnectionGroup group = await ConnectionMultiplexer.ConnectGroupAsync(members);

IDatabase db = group.GetDatabase();
await db.StringSetAsync("greeting", "hello");

```

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](https://github.com/seredis/demos/tree/main/geofailover); it is the same scenario, phase for phase.

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

| redis-py | SE.Redis |
| --- | --- |
| DatabaseConfig | ConnectionGroupMember |
| MultiDbConfig | MultiGroupOptions |
| weight | Weight |
| auto_fallback_interval | FailbackDelay (measured differently, see below) |
| set_active_database() | TryFailoverTo() |
| ActiveDatabaseChanged | ConnectionChanged |

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:

```csharp
MultiGroupOptions options = new MultiGroupOptions.Builder
{
    HealthCheck = new HealthCheck.Builder { ProbeCount = 5, ProbePolicy = HealthCheckProbePolicy.MajoritySuccess },
    CircuitBreaker = new CircuitBreaker.Builder { FailureRateThreshold = 25 },
    RetryPolicy = new RetryPolicy.Builder { MaxAttempts = 5 },
    FailbackDelay = TimeSpan.FromMinutes(2),
};

await using var group = await ConnectionMultiplexer.ConnectGroupAsync(members, options);

```

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:

1. Do we know whether the server could have applied the command?

2. 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:

```csharp
IDatabaseAsync db = group.GetDatabase().WithRetry();      // uses the group's RetryPolicy
IDatabaseAsync strict = group.GetDatabase().WithRetry(new RetryPolicy.Builder { MaxAttempts = 2 });

```

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:

| Category | Meaning | Examples |
| --- | --- | --- |
| CommandRetryAlways | always safe |  |
| CommandRetryConnection | connection state, safe metadata | CLIENT SETNAME, CONFIG GET |
| CommandRetryReadOnly | pure reads | GET, HGETALL |
| CommandRetryWriteChecked | conditional writes; a replay has no effect or fails | SETNX, SET ... NX, SET ... IFEQ |
| CommandRetryWriteLastWins | unconditional overwrite | SET, HSET |
| CommandRetryWriteAccumulating | a replay can apply twice | INCR, LPUSH |
| CommandRetryServerAdmin | server administration | CONFIG SET |
| CommandRetryNever | never retried |  |

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.

```csharp
IDatabaseAsync db = group.GetDatabase().WithRetry();

// times out: a read, so it is retried, and may land on another region
var page = await db.StringGetAsync("page:home");

// times out: may already have been applied, so the timeout reaches the caller
// (but a LOADING or MOVED reply, or a failure before it was sent, is still retried)
await db.StringIncrementAsync("page:views");

```

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:

```csharp
RetryPolicy permissive = new RetryPolicy.Builder
{
    MaxCommandRetryCategory = CommandFlags.CommandRetryWriteAccumulating,
};

```

### 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:

```csharp
// a module command that only reads
var hits = await db.ExecuteAsync("FT.SEARCH", ["idx:products", "@title:redis"], CommandFlags.CommandRetryReadOnly);

// a script that only reads
var value = await db.ScriptEvaluateAsync(
    "return redis.call('GET', KEYS[1])", keys: ["config:flags"], flags: CommandFlags.CommandRetryReadOnly);

```

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:

```csharp
public sealed class ReadsOnSameServer : RetryPolicy
{
    public override RetryResult CanRetry(in FaultContext fault)
    {
        // the category is a small numeric field inside CommandFlags; CommandRetryNever covers the whole field
        var category = fault.Flags & CommandFlags.CommandRetryNever;
        bool isRead = category != 0 && category <= CommandFlags.CommandRetryReadOnly;
        return fault.NotApplied || isRead ? RetryResult.SameServer : RetryResult.None;
    }
}

```

### 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](https://github.com/StackExchange/StackExchange.Redis/discussions/3221) and the [tracking PR](https://github.com/StackExchange/StackExchange.Redis/pull/3262).

## 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.

```csharp
IDatabaseAsync db = group.GetDatabase().WithRetry();

var tran = db.CreateTransaction();
tran.AddCondition(Condition.StringEqual("stock:42", 5));
var set = tran.StringSetAsync("stock:42", 4);
var push = tran.ListRightPushAsync("orders", orderId);

if (await tran.ExecuteAsync())
{
    await set; await push;
}
else if (tran.WasWatchConflict)
{
    // another client kept changing stock:42 under us, even after retrying
}
else
{
    // stock:42 really wasn't 5
}

```

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 subscribed.

## Operating a group

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

```csharp
group.ConnectionChanged += (_, e) =>
{
    if (e.Type == GroupConnectionChangedEventArgs.ChangeType.ActiveChanged)
    {
        logger.LogWarning("Redis failover: {From} -> {To}", e.PreviousGroup?.Name ?? "(none)", e.Group.Name);
    }
};

```

`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:

```csharp
var next = new ConnectionGroupMember("redis-central.example.com:6379", name: "Central") { Weight = 20 };
await group.AddAsync(next);

// once it is connected and healthy, it outranks the others and takes the traffic;
// after that, the old region can go
group.Remove(oldMember);

```

OpenTelemetry metrics for failover are [planned](https://github.com/StackExchange/StackExchange.Redis/issues/2782). 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](https://seredis.dev/Failover), the runnable demo is at [seredis/geofailoverdemo](https://github.com/seredis/demos/tree/main/geofailover), and the feature is available in [StackExchange.Redis](https://www.nuget.org/packages/StackExchange.Redis/) 3.1.0 and later.