Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

make Redis client degrade gracefully and auto-recover when unreachable

aashud75a8dbf4e15
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 0bc0c6768b..95f87f107f 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -6,6 +6,16 @@ Format: `Context → Problem → Rule → Applies to`
---
+## ioredis retryStrategy returning null kills auto-recovery
+
+**Context:** Making the Redis client (`@carbon/kv`) resilient to outages (issue #1076).
+
+**Problem:** A `retryStrategy` that returns `null` after N attempts (e.g. `if (times > 3) return null`) tells ioredis to **stop reconnecting permanently**. Once Redis is briefly unreachable the client gives up and every later command fails with "Connection is closed." even after Redis is healthy again — the app never recovers without a process restart. Command-level timeouts/try-catch cannot fix this; it is a connection-lifecycle setting. Unit tests with `ioredis-mock` do NOT catch it — only a real kill-and-restart test does.
+
+**Rule:** For long-running servers, `retryStrategy` must keep reconnecting with capped backoff (`min(times * 200, 5000)`) and never return null. Bound per-command latency elsewhere (`maxRetriesPerRequest` + a timeout wrapper), not by abandoning reconnection. Verify recovery by stopping and restarting a real Redis, not just mocks.
+
+**Applies to:** `packages/kv/src/client.ts`, `packages/kv/src/resilient.ts`, any ioredis client config.
+
## Permission scope renames are invisible to typecheck
**Context:** Renaming DB RLS policies (e.g., `plm_*` → `production_*`) as part of a module rename.
diff --git a/.ai/rules/dev-shared-redis.md b/.ai/rules/dev-shared-redis.md
index 677ab628c4..ba8fc4c288 100644
--- a/.ai/rules/dev-shared-redis.md
+++ b/.ai/rules/dev-shared-redis.md
@@ -15,10 +15,21 @@ paths:
- Single global singleton in **`packages/kv/src/client.ts`**: `new Redis(REDIS_URL, ...)`
stashed on `global.__redis` (survives HMR / warm lambdas). Options:
`maxRetriesPerRequest: 3`, `lazyConnect: true`, `enableOfflineQueue: true`,
- capped `retryStrategy` (stop after 3). Throws if `REDIS_URL` is unset.
+ and a `retryStrategy` that reconnects forever with capped backoff
+ (`min(times * 200, 5000)`) so the client auto-recovers when Redis returns —
+ per-command latency is bounded by `maxRetriesPerRequest` + the resilience-layer
+ timeout, not by giving up on reconnection. Throws if `REDIS_URL` is unset.
- Exported as `{ redis }` from `packages/kv/src/index.ts`, which also exports the
`Ratelimit` class (a custom ioredis-backed reimplementation of the
`@upstash/ratelimit` API using Lua `eval` scripts — see `packages/kv/src/ratelimit/`).
+- **Resilience wrapper** (`packages/kv/src/resilient.ts`): the singleton is
+ passed through `withResilience()`, a Proxy that makes every command fail soft
+ when Redis is unreachable — reads resolve `null` (collections `[]`), writes
+ resolve `null`, and `pipeline().exec()` resolves `[]`, each with a
+ `REDIS_TIMEOUT_MS` cap. Consumers keep the ordinary ioredis API and need no
+ per-call try/catch; a `null` read is just a cache miss → read through to the DB.
+ `Ratelimit.limit()` fails open (`success: true`) on any Redis error. This is the
+ fix for a Redis outage no longer taking down requests (issue #1076).
## Connection config
diff --git a/packages/kv/AGENTS.md b/packages/kv/AGENTS.md
index 4567ccf987..06ce15bd44 100644
--- a/packages/kv/AGENTS.md
+++ b/packages/kv/AGENTS.md
@@ -5,7 +5,8 @@ Redis client (ioredis) and rate limiting library. Used for permission caching, l
## Always
- Import the singleton Redis client via `import { redis } from "@carbon/kv"` — it's a global singleton with lazy connect and retry logic.
-- Use `Ratelimit` class with static factory methods: `Ratelimit.fixedWindow()`, `Ratelimit.slidingWindow()`, or `Ratelimit.tokenBucket()`.
+- The singleton is **resilience-wrapped** (`src/resilient.ts`): Redis is a cache, never the source of truth, so when it's unreachable commands **fail soft instead of throwing** — a read resolves `null` (a collection resolves `[]`), a write resolves `null`, and a pipeline `.exec()` resolves `[]`. Just `await redis.get(...)` normally; treat `null` as a cache miss and read through to the DB. Do **not** wrap call sites in try/catch for connectivity — that's already handled. Each command also has a `REDIS_TIMEOUT_MS` cap so a hung Redis can't stall a request.
+- Use `Ratelimit` class with static factory methods: `Ratelimit.fixedWindow()`, `Ratelimit.slidingWindow()`, or `Ratelimit.tokenBucket()`. When Redis is down `Ratelimit.limit()` **fails open** (returns `success: true`) — a cache outage never blocks auth.
- Handle rate limit responses: check `response.success` — caller is responsible for returning 429 when `!success`.
- Requires `REDIS_URL` env var — throws at import if not set.
@@ -30,7 +31,7 @@ pnpm --filter @carbon/kv typecheck
| Export | Provides |
|--------|----------|
-| `redis` | Global ioredis singleton (lazy connect, 3 retries, offline queue) |
+| `redis` | Global ioredis singleton (lazy connect, 3 retries, offline queue), resilience-wrapped to fail soft when Redis is unreachable |
| `Ratelimit` | Rate limiter class with `limit()`, `blockUntilReady()`, `getRemaining()`, `resetUsedTokens()` |
| `Ratelimit.fixedWindow(tokens, window)` | Fixed window algorithm (simple, low memory) |
| `Ratelimit.slidingWindow(tokens, window)` | Sliding window (smoother, prevents boundary bursts) |
diff --git a/packages/kv/src/client.ts b/packages/kv/src/client.ts
index d1bd9ebbee..a925e10626 100644
--- a/packages/kv/src/client.ts
+++ b/packages/kv/src/client.ts
@@ -1,5 +1,6 @@
import { REDIS_URL } from "@carbon/env";
import Redis from "ioredis";
+import { logUnavailable, reconnectStrategy, withResilience } from "./resilient";
declare global {
var __redis: Redis | undefined;
@@ -10,17 +11,18 @@ if (!REDIS_URL) {
}
if (!global.__redis) {
- global.__redis = new Redis(REDIS_URL, {
+ const client = new Redis(REDIS_URL, {
maxRetriesPerRequest: 3,
lazyConnect: true, // don't connect until first command
enableOfflineQueue: true, // buffer commands while connecting
- retryStrategy(times) {
- if (times > 3) return null; // stop retrying, don't hang the lambda
- return Math.min(times * 50, 2000);
- }
+ retryStrategy: reconnectStrategy
});
+ // Registered once with the singleton; without a listener ioredis re-emits
+ // connection errors as process-level unhandled errors.
+ client.on("error", logUnavailable);
+ global.__redis = client;
}
-const redis = global.__redis;
+const redis = withResilience(global.__redis);
export default redis;
diff --git a/packages/kv/src/ratelimit/ratelimit.ts b/packages/kv/src/ratelimit/ratelimit.ts
index 4ad57ae8ee..1d80538dc4 100644
--- a/packages/kv/src/ratelimit/ratelimit.ts
+++ b/packages/kv/src/ratelimit/ratelimit.ts
@@ -77,26 +77,34 @@ export class Ratelimit {
}
}
- // Apply timeout
- const response = this.limiter().limit(this.ctx, key, opts?.rate);
-
- if (this.timeout > 0) {
- const timeoutPromise = new Promise<RatelimitResponse>((resolve) => {
- setTimeout(() => {
- resolve({
- success: true,
- limit: 0,
- remaining: 0,
- reset: 0,
- pending: Promise.resolve()
- });
- }, this.timeout);
- });
-
- return Promise.race([response, timeoutPromise]);
+ // Fail open on any Redis error — a cache outage must not block auth.
+ try {
+ const response = this.limiter().limit(this.ctx, key, opts?.rate);
+
+ if (this.timeout > 0) {
+ const timeoutPromise = new Promise<RatelimitResponse>((resolve) => {
+ setTimeout(() => {
+ resolve(this.failOpen());
+ }, this.timeout);
+ });
+
+ return await Promise.race([response, timeoutPromise]);
+ }
+
+ return await response;
+ } catch {
+ return this.failOpen();
}
+ }
- return response;
+ private failOpen(): RatelimitResponse {
+ return {
+ success: true,
+ limit: 0,
+ remaining: 0,
+ reset: 0,
+ pending: Promise.resolve()
+ };
}
/**
@@ -143,7 +151,12 @@ export class Ratelimit {
identifier: string
): Promise<{ remaining: number; reset: number; limit: number }> {
const key = this.getKey(identifier);
- return this.limiter().getRemaining(this.ctx, key);
+ try {
+ return await this.limiter().getRemaining(this.ctx, key);
+ } catch {
+ // Redis down: report no known usage rather than throwing.
+ return { remaining: 0, reset: 0, limit: 0 };
+ }
}
/**
@@ -152,7 +165,11 @@ export class Ratelimit {
*/
async resetUsedTokens(identifier: string): Promise<void> {
const key = this.getKey(identifier);
- return this.limiter().resetTokens(this.ctx, key);
+ try {
+ return await this.limiter().resetTokens(this.ctx, key);
+ } catch {
+ // Redis down: nothing to reset, don't throw.
+ }
}
private getKey(identifier: string): string {
diff --git a/packages/kv/src/resilient.test.ts b/packages/kv/src/resilient.test.ts
new file mode 100644
index 0000000000..167e67cc3f
--- /dev/null
+++ b/packages/kv/src/resilient.test.ts
@@ -0,0 +1,160 @@
+import type Redis from "ioredis";
+import RedisMock from "ioredis-mock";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { Ratelimit } from "./ratelimit";
+import {
+ REDIS_TIMEOUT_MS,
+ reconnectStrategy,
+ withResilience
+} from "./resilient";
+
+/** A client whose every command rejects immediately (Redis unreachable). */
+function failingClient(): Redis {
+ const reject = () => Promise.reject(new Error("ECONNREFUSED"));
+ return {
+ on: () => undefined,
+ get: reject,
+ set: reject,
+ del: reject,
+ getdel: reject,
+ setex: reject,
+ keys: reject,
+ eval: reject,
+ pipeline: () => {
+ const p: Record<string, unknown> = {};
+ p.del = () => p;
+ p.set = () => p;
+ p.exec = reject;
+ return p;
+ }
+ } as unknown as Redis;
+}
+
+describe("withResilience", () => {
+ beforeEach(() => {
+ vi.spyOn(console, "warn").mockImplementation(() => undefined);
+ vi.spyOn(console, "info").mockImplementation(() => undefined);
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+ });
+
+ describe("healthy Redis (pass-through)", () => {
+ it("returns real values, unchanged", async () => {
+ const redis = withResilience(new RedisMock() as unknown as Redis);
+
+ expect(await redis.set("k", "v")).toBe("OK");
+ expect(await redis.get("k")).toBe("v");
+ expect(await redis.del("k")).toBe(1);
+ expect(await redis.get("k")).toBeNull();
+ });
+
+ it("passes through collection commands", async () => {
+ const redis = withResilience(new RedisMock() as unknown as Redis);
+ await redis.set("a", "1");
+ await redis.set("b", "2");
+
+ expect((await redis.keys("*")).sort()).toEqual(["a", "b"]);
+ });
+
+ it("passes through pipelines", async () => {
+ const redis = withResilience(new RedisMock() as unknown as Redis);
+ const result = await redis.pipeline().set("a", "1").set("b", "2").exec();
+
+ expect(result).toHaveLength(2);
+ });
+ });
+
+ describe("unreachable Redis (fail-soft)", () => {
+ it("resolves null for a read instead of throwing", async () => {
+ const redis = withResilience(failingClient());
+ await expect(redis.get("k")).resolves.toBeNull();
+ });
+
+ it("resolves null for a write instead of throwing", async () => {
+ const redis = withResilience(failingClient());
+ await expect(redis.set("k", "v")).resolves.toBeNull();
+ await expect(redis.del("k")).resolves.toBeNull();
+ await expect(redis.setex("k", 60, "v")).resolves.toBeNull();
+ });
+
+ it("resolves [] for collection commands so iteration is safe", async () => {
+ const redis = withResilience(failingClient());
+ const keys = await redis.keys("prefix:*");
+
+ expect(keys).toEqual([]);
+ expect(Array.isArray(keys)).toBe(true);
+ });
+
+ it("resolves [] for a pipeline exec", async () => {
+ const redis = withResilience(failingClient());
+ await expect(redis.pipeline().del("a").del("b").exec()).resolves.toEqual(
+ []
+ );
+ });
+ });
+
+ describe("hanging Redis (timeout)", () => {
+ it("falls back after REDIS_TIMEOUT_MS instead of hanging forever", async () => {
+ vi.useFakeTimers();
+ const hanging = {
+ on: () => undefined,
+ get: () => new Promise(() => undefined) // never settles
+ } as unknown as Redis;
+ const redis = withResilience(hanging);
+
+ const pending = redis.get("k");
+ await vi.advanceTimersByTimeAsync(REDIS_TIMEOUT_MS);
+
+ await expect(pending).resolves.toBeNull();
+ });
+ });
+});
+
+describe("reconnectStrategy", () => {
+ // Returning null would tell ioredis to stop reconnecting permanently — the
+ // exact bug that defeats auto-recovery. This guards against a revert.
+ it("never returns null, so the client keeps reconnecting", () => {
+ for (const times of [1, 2, 3, 10, 100, 1000]) {
+ expect(reconnectStrategy(times)).not.toBeNull();
+ expect(typeof reconnectStrategy(times)).toBe("number");
+ }
+ });
+
+ it("backs off with an increasing, capped delay", () => {
+ expect(reconnectStrategy(1)).toBeLessThan(reconnectStrategy(5));
+ expect(reconnectStrategy(1000)).toBe(5000);
+ });
+});
+
+describe("Ratelimit fail-open when Redis is down", () => {
+ beforeEach(() => {
+ vi.spyOn(console, "warn").mockImplementation(() => undefined);
+ });
+ afterEach(() => vi.restoreAllMocks());
+
+ it("allows the request (success: true) instead of throwing", async () => {
+ const limiter = new Ratelimit({
+ redis: failingClient(),
+ limiter: Ratelimit.fixedWindow(5, "1 m"),
+ timeout: 0
+ });
+
+ const result = await limiter.limit("user:1");
+ expect(result.success).toBe(true);
+ });
+
+ it("still enforces limits when Redis is healthy", async () => {
+ const limiter = new Ratelimit({
+ redis: new RedisMock() as unknown as Redis,
+ limiter: Ratelimit.fixedWindow(2, "1 m"),
+ timeout: 0
+ });
+
+ expect((await limiter.limit("user:2")).success).toBe(true);
+ expect((await limiter.limit("user:2")).success).toBe(true);
+ expect((await limiter.limit("user:2")).success).toBe(false);
+ });
+});
diff --git a/packages/kv/src/resilient.ts b/packages/kv/src/resilient.ts
new file mode 100644
index 0000000000..24972294e8
--- /dev/null
+++ b/packages/kv/src/resilient.ts
@@ -0,0 +1,132 @@
+import type Redis from "ioredis";
+
+export const REDIS_TIMEOUT_MS = 2000;
+const LOG_THROTTLE_MS = 10_000;
+
+let lastLoggedAt = 0;
+let unavailable = false;
+
+export function logUnavailable(err: unknown): void {
+ const now = Date.now();
+ if (!unavailable || now - lastLoggedAt >= LOG_THROTTLE_MS) {
+ const message = err instanceof Error ? err.message : String(err);
+ console.warn(`Redis unavailable, falling back: ${message}`);
+ lastLoggedAt = now;
+ }
+ unavailable = true;
+}
+
+function logReconnected(): void {
+ if (unavailable) {
+ console.info("Redis reconnected");
+ unavailable = false;
+ }
+}
+
+// Reconnect forever with capped backoff so the client auto-recovers when Redis
+// returns. Never returns null — that would end reconnection permanently; a null
+// here is the exact bug that defeats auto-recovery. Per-command latency is
+// bounded by maxRetriesPerRequest + the guard timeout, not by giving up here.
+export const reconnectStrategy = (times: number): number =>
+ Math.min(times * 200, 5000);
+
+function guard<T>(promise: Promise<T>, fallback: T): Promise<T> {
+ return new Promise<T>((resolve) => {
+ let settled = false;
+ const finish = (value: T) => {
+ if (!settled) {
+ settled = true;
+ resolve(value);
+ }
+ };
+ const timer = setTimeout(() => {
+ logUnavailable(new Error("redis timeout"));
+ finish(fallback);
+ }, REDIS_TIMEOUT_MS);
+
+ // A late settle after the timeout is intentionally swallowed here so it
+ // can't surface as an unhandled rejection.
+ promise.then(
+ (value) => {
+ clearTimeout(timer);
+ logReconnected();
+ finish(value);
+ },
+ (err) => {
+ clearTimeout(timer);
+ logUnavailable(err);
+ finish(fallback);
+ }
+ );
+ });
+}
+
+// Collection commands fall back to [] (not null) so callers can iterate safely.
+const ARRAY_FALLBACK = new Set([
+ "keys",
+ "mget",
+ "hkeys",
+ "hvals",
+ "smembers",
+ "lrange",
+ "zrange",
+ "zrevrange",
+ "sscan",
+ "hscan",
+ "zscan"
+]);
+
+const fallbackFor = (command: string): unknown =>
+ ARRAY_FALLBACK.has(command.toLowerCase()) ? [] : null;
+
+function wrapPipeline<
+ T extends { exec?: (...args: unknown[]) => Promise<unknown> }
+>(pipeline: T): T {
+ // Pipelines are chainable objects, so the proxy can't reach their commands;
+ // guard the terminal exec() instead.
+ if (pipeline && typeof pipeline.exec === "function") {
+ const originalExec = pipeline.exec.bind(pipeline);
+ pipeline.exec = (...args: unknown[]) =>
+ guard(originalExec(...args), [] as unknown[]);
+ }
+ return pipeline;
+}
+
+// Redis is a cache, never the source of truth. This Proxy makes an unreachable
+// Redis degrade instead of crash: reads resolve null, collections [], writes
+// null — so consumers keep the ordinary ioredis API with no per-call handling.
+export function withResilience(client: Redis): Redis {
+ return new Proxy(client, {
+ get(target, prop) {
+ const value = Reflect.get(target, prop);
+ if (typeof value !== "function") return value;
+
+ const command = typeof prop === "string" ? prop : "";
+
+ if (command === "pipeline" || command === "multi") {
+ return (...args: unknown[]) =>
+ wrapPipeline(
+ (
+ value as (...a: unknown[]) => {
+ exec?: (...a: unknown[]) => Promise<unknown>;
+ }
+ ).apply(target, args)
+ );
+ }
+
+ return (...args: unknown[]) => {
+ let result: unknown;
+ try {
+ result = (value as (...a: unknown[]) => unknown).apply(target, args);
+ } catch (err) {
+ logUnavailable(err);
+ return Promise.resolve(fallbackFor(command));
+ }
+ if (result && typeof (result as Promise<unknown>).then === "function") {
+ return guard(result as Promise<unknown>, fallbackFor(command));
+ }
+ return result;
+ };
+ }
+ }) as Redis;
+}