Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
refactor(redis): improve Redis connection error logging and handling
Victor Hugo dos Santose598e440afb8
diff --git a/backend/src/ee/services/event-bus/redis-bus.ts b/backend/src/ee/services/event-bus/redis-bus.tsindex b3ddd26ee5..519557b1c9 100644--- a/backend/src/ee/services/event-bus/redis-bus.ts+++ b/backend/src/ee/services/event-bus/redis-bus.ts@@ -1,5 +1,6 @@import { Cluster, Redis } from "ioredis";+import { attachConnectionLogging } from "@app/lib/config/redis";import { logger } from "@app/lib/logger";import { EventBusSchema, EventBusTopicName, TEventBusEvent } from "./event-bus-types";@@ -9,8 +10,9 @@ export type TRedisBusOnMessage = (event: TEventBusEvent) => void;export const createRedisBus = (redis: Redis | Cluster, topic: EventBusTopicName) => {// Duplicate the redis connection for pub/sub// Redis doesn't allow a single connection to both publish and subscribe- const publisher = redis.duplicate();- const subscriber = publisher.duplicate();+ // Logging is attached here rather than in init() because duplicate() connects eagerly, long before init() runs+ const publisher = attachConnectionLogging(redis.duplicate(), "event-bus-publisher");+ const subscriber = attachConnectionLogging(publisher.duplicate(), "event-bus-subscriber");let messageHandler: TRedisBusOnMessage | null = null;@@ -18,14 +20,6 @@ export const createRedisBus = (redis: Redis | Cluster, topic: EventBusTopicName)* Initialize the Redis bus by subscribing to the topic*/const init = async (): Promise<void> => {- subscriber.on("error", (error) => {- logger.error(error, "Event bus Redis subscriber error");- });-- publisher.on("error", (error) => {- logger.error(error, "Event bus Redis publisher error");- });-subscriber.on("message", (channel: string, message: string) => {if (channel !== topic || !messageHandler) {logger.info("Received emtpy channel or message in event bus");diff --git a/backend/src/lib/config/redis.ts b/backend/src/lib/config/redis.tsindex ec0d588461..9aba1aba79 100644--- a/backend/src/lib/config/redis.ts+++ b/backend/src/lib/config/redis.ts@@ -21,24 +21,56 @@ export type TRedisConfigKeys = Partial<{const REDIS_ERROR_LOG_THROTTLE_MS = 10_000;-const attachConnectionLogging = (client: Redis | Cluster, name: string) => {- let lastLoggedAt = 0;+// The error channel carries more than socket failures: auth failures (NOAUTH/WRONGPASS) reach it via+// recoverFromFatalError, as do cluster slot-refresh failures. So the throttle is keyed per normalized error code.+// Keying on err.message instead would grow unbounded, since cluster messages embed host:port.+const getRedisErrorKey = (err: Error) => {+ const { code } = err as Error & { code?: string };+ if (code) return code; // ECONNREFUSED, ETIMEDOUT, ...++ const replyPrefix = /^([A-Z]{4,})/.exec(err.message)?.[1];+ if (replyPrefix) return replyPrefix; // NOAUTH, WRONGPASS, CLUSTERDOWN, ...++ return err.name;+};++/**+ * Attaches throttled, named connection logging to a client. Call this on any client not built by+ * `buildRedisFromConfig`. Specifically `duplicate()`d clients, since `duplicate()` copies options but not listeners.+ */+export const attachConnectionLogging = (client: Redis | Cluster, name: string) => {+ const throttleByErrorKey = new Map<string, { lastLoggedAt: number; suppressedCount: number }>();let isDown = false;client.on("error", (err: Error) => {+ const errorKey = getRedisErrorKey(err);const now = Date.now();- if (now - lastLoggedAt < REDIS_ERROR_LOG_THROTTLE_MS) return;+ const throttle = throttleByErrorKey.get(errorKey);++ if (throttle && now - throttle.lastLoggedAt < REDIS_ERROR_LOG_THROTTLE_MS) {+ throttle.suppressedCount += 1;+ return;+ }- lastLoggedAt = now;+ const suppressedCount = throttle?.suppressedCount ?? 0;+ throttleByErrorKey.set(errorKey, { lastLoggedAt: now, suppressedCount: 0 });+ logger.error(+ { err, redisClient: name, redisErrorKey: errorKey, suppressedCount },+ `Redis connection error [client=${name}] [error=${errorKey}] [suppressedCount=${suppressedCount}] [message=${err.message}]`+ );+ });++ client.on("close", () => {isDown = true;- logger.error({ err, redisClient: name }, `Redis connection error [client=${name}] [error=${err.message}]`);});client.on("ready", () => {+ // Must clear, otherwise stale timestamps would throttle the first error of the next outage.+ throttleByErrorKey.clear();+// Skip the initial connect; only a recovery is worth a line.if (!isDown) return;isDown = false;- lastLoggedAt = 0;logger.info({ redisClient: name }, `Redis connection restored [client=${name}]`);});diff --git a/docs/self-hosting/configuration/requirements.mdx b/docs/self-hosting/configuration/requirements.mdxindex eb77434a82..edeaa4a6b5 100644--- a/docs/self-hosting/configuration/requirements.mdx+++ b/docs/self-hosting/configuration/requirements.mdx@@ -65,7 +65,7 @@ connection is configured, and a running instance is degraded for as long as RediRedis requirements:- Use Redis versions 6.x or 7.x. We advise upgrading to at least Redis 6.2.-- Redis Standalone (with or without High Availability), Redis Sentinel, and Redis Cluster are all+- Redis Standalone (with or without High Availability) and Redis Sentinel aresupported. See [Redis configuration](/self-hosting/configuration/envars#redis) for theenvironment variables each mode expects.- Redis storage needs are minimal: a setup with 2 vCPU, 4 GB RAM, and 30GB SSD will be sufficient for small deployments.