{
  "schema_version": 3,
  "id": "develop/clients/nodejs/failover",
  "title": "Client-side geographic failover",
  "url": "https://redis.io/docs/latest/develop/clients/nodejs/failover/",
  "summary": "Improve reliability using the failover features of node-redis.",
  "tags": [
    "docs",
    "develop",
    "stack",
    "oss",
    "rs",
    "rc",
    "oss",
    "kubernetes",
    "clients"
  ],
  "last_updated": "2026-11-30T16:18:16Z",
  "page_type": "content",
  "content_hash": "dcfa8e80382ff6f4cb75072e58f98347c9eede460996d9970f03400e01f5a6e8",
  "sections": [
    {
      "id": "overview",
      "title": "Overview",
      "role": "overview",
      "text": "node-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 node-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 node-redis v6.4.0 and later."
    },
    {
      "id": "failover-configuration",
      "title": "Failover configuration",
      "role": "content",
      "text": "The example below shows a simple case with a list of two servers,\n`redis-east` and `redis-west`, where `redis-east` is the preferred\ntarget. If `redis-east` fails, node-redis should fail over to\n`redis-west`.\n\nSupply the weighted endpoints in the `databases` list when you call\n`createMultiDbClient()`\n(see [Selecting a failover target](https://redis.io/docs/latest/develop/clients/failover#selecting-a-failover-target) for a full description of how\nthe weighted list is used).\nUse the `weight` option to order the endpoints, with the highest\nweight being tried first.\n\n[code example]\n\n`createMultiDbClient()` returns an object with two fields:\n\n- `client` has the same commands as the client that `createClient()` returns, and routes each\n  command to the active database. Use it in place of your usual client.\n  It also emits the [failover events](#failover-events).\n- `controller` lets you inspect and change the set of databases at runtime\n  (see [Managing databases at runtime](#managing-databases-at-runtime)).\n\n`connect()` connects to every database and resolves when enough of them pass\nan initial health check (see the `initialAvailability` option in\n[General failover configuration](#general-failover-configuration)).\nIf the first call to `connect()` rejects, the client is unusable, so create a new\none to try again."
    },
    {
      "id": "endpoint-configuration",
      "title": "Endpoint configuration",
      "role": "content",
      "text": "Each entry in the `databases` list supports the following options:\n\n| Option | Description |\n| --- | --- |\n| `options` | The options to pass to the internal client for this endpoint. These are the same options you pass to `createClient()` (see [Connect to the server](https://redis.io/docs/latest/develop/clients/nodejs/connect)). |\n| `id` | Identifier for the endpoint, used in events and in `controller` methods. Default is `db-<n>`, where `<n>` is the position of the endpoint in the list. |\n| `weight` | Priority of the endpoint, from `0` to `1`, with higher values being tried first. If two endpoints have the same weight, the one that appears first in the list is preferred. Default is `1`. |\n| `poolOptions` | Connection pool options for this endpoint. Only available with `createMultiDbClientPool()` (see [Client types](#client-types)). |"
    },
    {
      "id": "client-types",
      "title": "Client types",
      "role": "content",
      "text": "node-redis provides a separate factory function for each type of client. All\nthe endpoints in one failover client must be the same type.\n\n| Function | Endpoint type | `options` field |\n| --- | --- | --- |\n| `createMultiDbClient()` | Standalone client | Options for `createClient()` |\n| `createMultiDbClientPool()` | Client pool | Options for `createClientPool()` |\n| `createMultiDbCluster()` | [Redis Cluster](https://redis.io/docs/latest/develop/clients/nodejs/connect#connect-to-a-redis-cluster) | Options for `createCluster()` |\n| `createMultiDbSentinel()` | [Redis Sentinel](https://redis.io/docs/latest/develop/clients/nodejs/connect#connect-to-redis-sentinel) | Options for `createSentinel()` |"
    },
    {
      "id": "timeouts-for-unresponsive-servers",
      "title": "Timeouts for unresponsive servers",
      "role": "content",
      "text": "A server that stops responding without closing the connection (for example, after\na network partition) doesn't cause commands to fail. Health checks detect the problem\nand fail over, but commands that were already sent to the failed server\nwait for a reply until that server responds again.\n\nTo make these commands fail instead, set `socket.socketTimeout` in the `options`\nfor each endpoint. When no data arrives on the connection within the timeout,\npending commands reject with `SocketTimeoutError`. By default, node-redis doesn't\nreconnect after a socket timeout, which would keep the endpoint out of the failover\nset permanently, so you must also supply a `socket.reconnectStrategy` that reconnects\n(see [Reconnect after disconnection](https://redis.io/docs/latest/develop/clients/nodejs/connect#reconnect-after-disconnection)):\n\n[code example]\n\nAlternatively, use the experimental `rejectInFlight` command option, which makes the\ncommand `timeout` apply to commands that were already sent. Set it in the\n`commandOptions` for each endpoint. A command that times out rejects with\n`TimeoutReadError`, and the connection stays open, so you don't need a custom\n`reconnectStrategy`:\n\n[code example]\n\nThe server might have run a command that rejects with `TimeoutReadError`, so retry it\nonly if it is safe to repeat."
    },
    {
      "id": "circuit-breaker-configuration",
      "title": "Circuit breaker configuration",
      "role": "content",
      "text": "The `failureDetector` option configures the circuit breaker\n(see [Detecting connection problems](https://redis.io/docs/latest/develop/clients/failover#detecting-connection-problems) for more information on how the\ncircuit breaker works). The circuit breaker triggers a failover when both\n`minNumOfFailures` and `failureRateThreshold` are reached within the sliding window:\n\n| Option | Description |\n| --- | --- |\n| `windowSize` | Duration in milliseconds to keep failures and successes in the sliding window. Default is `2000`. |\n| `minNumOfFailures` | Minimum number of failures that must occur to trigger a failover. Set this to `0` to use only the failure rate. Default is `1000`. |\n| `failureRateThreshold` | Percentage of failed commands required to trigger a failover. Set this to `0` to use only the number of failures. Default is `10`. |\n| `errorFilter` | Function that decides which errors count as failures. Default is `defaultErrorFilter`. |\n\n[code example]\n\n`defaultErrorFilter` counts connection errors, timeouts, and error replies that\nreport a problem with the server, such as `LOADING`, `BUSY`, `MASTERDOWN`, `CLUSTERDOWN`,\n`READONLY`, `NOREPLICAS`, and `MISCONF`. Other error replies, such as `WRONGTYPE` or\n`OOM`, are caused by the command rather than the server, so they don't count as failures.\nTo count extra errors, combine your own test with `defaultErrorFilter`:\n\n[code example]"
    },
    {
      "id": "retries",
      "title": "Retries",
      "role": "content",
      "text": "node-redis doesn't retry commands when a failover happens:\n\n- Commands that are waiting for a reply from the failed server reject with that server's error.\n- For standalone and pool endpoints, commands that are queued but not yet sent\n  reject with `CommandAbandonedError`. This prevents them from running\n  on the failed server when it reconnects later.\n- Commands that you issue after the failover go to the new active database.\n\nHandle these errors in your app, and retry the command if it is safe to do so\n(see [Retry with backoff](https://redis.io/docs/latest/develop/clients/nodejs/error-handling#pattern-3-retry-with-backoff)).\nThe databases replicate asynchronously, so a write that the failed server acknowledged\nmight not be present on the new active database."
    },
    {
      "id": "failback-configuration",
      "title": "Failback configuration",
      "role": "content",
      "text": "Automatic failback is disabled by default. Use the following options to configure it:\n\n| Option | Description |\n| --- | --- |\n| `autoFallbackInterval` | Time interval in milliseconds between automatic failback attempts. Each attempt switches to a healthy endpoint with a higher weight than the active one, if there is one. Set this to `-1` to disable automatic failback. Default is `-1`. |\n| `gracePeriod` | Duration in milliseconds to keep an unhealthy endpoint disabled before checking whether it has recovered. Default is `60000`. |"
    },
    {
      "id": "general-failover-configuration",
      "title": "General failover configuration",
      "role": "content",
      "text": "There are also a few other options you can pass to `createMultiDbClient()` to control the failover behavior:\n\n| Option | Description |\n| --- | --- |\n| `maxFailoverAttempts` | Number of attempts to fail over to a new endpoint before giving up. Default is `10`. |\n| `delayBetweenFailoverAttempts` | Time interval in milliseconds between successive failover attempts. Default is `12000`. |\n| `initialAvailability` | How many endpoints must pass the initial health check for `connect()` to succeed: `'ALL'`, `'MAJORITY'` (more than half), or `'ONE'`. Default is `'MAJORITY'`. With two endpoints, `'MAJORITY'` means both, so use `'ONE'` if your app should start when one endpoint is down. |\n| `failoverStrategy` | Custom strategy object to select the endpoint to fail over to. Default is `WeightBasedStrategy`, which selects the healthy endpoint with the highest weight. |"
    },
    {
      "id": "failover-events",
      "title": "Failover events",
      "role": "content",
      "text": "You may want to take some custom action when a failover occurs. For example, you could log a warning, increment a metric, or externally persist the cluster connection state.\n\nListen for the `failover` event on the client to detect when the active database changes:\n\n[code example]\n\nThe client emits the following events:\n\n| Event | Payload | Emitted when |\n| --- | --- | --- |\n| `connect` | None | `connect()` starts connecting to the endpoints. |\n| `ready` | None | Enough endpoints have passed the initial health check and the client has selected an active database. |\n| `end` | None | `close()` or `destroy()` has completed. |\n| `failover` | `{ from, to, reason }` | The active database changed. `reason` is one of `failure-detector`, `health-check`, `connection-ended`, `forced`, or `active-removed`. |\n| `fallback` | `{ from, to }` | Automatic failback switched to an endpoint with a higher weight. |\n| `database-unhealthy` | `{ id, cause }` | An endpoint failed and was disabled. |\n| `database-recovered` | `{ id }` | A disabled endpoint passed its health checks again. |\n| `all-databases-down` | `{ attempt, maxAttempts }` | A failover attempt found no healthy endpoint (see [Behavior when all endpoints are unhealthy](#behavior-when-all-endpoints-are-unhealthy)). |\n| `terminated` | `{ attempts }` | The client used all its failover attempts and stopped. |\n| `error` | `Error` | A background task, such as a health check, failed. |\n| `member-error` | `{ id, error }` | The internal client for an endpoint reported an error. |\n| `member-ready` | `{ id }` | The internal client for an endpoint connected or reconnected. |\n| `member-end` | `{ id }` | The internal client for an endpoint stopped trying to reconnect. |\n\nUnlike the client that `createClient()` returns, the failover client doesn't\nthrow if it emits an `error` event that has no listener."
    },
    {
      "id": "health-check-configuration",
      "title": "Health check configuration",
      "role": "content",
      "text": "Each health check consists of one or more separate \"probes\", each of which is a simple\ntest (such as a [`PING`](https://redis.io/docs/latest/commands/ping) command) to determine if the\ndatabase is available. The results of the separate probes are combined\nusing a configurable policy to determine if the database is healthy.\nnode-redis checks every endpoint periodically, including the active one.\nA disabled endpoint must pass `numProbes` probes in a row after its `gracePeriod`\nto become available again.\n\nThe `healthCheck` option accepts the following fields:\n\n| Option | Description |\n| --- | --- |\n| `interval` | Time interval in milliseconds between successive health checks (each of which may consist of multiple probes). Default is `5000`. |\n| `numProbes` | Number of separate probes performed during each health check. Default is `3`. |\n| `delayBetweenProbes` | Delay in milliseconds between probes during a health check. Default is `500`. |\n| `timeout` | Timeout in milliseconds for each probe. This must be less than `interval`. Default is `3000`. |\n| `policy` | Policy for determining database health from the separate probes of a health check: `'ALL'` (all probes must succeed), `'MAJORITY'` (more than half the probes must succeed), or `'ANY'` (at least one probe must succeed). Default is `'ALL'`. |\n\nUse the separate `healthChecks` option to supply a list of health check strategies.\nAn endpoint is healthy only if all the strategies in the list succeed. The default list\ncontains just [`DefaultHealthCheck`](#defaulthealthcheck-default).\n\n[code example]\n\nProbes use the same connection as your commands. A blocking command such as\n[`BLPOP`](https://redis.io/docs/latest/commands/blpop) with no timeout, or a slow script,\ncan delay a probe until it times out and trigger a failover from a healthy server.\nRun blocking commands on a separate client, or set `healthCheck.timeout`\nhigher than their longest expected run time.\n\nThe sections below explain the available strategies in more detail."
    },
    {
      "id": "defaulthealthcheck-default",
      "title": "`DefaultHealthCheck` (default)",
      "role": "content",
      "text": "The default strategy, `DefaultHealthCheck`, periodically sends a Redis\n[`PING`](https://redis.io/docs/latest/commands/ping) command\nand checks that it gives the expected response. Any unexpected response\nor error indicates an unhealthy server. Although `DefaultHealthCheck` is\nvery simple, it is a good basic approach for most Redis deployments."
    },
    {
      "id": "lag-aware-health-check",
      "title": "`LagAwareHealthCheck` (Redis Software only)",
      "role": "content",
      "text": "`LagAwareHealthCheck` is designed specifically for\nRedis Software [Active-Active](https://redis.io/docs/latest/operate/rs/databases/active-active)\ndeployments. It determines the health of the server by using the\n[REST API](https://redis.io/docs/latest/operate/rs/references/rest-api) to check the\nsynchronization lag between a specific database and the others in the Active-Active\nsetup. If the lag is within a specified tolerance, the server is considered healthy.\n\nAdd a `LagAwareHealthCheck` instance to the `healthChecks` list. The `restEndpoint`\nand `bdbUid` options accept either a single value or a function that receives the\nendpoint `id`, so you can supply a different value for each endpoint:\n\n[code example]\n\nThe `LagAwareHealthCheck` constructor accepts the following options:\n\n| Option | Description |\n| --- | --- |\n| `restEndpoint` | Base URL of the Redis Software cluster's REST API, such as `https://cluster.example.com:9443`. This is the cluster address, not the database endpoint. |\n| `bdbUid` | The database's ID in the REST API. |\n| `credentials` | Object with `username` and `password` fields for basic authentication. |\n| `lagTolerance` | Tolerable synchronization lag between databases in milliseconds. Default is `5000`. |\n| `requestTimeout` | REST API request timeout in milliseconds. Default is `3000`. |\n| `requestOptions` | Extra options to pass to each `fetch()` request, such as a custom `dispatcher` for TLS settings. |\n| `onProbeError` | Function that receives the error and the endpoint `id` when a probe fails. Without it, a misconfigured health check looks the same as an unhealthy database. |\n\n`LagAwareHealthCheck` uses the Node.js built-in `fetch()` function. To trust a custom\ncertificate authority (CA), either set the `NODE_EXTRA_CA_CERTS` environment variable or pass an\n[undici](https://undici.nodejs.org/) `dispatcher` in `requestOptions`."
    },
    {
      "id": "custom-health-check-strategy",
      "title": "Custom health check strategy",
      "role": "content",
      "text": "You can supply your own custom health check strategy with an object that\nhas a `probe()` method.\nFor example, you might use this to integrate with external monitoring tools or\nto implement checks that are specific to your application. Add an\ninstance of your custom class to the `healthChecks` list, as with\n[`LagAwareHealthCheck`](#lag-aware-health-check).\n\n`probe()` receives a `target` object with the endpoint's `id` and a `sendCommand()`\nmethod. It must return a promise that resolves to `true` if the endpoint is healthy\nor `false` if it isn't. A rejected promise also counts as a failed probe.\n\nThe example below\nshows a simple custom strategy that sends a Redis [`ECHO`](https://redis.io/docs/latest/commands/echo)\ncommand and checks for the expected response.\n\n[code example]"
    },
    {
      "id": "managing-databases-at-runtime",
      "title": "Managing databases at runtime",
      "role": "content",
      "text": "Although you will typically configure all databases during the\ninitial connection, you can also modify the configuration at runtime.\nUse the `controller` object to add and remove database endpoints, and update their weights:\n\n[code example]"
    },
    {
      "id": "manual-failover",
      "title": "Manual failover",
      "role": "content",
      "text": "By default, the client selects the healthy endpoint with the highest weight.\nHowever, you can use `controller.setActiveDatabase()` to select which database to use manually:\n\n[code example]\n\n`setActiveDatabase()` runs a health check on the database first and rejects if the\ncheck fails. The client then suspends automatic failback until you call `releasePin()`.\n`releasePin()` doesn't switch databases itself: the client stays on the selected\ndatabase until automatic failback (if you enabled it) or a failover selects another one.\nIf the selected database fails, the client fails over automatically and resumes\nautomatic failback.\n\nIf you decide to implement manual failover, you will need a way for external systems to trigger this method in your application. For example, if your application exposes a REST API, you might consider creating a REST endpoint to call `setActiveDatabase()`."
    },
    {
      "id": "pubsub-and-re-subscription",
      "title": "Pub/Sub and re-subscription",
      "role": "content",
      "text": "The failover client supports [Pub/Sub](https://redis.io/docs/latest/develop/pubsub)\nmessaging with automatic re-subscription during failover.\nThis means you don't have to detect failovers and re-subscribe manually.\nWhen the active database changes, the client moves all your channel, pattern,\nand sharded channel subscriptions to the new active database, and removes them\nfrom the previous one.\nThis works for all client types except `createMultiDbClientPool()`, which doesn't\nsupport Pub/Sub.\n\nFor reliable Pub/Sub delivery during failover, use failover clients\nfor *both* publishers and subscribers. Use `client.duplicate()` to create a separate\nfailover client for subscribing. `duplicate()` returns a new `client` and\n`controller` pair, which you must connect separately:\n\n[code example]\n\n> [!NOTE]\n> Messages published between the failover and the completion of the re-subscription\n> are lost. Message loss can also occur if the publisher fails over to the new database\n> before the subscriber."
    },
    {
      "id": "transactions-and-connection-state",
      "title": "Transactions and connection state",
      "role": "content",
      "text": "The connection state for a database doesn't move to the new active database when\na failover happens. This has the following effects:\n\n- **Transactions**: A transaction runs entirely on the database that was active when you\n  called `multi()`. If a failover happens before you call `exec()`, `exec()`\n  commits nothing and rejects with `WatchError` if you called\n  [`WATCH`](https://redis.io/docs/latest/commands/watch), or `CommandAbandonedError` otherwise.\n  Call `multi()` each time you run a transaction, and retry the whole\n  `WATCH`/`MULTI`/`EXEC` sequence on `WatchError` (see\n  [Watch keys for changes](https://redis.io/docs/latest/develop/clients/nodejs/transpipe#watch-keys-for-changes)).\n- **Scan iterators**: An iterator such as `scanIterator()` reads from the database\n  that was active when you created it. If a failover happens while you iterate, the\n  iterator rejects with `CommandAbandonedError`. Create a new iterator to scan the\n  new active database.\n- **`legacy()`**: The callback-based interface that `legacy()` returns always uses\n  the database that was active when you created it.\n- **Database index**: The [`SELECT`](https://redis.io/docs/latest/commands/select) command isn't supported.\n  Set the `database` option in the `options` for each endpoint instead.\n- **`MONITOR`**: The [`MONITOR`](https://redis.io/docs/latest/commands/monitor) command isn't supported.\n  Use a separate client to monitor a specific server.\n- **Client-side caching**: Set the `clientSideCache` option in the `options` for each\n  endpoint (see\n  [Connect using client-side caching](https://redis.io/docs/latest/develop/clients/nodejs/connect#connect-using-client-side-caching)).\n  The `emitInvalidate` option isn't supported."
    },
    {
      "id": "behavior-when-all-endpoints-are-unhealthy",
      "title": "Behavior when all endpoints are unhealthy",
      "role": "content",
      "text": "In the extreme case where no endpoint is healthy, commands reject immediately with a\n`TemporarilyUnavailableError`. This indicates that the client is periodically checking\nto see if any endpoint becomes healthy again, and emits an `all-databases-down` event\nafter each unsuccessful attempt. The number of\ntimes it will keep checking is configured by the `maxFailoverAttempts` option and\nthe delay between attempts is configured by the `delayBetweenFailoverAttempts` option (see [General failover configuration](#general-failover-configuration)). With the default settings, `maxFailoverAttempts` * `delayBetweenFailoverAttempts`\ngives a period of 120 seconds to find a healthy endpoint.\n\nIf the client exhausts all the available failover attempts before any endpoint becomes\nhealthy again, it emits a `terminated` event and stops checking. After this, commands reject with\n`PermanentlyUnavailableError`. To recover, call `client.connect()` again after a suitable delay:\n\n[code example]"
    },
    {
      "id": "troubleshooting",
      "title": "Troubleshooting",
      "role": "errors",
      "text": "This section lists some common problems and their solutions."
    },
    {
      "id": "connect-fails-when-one-endpoint-is-down",
      "title": "`connect()` fails when one endpoint is down",
      "role": "content",
      "text": "With the default `initialAvailability` setting of `'MAJORITY'`, more than half the\nendpoints must pass the initial health check, which means both endpoints in a two-endpoint\nconfiguration. Set `initialAvailability` to `'ONE'` to let the client start when only one\nendpoint is available (see [General failover configuration](#general-failover-configuration))."
    },
    {
      "id": "excessive-or-constant-health-check-failures",
      "title": "Excessive or constant health check failures",
      "role": "content",
      "text": "If all health checks fail, you should first rule out authentication\nproblems with the Redis server and also make sure there are no persistent\nnetwork connectivity problems.\n\nIf you are using [`DefaultHealthCheck`](#defaulthealthcheck-default) or a\n[custom health check strategy](#custom-health-check-strategy),\ncheck that `healthCheck.timeout` is not too low for your network conditions,\nand that no blocking or long-running commands are delaying the probes\n(see [Health check configuration](#health-check-configuration)).\n\nFor\n[`LagAwareHealthCheck`](#lag-aware-health-check), check that `restEndpoint` and `bdbUid`\nare set correctly for each endpoint, and use the `onProbeError` option to log the cause\nof each failure. Note that health checks might be taking longer to\nexecute than you anticipated, so make sure your `requestTimeout` setting is not too low."
    },
    {
      "id": "no-failback-after-recovery",
      "title": "No failback after recovery",
      "role": "content",
      "text": "Automatic failback is disabled by default, so the client stays on the failover target\nuntil it fails. Set the `autoFallbackInterval` option to enable automatic failback\n(see [Failback configuration](#failback-configuration)).\n\nIf you set `socket.socketTimeout`, check that your `reconnectStrategy` reconnects\nafter a socket timeout (see\n[Timeouts for unresponsive servers](#timeouts-for-unresponsive-servers)). Otherwise,\nthe endpoint stops reconnecting and never becomes available again."
    },
    {
      "id": "slow-failback-after-recovery",
      "title": "Slow failback after recovery",
      "role": "content",
      "text": "If failback is too slow after a server recovers, you can try\nreducing the `autoFallbackInterval` and `healthCheck.interval` periods and also reducing the `gracePeriod`\nbefore failback is attempted (see [Failback configuration](#failback-configuration) and\n[Health check configuration](#health-check-configuration)\nfor more information about these options)."
    }
  ],
  "examples": [
    {
      "id": "failover-configuration-ex0",
      "language": "js",
      "code": "import { createMultiDbClient } from 'redis';\n\nconst { client, controller } = createMultiDbClient({\n  databases: [\n    {\n      id: 'east',\n      options: { url: 'redis://redis-east.example.com:14000' },\n      weight: 1\n    },\n    {\n      id: 'west',\n      options: { url: 'redis://redis-west.example.com:14000' },\n      weight: 0.5\n    }\n  ]\n});\n\nawait client.connect();\nawait client.set('key', 'value'); // Served by 'east' until it fails.",
      "section_id": "failover-configuration"
    },
    {
      "id": "timeouts-for-unresponsive-servers-ex0",
      "language": "js",
      "code": "const socket = {\n  // Health checks keep the connection active, so set this\n  // higher than `healthCheck.interval` (5000 ms by default).\n  socketTimeout: 10000,\n  reconnectStrategy: retries => Math.min(retries * 50, 2000)\n};\n\nconst { client, controller } = createMultiDbClient({\n  databases: [\n    {\n      id: 'east',\n      options: { url: 'redis://redis-east.example.com:14000', socket },\n      weight: 1\n    },\n    {\n      id: 'west',\n      options: { url: 'redis://redis-west.example.com:14000', socket },\n      weight: 0.5\n    }\n  ]\n});",
      "section_id": "timeouts-for-unresponsive-servers"
    },
    {
      "id": "timeouts-for-unresponsive-servers-ex1",
      "language": "js",
      "code": "const commandOptions = { timeout: 1000, rejectInFlight: true };\n\nconst { client, controller } = createMultiDbClient({\n  databases: [\n    {\n      id: 'east',\n      options: { url: 'redis://redis-east.example.com:14000', commandOptions },\n      weight: 1\n    },\n    {\n      id: 'west',\n      options: { url: 'redis://redis-west.example.com:14000', commandOptions },\n      weight: 0.5\n    }\n  ]\n});",
      "section_id": "timeouts-for-unresponsive-servers"
    },
    {
      "id": "circuit-breaker-configuration-ex0",
      "language": "js",
      "code": "const { client, controller } = createMultiDbClient({\n  databases: [ ... ],\n  failureDetector: {\n    minNumOfFailures: 500,\n    failureRateThreshold: 20,\n    windowSize: 5000\n  }\n});",
      "section_id": "circuit-breaker-configuration"
    },
    {
      "id": "circuit-breaker-configuration-ex1",
      "language": "js",
      "code": "import { createMultiDbClient, defaultErrorFilter } from 'redis';\n\nconst { client, controller } = createMultiDbClient({\n  databases: [ ... ],\n  failureDetector: {\n    errorFilter: err => defaultErrorFilter(err) || err.message.includes('MYERROR')\n  }\n});",
      "section_id": "circuit-breaker-configuration"
    },
    {
      "id": "failover-events-ex0",
      "language": "js",
      "code": "client.on('failover', ({ from, to, reason }) => {\n  console.warn(`Failover from ${from} to ${to} (${reason})`);\n});",
      "section_id": "failover-events"
    },
    {
      "id": "health-check-configuration-ex0",
      "language": "js",
      "code": "const { client, controller } = createMultiDbClient({\n  databases: [ ... ],\n  healthCheck: {\n    interval: 2000,\n    timeout: 1000,\n    numProbes: 2,\n    policy: 'MAJORITY'\n  }\n});",
      "section_id": "health-check-configuration"
    },
    {
      "id": "lag-aware-health-check-ex0",
      "language": "js",
      "code": "import { createMultiDbClient, LagAwareHealthCheck } from 'redis';\n\nconst { client, controller } = createMultiDbClient({\n  databases: [\n    {\n      id: 'east',\n      options: { url: 'redis://redis-east.example.com:14000' },\n      weight: 1\n    },\n    {\n      id: 'west',\n      options: { url: 'redis://redis-west.example.com:14000' },\n      weight: 0.5\n    }\n  ],\n  healthChecks: [\n    new LagAwareHealthCheck({\n      restEndpoint: id => id === 'east'\n        ? 'https://cluster-east.example.com:9443'\n        : 'https://cluster-west.example.com:9443',\n      bdbUid: 1,\n      credentials: { username: '<username>', password: '<password>' },\n      lagTolerance: 5000, // ms\n      onProbeError: (err, id) => console.error(`Health check failed for ${id}:`, err)\n    })\n  ]\n});",
      "section_id": "lag-aware-health-check"
    },
    {
      "id": "custom-health-check-strategy-ex0",
      "language": "js",
      "code": "class EchoHealthCheck {\n  async probe(target) {\n    const reply = await target.sendCommand(['ECHO', 'healthcheck']);\n    return reply === 'healthcheck';\n  }\n}\n\nconst { client, controller } = createMultiDbClient({\n  databases: [ ... ],\n  healthChecks: [new EchoHealthCheck()]\n});",
      "section_id": "custom-health-check-strategy"
    },
    {
      "id": "managing-databases-at-runtime-ex0",
      "language": "js",
      "code": "// Get the active database. This returns an object with the\n// `id`, `weight`, `circuitState`, and `role` fields.\nconst active = controller.getActiveDatabase();\n\n// Get all the databases, in configuration order.\nconst databases = controller.getDatabases();\n\n// Add a database. This runs a health check first and rejects\n// if the database is unhealthy, unless you set\n// `skipInitialHealthCheck` to `true`.\nawait controller.addDatabase({\n  id: 'south',\n  options: { url: 'redis://redis-south.example.com:14000' },\n  weight: 0.6\n});\n\n// Update the weight of a database.\ncontroller.setWeight('west', 0.9);\n\n// Replace a database with a new configuration.\nawait controller.replaceDatabase('west', {\n  id: 'west-2',\n  options: { url: 'redis://redis-west-2.example.com:14000' }\n});\n\n// Remove a database from the failover set. If you remove the active\n// database, the client fails over to another one first.\nawait controller.removeDatabase('south');\n\n// Enable automatic failback with a 2-minute interval\n// (or pass `false` to disable it).\ncontroller.setAutoFallback(120000);",
      "section_id": "managing-databases-at-runtime"
    },
    {
      "id": "manual-failover-ex0",
      "language": "js",
      "code": "// Health-check 'west', then make it the active database.\nawait controller.setActiveDatabase('west');\n\n// Resume automatic failback.\ncontroller.releasePin();",
      "section_id": "manual-failover"
    },
    {
      "id": "pubsub-and-re-subscription-ex0",
      "language": "js",
      "code": "const { client: subscriber } = client.duplicate();\nawait subscriber.connect();\n\nawait subscriber.subscribe('news', message => {\n  console.log(message);\n});\n\n// If a failover happens here, the subscription is automatically\n// re-established on the new active database.\nawait client.publish('news', 'Hello');",
      "section_id": "pubsub-and-re-subscription"
    },
    {
      "id": "behavior-when-all-endpoints-are-unhealthy-ex0",
      "language": "js",
      "code": "client.on('terminated', () => {\n  setTimeout(() => {\n    client.connect().catch(err => console.error('Reconnect failed:', err));\n  }, 30000);\n});",
      "section_id": "behavior-when-all-endpoints-are-unhealthy"
    }
  ]
}
