{
  "schema_version": 3,
  "id": "develop/clients/go/failover",
  "title": "Client-side geographic failover",
  "url": "https://redis.io/docs/latest/develop/clients/go/failover/",
  "summary": "Improve reliability using the failover features of go-redis.",
  "tags": [
    "docs",
    "develop",
    "stack",
    "oss",
    "rs",
    "rc",
    "oss",
    "kubernetes",
    "clients"
  ],
  "last_updated": "2026-11-25T14:37:37Z",
  "page_type": "content",
  "content_hash": "7e2b25cb1828c7a4fd5853ccd9435f0ba139737eff6b674e7ec2c0ce1dfa3bc2",
  "sections": [
    {
      "id": "overview",
      "title": "Overview",
      "role": "overview",
      "text": "go-redis supports [Client-side geographic failover](https://en.wikipedia.org/wiki/Failover)\nto improve the availability of connections to Redis databases. This page explains\nhow to configure go-redis for failover. For an overview of the concepts,\nsee the main [Client-side geographic failover](https://redis.io/docs/latest/develop/clients/failover) page.\n\nFailover is available in go-redis v9.24.0 and later."
    },
    {
      "id": "failover-configuration",
      "title": "Failover configuration",
      "role": "content",
      "text": "The `MultiDBClient` groups several databases into a set of *members* and sends every\ncommand to one *active* member. The example below uses two members, `redis-east` and\n`redis-west`, where `redis-east` is the preferred one. If `redis-east` fails,\ngo-redis fails over to `redis-west`.\n\nGive each member a `Weight` to rank it (see\n[Selecting a failover target](https://redis.io/docs/latest/develop/clients/failover#selecting-a-failover-target)\nfor how the client uses the ranking). The member with the highest weight is preferred.\n\n[code example]\n\nThe returned `MultiDBClient` has the same commands as the client that\n`redis.NewClient()` returns, so you can use it in place of your usual client.\nIt also has methods to inspect and change the set of members at runtime (see\n[Control the client at runtime](#control-the-client-at-runtime))."
    },
    {
      "id": "member-configuration",
      "title": "Member configuration",
      "role": "content",
      "text": "Each entry in the `Clients` list supports the following fields:\n\n| Field | Description |\n| --- | --- |\n| `Options` | The options for a standalone member. These are the same options you pass to `redis.NewClient()` (see [Connect to the server](https://redis.io/docs/latest/develop/clients/go/connect)). |\n| `ClusterOptions` | The options for a cluster member, as for `redis.NewClusterClient()`. Set exactly one of `Options` and `ClusterOptions`. |\n| `Weight` | Priority of the member, in the range (0, 1]. Higher values are preferred. `0` means the default of `1.0`, and `-1` disables the member. |\n| `HealthChecks` | Health checks for this member only. See [Health checks](#health-checks). |\n| `HealthCheckPolicy` | How to combine the results of this member's health checks. |\n| `SkipInitialHealthCheck` | Used with `AddDatabase()`: register the member even if its first health check fails. The client ignores it for the members you pass to `NewMultiDBClient`. |\n\ngo-redis numbers the members from `0`, in the order you list them. Control methods and\ncallbacks use these numbers to refer to a member."
    },
    {
      "id": "where-to-set-options",
      "title": "Where to set options",
      "role": "content",
      "text": "`NewMultiDBClient` takes a `redis.MultiDBOptions` struct. Options that affect the whole\nclient are fields of that struct. Options for one member are fields of that member's\nentry in `Clients`. Connection settings such as timeouts go in the member's `Options`\n(or `ClusterOptions`).\n\nThe sections that follow show where each option goes."
    },
    {
      "id": "start-the-client",
      "title": "Start the client",
      "role": "content",
      "text": "`NewMultiDBClient` runs a health check on every member and picks the active member\nfrom the healthy ones. Set the `InitialDBState` field of `MultiDBOptions` to choose how\nmany members must pass before the call succeeds, for example\n`InitialDBState: redis.InitialDBStateOneAvailable`:\n\n| Value | Meaning |\n| --- | --- |\n| `redis.InitialDBStateMajorityAvailable` | Half of the members, rounded up, must be healthy. This is the default. |\n| `redis.InitialDBStateAllAvailable` | Every member must be healthy. |\n| `redis.InitialDBStateOneAvailable` | At least one member must be healthy. |\n\nIf too few members are healthy, `NewMultiDBClient` returns an error that matches\n`redis.ErrInsufficientHealthyDatabases`. When no member at all is healthy, the error\nalso matches `redis.ErrPermanentlyNotAvailable`.\n\nThe context you pass controls how long the client keeps trying:\n\n-   With no deadline, `NewMultiDBClient` makes one round of health checks and fails\n    immediately if too few members pass.\n-   With a deadline, it repeats the health checks until enough members pass or the\n    deadline expires. The deadline limits construction only, not later commands.\n    If it expires, the error also matches `context.DeadlineExceeded`.\n\nStartup takes about one second even when every member is healthy, because the default\nhealth check sends three probes 500 ms apart."
    },
    {
      "id": "detect-failures",
      "title": "Detect failures",
      "role": "content",
      "text": "The client uses two independent signals to decide that the active member has failed.\nEither one triggers a failover."
    },
    {
      "id": "circuit-breaker",
      "title": "Circuit breaker",
      "role": "content",
      "text": "Each member has its own circuit breaker, which opens after a run of consecutive\nfailures. After a cooldown it moves to half-open and lets health checks through.\nIt closes again after a run of successes. Configure it with the `CircuitBreakerConfig`\nfield of `MultiDBOptions`, which takes a `*redis.MultiDBCircuitBreakerConfig`. The\nsettings apply to every member.\n\n[code example]\n\nThe struct has these fields. A field you leave at zero takes its default.\n\n| Field | Description | Default |\n| --- | --- | --- |\n| `FailureThreshold` | Consecutive failures before the circuit opens. | `5` |\n| `SuccessThreshold` | Successes in the half-open state before the circuit closes. | `2` |\n| `GracePeriod` | Cooldown between opening and the first half-open probe. | `60s` |\n\nCommands and health probes count their failures separately. If either count reaches the\nthreshold, the circuit will open."
    },
    {
      "id": "failure-detector",
      "title": "Failure detector",
      "role": "content",
      "text": "One failure detector watches the traffic to all members. It trips only when both\nconditions hold within a sliding time window: a minimum number of failures and a\nminimum failure rate. Configure it with the `FailureDetectorConfig` field of\n`MultiDBOptions`, which takes a `*redis.MultiDBFailureDetectorConfig`:\n\n[code example]\n\nThe defaults are 1000 failures and a 10% failure rate in a 2 second window. At that\nsetting the circuit breaker usually trips first.\nThe client uses the fields as you give them: a field you leave at zero doesn't take\nits default (except `Window`, which defaults to 2 seconds). If you set only\n`MinNumFailures`, the rate condition is dropped, and if you set only a rate, a single\nfailed command can trip the detector on an idle client. To change one value, start\nfrom `redis.DefaultMultiDBFailureDetectorConfig()`."
    },
    {
      "id": "retries",
      "title": "Retries",
      "role": "content",
      "text": "The `CommandRetries` field of `MultiDBOptions` sets how many extra attempts a failed\ncommand gets. Each attempt goes to whichever member is active at that moment, so a retry\nreaches the new member after a failover. A value of `0` means the default of `2`, and `-1` disables\nretries.\n\n[code example]\n\n> [!WARNING]\n> If you leave `MaxRetries` unset in each member's `Options` or `ClusterOptions`, go-redis will turn off the\n> member's own retries and rely only on `CommandRetries`. An explicit `MaxRetries` value\n> multiplies the number of times every attempt is sent, and the circuit breaker and failure detector\n> don't see those extra retries. If this happens, a command can block for much longer before the\n> client fails over."
    },
    {
      "id": "fail-over-and-fail-back",
      "title": "Fail over and fail back",
      "role": "content",
      "text": "When the active member's circuit opens or the failure detector trips, the client picks\nthe healthy member with the highest weight and retries the command there. To replace\nthis selection with your own, set the `FailoverStrategy` field of `MultiDBOptions` to a\ntype that implements `redis.MultiDBFailoverStrategy`. The default is\n`redis.WeightBasedFailoverStrategy`.\n\nThese fields of `MultiDBOptions` control failover and failback:\n\n| Field | Description | Default |\n| --- | --- | --- |\n| `MaxFailoverAttempts` | Consecutive failed failover attempts before the client returns `redis.ErrPermanentlyNotAvailable`. | `10` |\n| `FailoverAttemptDelay` | Minimum delay between failed failover attempts. A burst of failures inside this window counts as one attempt. | `12s` |\n| `ProbeTargetBeforeFailover` | Health-check the chosen member before switching to it. | `false` |\n| `AutoFallbackInterval` | How often to check whether a higher-weight member has recovered. A negative value disables fallback. | `120s` |\n\nFailback happens in two steps:\n\n1.  The failed member's circuit breaker closes. The amount of time this takes is at least as long as `GracePeriod`, plus\n    the time to handle the successful probes in the half-open state.\n1.  At the next `AutoFallbackInterval` check, the client switches back to the\n    higher-weight member.\n\nWith the defaults, failback can take several minutes. Lower `GracePeriod` and\n`AutoFallbackInterval` if you want the client to return to the preferred member faster."
    },
    {
      "id": "when-no-member-is-healthy",
      "title": "When no member is healthy",
      "role": "content",
      "text": "If no member can take traffic, commands fail with `redis.ErrTemporarilyNotAvailable`\nwhile the client keeps trying other members. If the number of failed attempts in a row exceeds `MaxFailoverAttempts` then commands will fail with `redis.ErrPermanentlyNotAvailable`.\nThe client doesn't close in either case. It keeps probing the members and recovers when\none becomes healthy, as soon as the `GracePeriod` has elapsed (this defaults to 60 seconds).\n\n[code example]"
    },
    {
      "id": "pipelines-and-transactions",
      "title": "Pipelines and transactions",
      "role": "content",
      "text": "A pipeline executes on the active member as a single, indivisible operation. If the member fails, the client\nretries the whole pipeline on the new active member repeatedly, until the number of attempts exceeds `CommandRetries`.\nIf a transaction pipeline (via `TxPipelined`) is interrupted by a failover, it doesn't automatically get moved to another member. Instead, it returns an error, and you must decide whether to attempt it again."
    },
    {
      "id": "pubsub",
      "title": "Pub/Sub",
      "role": "content",
      "text": "`Subscribe()` on a `MultiDBClient` keeps delivering messages across a failover and a\nfailback. The client moves the subscription to the new active member for you.\nMessages that are published while the active member is failing aren't delivered."
    },
    {
      "id": "health-checks",
      "title": "Health checks",
      "role": "content",
      "text": "The client checks every member on a timer, so it can find out that a failed member has\nrecovered. Set these fields of `MultiDBOptions` to control the checks for every member.\nTo give one member its own checks, set `HealthChecks` and `HealthCheckPolicy` in that\nmember's entry in `Clients` instead. A member's own settings replace the client-wide\nones.\n\n| Field | Description | Default |\n| --- | --- | --- |\n| `HealthCheckInterval` | How often to check each member. | `5s` |\n| `HealthCheckTimeout` | Time limit for one check. If it is at least `HealthCheckInterval`, go-redis lowers it to half the interval. | `3s` |\n| `HealthChecks` | The checks to run on every member. | One `PING` check |\n| `HealthCheckPolicy` | How to combine the probe results. | `HEALTHY_ALL` |\n\nEach check sends several *probes*. A *policy* decides how many probes must pass for\nthe check to pass. The `multidb` package provides three:\n\n| Policy | A check passes when |\n| --- | --- |\n| `NewHealthyAllPolicy()` | All probes succeed. This is the default. |\n| `NewHealthyMajorityPolicy()` | More than half of the probes succeed. |\n| `NewHealthyAnyPolicy()` | At least one probe succeeds. |\n\nWhen you set several checks, all of them must pass."
    },
    {
      "id": "ping-check-default",
      "title": "Ping check (default)",
      "role": "content",
      "text": "The ping check sends a [`PING`](https://redis.io/docs/latest/commands/ping) command and expects the usual\nreply. By default, it sends 3 probes with a 500 ms delay between them. Change this with the `WithProbes()`,\n`WithDelay()` and `WithTimeout()` options, and pass the check in the `HealthChecks`\nfield. The policy goes in `HealthCheckPolicy`:\n\n[code example]"
    },
    {
      "id": "lag-aware-check-redis-software-only",
      "title": "Lag-aware check (Redis Software only)",
      "role": "content",
      "text": "The lag-aware check uses the Redis Software\n[REST API](https://redis.io/docs/latest/operate/rs/references/rest-api)\nto check the replication lag between an Active-Active database and its other instances.\nThe member is considered healthy if the lag is within the tolerance.\n\nAdd the check to the `HealthChecks` list, alongside or instead of the ping check:\n\n[code example]\n\nOther options set the REST API port (default `9443`), the HTTP client, and the\nTransport Layer Security (TLS) settings, including a custom root certificate\nauthority and a client certificate.\n\nA lag-aware check can only clear a member to receive traffic again. It never evicts\nthe member that is currently active. While a member is active, the client still sends\nit a plain `PING` so that a dead endpoint is found."
    },
    {
      "id": "custom-health-checks",
      "title": "Custom health checks",
      "role": "content",
      "text": "To run your own check, implement the `redis.MultiDBHealthCheck` interface and add it to\n`HealthChecks`. To create a custom policy, implement `redis.MultiDBHealthCheckPolicy`.\n\n> [!WARNING]\n> Health checks, policies, failover strategies, failure detectors, hooks (added with\n> `AddHook` or `AddDatabaseHook`) and metrics recorders run inside the client's own\n> locks. Don't call the control methods or `Close` from them, because the call can\n> deadlock or corrupt the failover accounting. The `OnFailover`,\n> `OnActiveDatabaseChanged` and `OnCircuitStateChanged` callbacks are the only exceptions\n> that *can* call control methods."
    },
    {
      "id": "failover-callbacks",
      "title": "Failover callbacks",
      "role": "content",
      "text": "The client calls your functions when its state changes. Set them as fields of\n`MultiDBOptions`. Each callback runs on its own queue, so it doesn't block commands.\n\n[code example]\n\n`OnActiveDatabaseChanged` also fires when you switch members by hand."
    },
    {
      "id": "control-the-client-at-runtime",
      "title": "Control the client at runtime",
      "role": "content",
      "text": "`MultiDBClient` provides these methods to inspect and change the client while it runs:\n\n| Method | Description |\n| --- | --- |\n| `ActiveDatabaseID()` | Returns the number of the active member, or `-1` if none is selected. |\n| `SetActiveDatabase(ctx, id)` | Switches to a member after a fresh health probe. Returns `redis.ErrTargetUnhealthy` if the probe fails, `redis.ErrDatabaseDisabled` if the weight is `-1`, or `redis.ErrDatabaseNotFound` for an unknown number. |\n| `ForceActiveDatabase(ctx, id)` | Switches to a member with no health probe, including a disabled one. |\n| `AddDatabase(ctx, cfg)` | Adds a member and returns its number. |\n| `RemoveDatabase(ctx, id)` | Removes a member. You can't remove the active member. |\n| `SetWeight(id, weight)` | Changes a member's weight. You can't disable the active member or the last enabled member. |\n| `SetAutoFallback(enabled)` | Turns automatic fallback on or off. |\n\nMember numbers are stable. If you remove a member, go-redis never reuses its number."
    },
    {
      "id": "observability",
      "title": "Observability",
      "role": "content",
      "text": "The `redisotel-native` package records MultiDB metrics when you enable the\n`MetricGroupFlagMultiDB` metric group. See\n[Observability](https://redis.io/docs/latest/develop/clients/go/observability) to set up\nOpenTelemetry (OTel) metrics. You enable the group when you initialize the\nobservability instance, before you create the client:\n\n[code example]\n\nThe `MultiDBClient` then records to this instance with no further setup.\n\n| Metric | Description |\n| --- | --- |\n| `redis.client.multidb.failovers` | Number of failovers, with the reason as an attribute. |\n| `redis.client.multidb.failover.duration` | Time taken by each failover. |\n| `redis.client.multidb.active_database.changes` | Number of active-member changes, including fallbacks and manual switches. |\n| `redis.client.multidb.circuit_breaker.state_changes` | Number of circuit breaker state changes. |\n| `redis.client.multidb.health_checks` | Number of health checks, with the result as an attribute. |\n| `redis.client.multidb.health_check.duration` | Time taken by each health check. |\n\nThe metrics identify a member by its host name only, so two members on the same host\nlook the same."
    },
    {
      "id": "troubleshooting",
      "title": "Troubleshooting",
      "role": "errors",
      "text": ""
    },
    {
      "id": "newmultidbclient-fails-with-errinsufficienthealthydatabases",
      "title": "`NewMultiDBClient` fails with `ErrInsufficientHealthyDatabases`",
      "role": "content",
      "text": "Fewer members passed the first health check than the `InitialDBState` field of\n`MultiDBOptions` requires. Check that the members are reachable from the app. If some\nmembers start late, pass a context with a deadline to `NewMultiDBClient` so the client\nkeeps retrying, or set `InitialDBState` to `redis.InitialDBStateOneAvailable`."
    },
    {
      "id": "a-failing-command-blocks-for-a-long-time-before-failover",
      "title": "A failing command blocks for a long time before failover",
      "role": "content",
      "text": "Check that you left `MaxRetries` unset in each member's `Options` or `ClusterOptions`.\nAlso check the `DialTimeout`, `ReadTimeout` and `WriteTimeout` fields in each member's\n`Options` or `ClusterOptions`. The circuit breaker trips after a number of failed commands equal to `FailureThreshold` - you should ensure each command fails quickly.\n\nA command on a cluster member takes longer to fail than one on a standalone member.\nWith 1 second timeouts, a command against an unresponsive three-node cluster takes\nabout 4 seconds to return an error, so the default threshold of five failed commands takes about 20\nseconds to open the circuit. Use shorter timeouts in the member's `ClusterOptions`, or a\nlower `FailureThreshold` in `CircuitBreakerConfig` to reduce this time."
    },
    {
      "id": "the-client-doesnt-fail-back-after-the-preferred-member-recovers",
      "title": "The client doesn't fail back after the preferred member recovers",
      "role": "content",
      "text": "Failback waits for the circuit's `GracePeriod` (in `CircuitBreakerConfig`) and then for\nthe next `AutoFallbackInterval` check. Check that `AutoFallbackInterval` isn't negative."
    }
  ],
  "examples": [
    {
      "id": "failover-configuration-ex0",
      "language": "go",
      "code": "import (\n\t\"context\"\n\t\"time\"\n\n\t\"github.com/redis/go-redis/v9\"\n)\n\n// A deadline bounds NewMultiDBClient only (see \"Start the client\").\nstartCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\ndefer cancel()\n\nclient, err := redis.NewMultiDBClient(startCtx, &redis.MultiDBOptions{\n\tClients: []redis.MultiDBClientConfig{\n\t\t{Options: &redis.Options{Addr: \"<east-host>:<port>\"}, Weight: 1.0},\n\t\t{Options: &redis.Options{Addr: \"<west-host>:<port>\"}, Weight: 0.5},\n\t},\n})\nif err != nil {\n\tpanic(err)\n}\ndefer client.Close()\n\nerr = client.Set(context.Background(), \"key\", \"value\", 0).Err() // Served by east until it fails.",
      "section_id": "failover-configuration"
    },
    {
      "id": "circuit-breaker-ex0",
      "language": "go",
      "code": "CircuitBreakerConfig: &redis.MultiDBCircuitBreakerConfig{\n\tFailureThreshold: 3,\n\tGracePeriod:      10 * time.Second,\n},",
      "section_id": "circuit-breaker"
    },
    {
      "id": "failure-detector-ex0",
      "language": "go",
      "code": "FailureDetectorConfig: &redis.MultiDBFailureDetectorConfig{\n\tMinNumFailures:       2,\n\tFailureRateThreshold: 0.5,\n\tWindow:               2 * time.Second,\n},",
      "section_id": "failure-detector"
    },
    {
      "id": "retries-ex0",
      "language": "go",
      "code": "CommandRetries: -1, // No retries.",
      "section_id": "retries"
    },
    {
      "id": "when-no-member-is-healthy-ex0",
      "language": "go",
      "code": "err := client.Set(ctx, \"key\", \"value\", 0).Err()\nswitch {\ncase errors.Is(err, redis.ErrPermanentlyNotAvailable):\n\t// Every member has failed repeatedly. Alert and back off.\ncase errors.Is(err, redis.ErrTemporarilyNotAvailable):\n\t// A failover is in progress. Retry shortly.\n}",
      "section_id": "when-no-member-is-healthy"
    },
    {
      "id": "ping-check-default-ex0",
      "language": "go",
      "code": "import \"github.com/redis/go-redis/v9/multidb\"\n\n// Fields of MultiDBOptions (or of a member's MultiDBClientConfig).\nHealthChecks: []redis.MultiDBHealthCheck{\n\tmultidb.NewPingHealthCheck(\n\t\tmultidb.WithProbes(2),\n\t\tmultidb.WithDelay(200*time.Millisecond),\n\t),\n},\nHealthCheckPolicy: multidb.NewHealthyMajorityPolicy(),",
      "section_id": "ping-check-default"
    },
    {
      "id": "lag-aware-check-redis-software-only-ex0",
      "language": "go",
      "code": "HealthChecks: []redis.MultiDBHealthCheck{\n\tmultidb.NewLagAwareHealthCheck(\n\t\tmultidb.WithLagAwareBaseURL(\"https://<cluster-fqdn>:9443\"),\n\t\tmultidb.WithLagAwareBasicAuth(\"<username>\", \"<password>\"),\n\t\tmultidb.WithLagAwareTolerance(2000), // milliseconds; the default is 5000\n\t),\n},",
      "section_id": "lag-aware-check-redis-software-only"
    },
    {
      "id": "failover-callbacks-ex0",
      "language": "go",
      "code": "// Fields of MultiDBOptions.\nOnFailover: func(ctx context.Context, from, to int) {\n\tlog.Printf(\"failing over from member %d to member %d\", from, to)\n},\nOnActiveDatabaseChanged: func(from, to int) {\n\tlog.Printf(\"active member is now %d (was %d)\", to, from)\n},\nOnCircuitStateChanged: func(id int, from, to string) {\n\tlog.Printf(\"member %d circuit: %s -> %s\", id, from, to)\n},",
      "section_id": "failover-callbacks"
    },
    {
      "id": "observability-ex0",
      "language": "go",
      "code": "import redisotel \"github.com/redis/go-redis/extra/redisotel-native/v9\"\n\notelInstance := redisotel.GetObservabilityInstance()\nconfig := redisotel.NewConfig().\n\tWithEnabled(true). // Metrics are off unless you enable them.\n\tWithMetricGroups(redisotel.MetricGroupFlagMultiDB)\n\nif err := otelInstance.Init(config); err != nil {\n\tpanic(err)\n}",
      "section_id": "observability"
    }
  ]
}
