# Multi-database client (automatic failover) > :warning: The multi-db API is experimental and may change in a future release. The multi-db client holds connections to several equivalent Redis databases — for example Active-Active replicas in different regions — and routes all traffic to one *active* member. When the active member fails, traffic switches to the healthiest remaining member automatically. All members must be of the same kind: standalone clients, pools, clusters, or sentinel deployments (one factory per kind). ```javascript import { createMultiDbClient } from 'redis'; const { client, controller } = createMultiDbClient({ databases: [ { id: 'east', options: { url: 'redis://east.example.com:6379' }, weight: 1 }, { id: 'west', options: { url: 'redis://west.example.com:6379' }, weight: 0.5 } ] }); client.on('failover', ({ from, to, reason }) => console.log(`failover ${from} -> ${to} (${reason})`)); await client.connect(); await client.set('key', 'value'); // served by 'east' until it fails ``` Every factory returns `{ client, controller }`: - `client` is the corresponding base client type (`RedisClientType`, `RedisClientPoolType`, `RedisClusterType`, `RedisSentinelType`) plus a typed event surface (`MultiDbClientType`) — a drop-in. Command methods, module namespaces (`client.json.*`), and derived views forward to the active member; `connect`/`close`/`destroy`/`quit` fan out across all members; every event fires here (see Events). - `controller` is the admin surface: inspection, weights, runtime add/remove, forced failover. It emits nothing — the client is the event surface. Factories: `createMultiDbClient`, `createMultiDbClientPool`, `createMultiDbCluster`, `createMultiDbSentinel` (from `@redis/client`; the `redis` package's `createMultiDbClient` pre-registers the Stack modules like its `createClient`). ## How selection works Each member carries a weight in `[0, 1]` (default 1) and a circuit breaker (`CLOSED` → `OPEN` → `HALF_OPEN`). The active member is always the highest-weight member with a `CLOSED` circuit; ties go to the earlier-configured member. - **Failure detection.** Every command outcome on the non-pinned surfaces — plain commands, module/function/script namespaces, derived views, and transaction executions — plus the active member's connection errors feed a sliding-window failure detector. Only the pinned surfaces listed under caveats (scan iterators, `legacy()`) bypass it. It trips when, within `windowSize`, the failure count reaches `minNumOfFailures` **and** the failure rate reaches `failureRateThreshold` percent (setting either to `0` disables that condition). A trip opens the active member's circuit and fails over. - **Background health checks.** Every member — active included — is probed on `healthCheck.interval` (default: PING). A failing active member fails over; a failing passive member is announced unhealthy. An `OPEN` circuit rests for `gracePeriod`, then recovery probes must pass `numProbes` consecutive times to close it again. - **All members down.** Commands fail fast with `TemporarilyUnavailableError` while the client retries selection every `delayBetweenFailoverAttempts`, up to `maxFailoverAttempts` times. After that the client is permanently unavailable: commands fail with `PermanentlyUnavailableError` and background checking stops. - **Fallback.** Off by default. With `autoFallbackInterval` set (or `controller.setAutoFallback(ms)`), the client periodically returns to a strictly higher-weight healthy member, emitting `fallback`. ## Configuration `databases` is required; each entry is a `DatabaseConfig`: | Field | Default | Meaning | | --- | --- | --- | | `options` | required | unchanged base client options for this member | | `id` | `db-` | stable identifier used in descriptors, events and controller calls | | `weight` | `1` | selection weight in `[0, 1]` | | `poolOptions` | — | pool factory only: per-member pool sizing | | `skipInitialHealthCheck` | `false` | honored only via `controller.addDatabase` | All other options are flat on the factory call: | Option | Default | Meaning | | --- | --- | --- | | `gracePeriod` | `60000` | ms an `OPEN` circuit rests before recovery probing | | `healthCheck.interval` | `5000` | ms between background check rounds per member | | `healthCheck.timeout` | `3000` | ms per probe (must be < `interval`); member connects are bounded by the whole probe-round budget (`numProbes` × `timeout` + inter-probe delays) | | `healthCheck.numProbes` | `3` | probes per round / consecutive successes to close a circuit | | `healthCheck.delayBetweenProbes` | `500` | ms between probes within a round | | `healthCheck.policy` | `'ALL'` | round aggregation: `ALL`, `MAJORITY` or `ANY` (early exit) | | `healthChecks` | `[DefaultHealthCheck]` | custom check chain — every check must pass | | `failureDetector` | thresholds below | custom `FailureDetector` instance, or thresholds for the default | | `failureDetector.minNumOfFailures` | `1000` | failures within the window; `0` = rate-only | | `failureDetector.failureRateThreshold` | `10` | failure rate (%); `0` = count-only | | `failureDetector.windowSize` | `2000` | sliding window in ms | | `failureDetector.errorFilter` | `defaultErrorFilter` | which errors count as failures (see below) | | `failoverStrategy` | `WeightBasedStrategy` | custom selection strategy | | `maxFailoverAttempts` | `10` | selection retries before permanent unavailability | | `delayBetweenFailoverAttempts` | `12000` | ms between selection retries | | `autoFallbackInterval` | `-1` (off) | ms between fallback evaluations | | `initialAvailability` | `'MAJORITY'` | members that must pass the initial check: `ALL`, `MAJORITY` or `ONE`. Majority is `floor(n/2)+1`, so with the common **two-member** setup it means **both** — pick `ONE` for a setup that should start degraded | `connect()` resolves only when `initialAvailability` is satisfied and an active member is selected; otherwise it rejects. A first `connect()` that rejects **destroys every member** — a rejected instance must not be reused. A repeat `connect()` on a client that has been ready rejects without tearing it down; if its re-probe failed the active member, the client fails over as it would on a background health check. A permanently unavailable client can be recovered with another `connect()`; `close()`/`destroy()` are terminal — `connect()` afterwards rejects, and a fresh start is `duplicate()` or a new factory call. ## Controller ```typescript controller.getActiveDatabase(); // DatabaseDescriptor { id, weight, circuitState, role } controller.getDatabases(); // all members, in config order await controller.addDatabase({ id: 'south', options: { url: '...' }, weight: 0.6 }); await controller.removeDatabase('south'); // removing the active member switches first await controller.replaceDatabase('west', { id: 'west-2', options: { url: '...' } }); // new id: joins first, old leaves after — the member COUNT never drops. Same id: // the old member leaves first, so the set transiently runs one member short. controller.setWeight('west', 0.9); controller.setAutoFallback(120_000); // or false to disable await controller.setActiveDatabase('west'); // forced failover: health-checked, then pinned controller.releasePin(); // resume automatic behavior ``` Forcing a member health-checks it first and rejects if the check fails. Automatic failover does NOT re-probe its target — it trusts the circuit state from the last background round, trading certainty for switch speed. A standby that died since its last check produces one quick secondary failover once the detector trips on it. A verified-healthy target's `OPEN` circuit is closed — the operator's knowledge overrides a stale state. While pinned, auto-fallback is suspended; automatic failover still runs if the pinned member fails, and clears the pin. ### Events The **client** is the single event surface (the controller emits nothing). Lifecycle events describe the multi-db client as a whole, not any one connection: | Event | Payload | Fired when | | --- | --- | --- | | `connect` | — | `connect()` started establishing the members | | `ready` | — | the availability policy is met and an active member serves (initial and recovery connects) | | `end` | — | a user-initiated `close()`/`destroy()` completed | | `terminated` | `{ attempts }` | the client went permanently unavailable; only `connect()` recovers it | | `error` | `Error` | a background task failed (pub/sub move, health-check round) | | `failover` | `{ from, to, reason }` | the active member switched (`failure-detector`, `health-check`, `connection-ended`, `forced`, `active-removed`) | | `fallback` | `{ from, to }` | auto-fallback returned to a higher-weight member | | `database-unhealthy` | `{ id, cause }` | a member's circuit opened | | `database-recovered` | `{ id }` | a member's circuit closed again | | `all-databases-down` | `{ attempt, maxAttempts }` | one failed selection attempt with no healthy member; recovery shows as `failover`, or as `database-recovered` when the member that was already active comes back | | `member-error` | `{ id, error }` | one member's client reported an error | | `member-ready` | `{ id }` | one member's client (re)connected | | `member-end` | `{ id }` | one member's client gave up reconnecting | Listener registration and removal work in every client state, including while every member is down. An `error` listener is optional: with none attached, background errors are dropped instead of crashing the process the way an unhandled EventEmitter `error` normally would. `member-*` payloads carry the member id — ids can be reused after a remove/add, so read the id per event rather than binding logic to a name captured long ago. ## Custom health checks and detectors A health check probes one member through a narrow handle (`{ id, sendCommand }`); scheduling and aggregation belong to the client. Checks chain: every check must pass. ```typescript import { createMultiDbClient, LagAwareHealthCheck } from 'redis'; const { client, controller } = createMultiDbClient({ databases: [/* ... */], healthChecks: [ new LagAwareHealthCheck({ restEndpoint: id => (id === 'east' ? 'https://east-cluster:9443' : 'https://west-cluster:9443'), bdbUid: 1, credentials: { username: 'admin', password: '...' }, lagTolerance: 5000 }) ] }); ``` `LagAwareHealthCheck` targets the Redis Enterprise cluster REST API's availability endpoint with lag verification: a member whose replication lag exceeds `lagTolerance` (default 5s) reports unhealthy even while it still answers commands. It uses Node's built-in `fetch`; for a custom CA, pass an undici dispatcher through `requestOptions` or use `NODE_EXTRA_CA_CERTS`. A custom `FailureDetector` implements `onCommandResult(ok, err?)`, `isFaulty()` and `reset()`. A custom `FailoverStrategy` implements `select(candidates)` over the exported read-only `FailoverCandidate` view (`{ id, weight, role, circuit: { state } }`), returning one of the given candidates with a `CLOSED` circuit — always a candidate it was given, never a copy — or `undefined` to escalate. ## Behavior contracts and caveats - **Commands are rejected on failover, never retried or replayed.** Commands awaiting a reply on the failing member reject with that member's error, exactly like a single client's reconnect. For standalone and pool members, commands still queued *unsent* on the dead member are rejected at the switch with `CommandAbandonedError` — without that, they would execute on the demoted member when it reconnects minutes later. Cluster and sentinel members keep their own queue lifecycles (unsent commands there follow the member's reconnect, unmigrated). Commands issued after the switch go to the new member, riding its offline queue if it is mid-reconnect. There is no automatic retry on the new member — surface the rejection to the application and let it decide. - **Eventual consistency.** Members are assumed to be asynchronously replicated. A switch offers no read-your-writes guarantee: a write acknowledged by the old member may not be visible on the new one. - **A failover invalidates outstanding WATCHes.** Watch state lives on one member's connection and cannot follow a switch, so a switch marks the session dirty: the next `EXEC` rejects with `WatchError` — the same retryable error a conflict or the base client's own reconnect produces — and the standard retry loop re-runs the whole watch/read/`EXEC` cycle on the new active member. `UNWATCH` and a settled `EXEC` clear the session. Nothing ever commits unguarded, and no transaction traffic continues on a demoted member. - **Connection session state does not follow a failover.** Runtime `SELECT` is rejected with an error — set `database` per member in its options instead; each member re-applies it on every reconnect. `MONITOR` is rejected the same way — it puts a connection into a permanent monitoring mode that cannot move with the traffic; attach it to an individual member. `emitInvalidate` on member options is rejected at configuration time: invalidation events fire on hidden member clients and cannot be forwarded soundly across a switch — use per-member `clientSideCache` (below). - **`ref()` / `unref()` fan out** over every member's socket (member kinds that expose them), and the intent is sticky: members added later come up matching it. - **Pub/sub.** On a switch, active subscriptions (channels, patterns, and sharded channels) move to the new member and are removed from the old one (so its recovery cannot double-deliver). Messages published between the switch and the re-subscribe completing are lost. This applies to standalone, cluster, and sentinel members. Pool members have no pub/sub surface (subscriptions need a dedicated connection the pool does not expose), so there is nothing to transfer. - **Client-side caching** works per member and needs no flush on switch: each member client maintains its own tracked cache, so reads after a failover are served by the new member. - **What counts as fault evidence.** The failure detector is fed by forwarded command outcomes and by data-path connection errors of the active member (a standalone/pool socket error, a cluster node error, a sentinel MASTER connection error). Sentinel replica, sentinel-node and pub/sub-proxy errors are tolerated by a healthy deployment and are never counted — they surface only as `member-error`. The default `errorFilter` (`defaultErrorFilter`, exported) counts connection errors, timeouts and error replies that report server state (`LOADING`, `BUSY`, `MASTERDOWN`, `CLUSTERDOWN`, `READONLY`, `NOREPLICAS`, `MISCONF`). Other error replies (`WRONGTYPE`, `CROSSSLOT`, `TRYAGAIN`, `OOM`, ...), WATCH conflicts and aborts are about the command, not the member: they count as traffic but not as failures. A `MULTI` error counts when any of its replies does. To extend the default, compose it: `errorFilter: err => defaultErrorFilter(err) || isMine(err)`. Hard-down members with the default offline queue are detected by health-check probe timeouts, not by command outcomes (queued commands do not reject until the switch abandons them). A standalone member that gives up reconnecting (`terminated`) also fails over at once; cluster and pool members rely on the probes. - **Probes share the command connection.** The default PING probe (and any custom check that uses `sendCommand`) runs on the member's own command connection or pool. A blocking or long-running command in flight (`BLPOP 0`, `XREAD BLOCK`, a slow script) can time a probe out and fail over away from a healthy member. Run blocking commands on a separate client, or set `healthCheck.timeout` above their longest expected run. - **Resource overhead.** N member connections are live the whole time (each kind's usual connection count), plus one background health-check timer per member and the detector's sliding window on the command path. The command hot path adds one indirection per call. - **Pinned surfaces.** A few handles bind to the member that was active when they were created and never follow a failover — create them per use, not at startup: - `multi()` — a transaction executes wholly on its pinned member; `exec()` rejects while every member is down and its outcome feeds the detector. If the active member changed since `multi()`, `exec()` and `execAsPipeline()` commit nothing: they reject with `WatchError` when a watch session exists (so the usual retry loop re-runs on the new member), and with `CommandAbandonedError` otherwise. A switch away and back still commits. An `EXEC` whose watch session was invalidated by a switch rejects with `WatchError` (see the WATCH caveat above). - scan iterators (`scanIterator` and friends) — SCAN cursors are member-specific, so an iterator cannot follow a switch: after the active member changes, its next batch rejects with `CommandAbandonedError` (a SCAN already in flight still yields), and it fails with its member's error if that member dies. While every member is down, creating one throws. - `legacy()` — the callback-style surface stays on its creation member; creating it while every member is down throws. Derived views (`withTypeMapping`, `withCommandOptions`, `withAbortSignal`, `asap`) are NOT pinned: they follow the active member per call, feed the detector, and reject while every member is down. `duplicate(overrides?)` returns a new unconnected `{ client, controller }` pair over the current live member set (a deliberate signature difference from the base client, mirrored by the type). With a custom failure detector, pass a factory (`failureDetector: () => new MyDetector()`) — `duplicate()` refuses a shared instance. - **Homogeneous members only.** One factory per topology; mixing kinds is not supported.