Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

fix(api): slow redis replies no longer fail requests after 500 ms

Carl-Gerhard Lindesvärd893073d74b7f
diff --git a/apps/api/e2e/README.md b/apps/api/e2e/README.md
index 5487526fe..0d5b6b4f4 100644
--- a/apps/api/e2e/README.md
+++ b/apps/api/e2e/README.md
@@ -357,7 +357,7 @@ spawns its own API on `:3399` pointed at a TCP proxy it can stop (`docker stop`)
or freeze (`docker pause`), and measures what `/track` costs while the Redis
**cache** is unreachable — sustained outage, 1 s blip under load, frozen server,
and a boot with Redis already down. `redis-command-cost.ts` measures the cost of
-a *legitimate* command, which is what bounds `CACHE_COMMAND_TIMEOUT_MS`.
+a *legitimate* command, which is what bounds `DEFAULT_CACHE_COMMAND_TIMEOUT_MS`.
```bash
cd apps/api
diff --git a/apps/api/src/config/env.test.ts b/apps/api/src/config/env.test.ts
index adeb8a750..0a030cf30 100644
--- a/apps/api/src/config/env.test.ts
+++ b/apps/api/src/config/env.test.ts
@@ -411,6 +411,17 @@ describe('cross-field invariants, checked before the transform', () => {
).toBe(30_000);
});
+ it('reads REDIS_CACHE_COMMAND_TIMEOUT_MS, defaulting to 5000', () => {
+ expect(loadConfig(base).REDIS_CACHE_COMMAND_TIMEOUT_MS).toBe(5000);
+ expect(
+ loadConfig({ ...base, REDIS_CACHE_COMMAND_TIMEOUT_MS: '2000' })
+ .REDIS_CACHE_COMMAND_TIMEOUT_MS
+ ).toBe(2000);
+ expect(() =>
+ loadConfig({ ...base, REDIS_CACHE_COMMAND_TIMEOUT_MS: 'soon' })
+ ).toThrow();
+ });
+
it('refuses a reaper deadman below the session idle window', () => {
expect(() =>
loadConfig({
diff --git a/apps/api/src/config/env.ts b/apps/api/src/config/env.ts
index b54009fec..5f4c54293 100644
--- a/apps/api/src/config/env.ts
+++ b/apps/api/src/config/env.ts
@@ -20,6 +20,8 @@ const DEVELOPMENT = 'development';
/** pino's own service-name suffix when NODE_ENV is unset. */
const DEFAULT_SERVICE_ENVIRONMENT = 'dev';
const DEFAULT_SHUTDOWN_FORCE_EXIT_MS = 20_000;
+/** Matches `packages/redis`'s own default, so leaving the variable unset changes nothing. */
+const DEFAULT_REDIS_CACHE_COMMAND_TIMEOUT_MS = 5000;
const DEFAULT_KAFKA_CLIENT_ID = 'openpanel';
const DEFAULT_KAFKA_EVENTS_TOPIC = 'events';
@@ -344,6 +346,9 @@ const rawSchema = z.object({
blankToUndefined,
z.coerce.number().int().positive().default(DEFAULT_SHUTDOWN_FORCE_EXIT_MS)
),
+ REDIS_CACHE_COMMAND_TIMEOUT_MS: positiveIntWithDefault(
+ DEFAULT_REDIS_CACHE_COMMAND_TIMEOUT_MS
+ ),
/**
* Redis Cluster hash-tags every queue key (`cron` -> `{cron}`). It decides a
@@ -923,6 +928,8 @@ export interface Config {
DISABLE_BULLBOARD: boolean;
COOKIE_SECRET: string;
SHUTDOWN_FORCE_EXIT_MS: number;
+ /** Sits here, not in `core`: the cache client is `packages/redis`'s singleton, configured once at boot. */
+ REDIS_CACHE_COMMAND_TIMEOUT_MS: number;
/** Sits here, not in `core.kafka`: `apps/api` picks the dead-letter sink and core only gets the `sendToDeadLetter` seam. */
INGEST_DEAD_LETTER_MAX_ENTRIES: number;
/** Sits here, not in `core.kafka`: the marker is keyed on the event, not a Kafka coordinate. */
@@ -969,6 +976,7 @@ const envSchema = rawSchema
DISABLE_BULLBOARD: raw.DISABLE_BULLBOARD,
COOKIE_SECRET: raw.COOKIE_SECRET,
SHUTDOWN_FORCE_EXIT_MS: raw.SHUTDOWN_FORCE_EXIT_MS,
+ REDIS_CACHE_COMMAND_TIMEOUT_MS: raw.REDIS_CACHE_COMMAND_TIMEOUT_MS,
INGEST_DEAD_LETTER_MAX_ENTRIES: raw.INGEST_DEAD_LETTER_MAX_ENTRIES,
INGEST_DUPLICATE_MARKER_TTL_MS: raw.INGEST_DUPLICATE_MARKER_TTL_MS,
dashboardOrigins: [
diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts
index 20cf9cf0d..8402e106d 100644
--- a/apps/api/src/main.ts
+++ b/apps/api/src/main.ts
@@ -61,6 +61,7 @@ import {
import { ch } from '@openpanel/db/src/clickhouse/client';
import { db, Prisma } from '@openpanel/db/src/prisma-client';
import {
+ configureRedisCache,
createDeadLetterRecorder,
createDuplicateEventMarker,
getRedisCache,
@@ -106,6 +107,9 @@ function loadConfigOrExit(): Config {
}
const config = loadConfigOrExit();
+configureRedisCache({
+ commandTimeoutMs: config.REDIS_CACHE_COMMAND_TIMEOUT_MS,
+});
// Workers keep the `worker` service name they shipped logs under before roles
// shared one image, so existing log searches and alerts still match.
const logger = createLogger({
diff --git a/apps/public/content/docs/self-hosting/environment-variables.mdx b/apps/public/content/docs/self-hosting/environment-variables.mdx
index 629e1d9c5..65c0f212c 100644
--- a/apps/public/content/docs/self-hosting/environment-variables.mdx
+++ b/apps/public/content/docs/self-hosting/environment-variables.mdx
@@ -74,6 +74,19 @@ REDIS_URL=redis://localhost:6379
REDIS_URL=redis://:password@localhost:6379
```
+### REDIS_CACHE_COMMAND_TIMEOUT_MS
+
+**Type**: `number`
+**Required**: No
+**Default**: `5000`
+
+How long, in milliseconds, a Redis command used for caching, buffers and ingest may take before it fails. Commands still fail immediately while Redis is unreachable; this only bounds a connection that is up but slow. Too low a value turns brief network stalls into failed requests and duplicate events.
+
+**Example**:
+```bash
+REDIS_CACHE_COMMAND_TIMEOUT_MS=5000
+```
+
### CLICKHOUSE_URL
**Type**: `string`
diff --git a/packages/redis/redis.test.ts b/packages/redis/redis.test.ts
index 5fb5d46f4..7f9cdbc7a 100644
--- a/packages/redis/redis.test.ts
+++ b/packages/redis/redis.test.ts
@@ -3,14 +3,16 @@
import net from 'node:net';
import { afterEach, describe, expect, it } from 'vitest';
import {
- CACHE_COMMAND_TIMEOUT_MS,
createFailFastCacheClient,
+ DEFAULT_CACHE_COMMAND_TIMEOUT_MS,
type ExtendedRedis,
QUEUE_CLIENT_OPTIONS,
} from './redis';
+/** Short enough for the default test timeout; the default is too long to wait out here. */
+const TEST_COMMAND_TIMEOUT_MS = 500;
/** ioredis's own cycle is tens of seconds; anything near it is the bug back. */
-const PROMPT_WHEN_NEVER_CONNECTED_MS = CACHE_COMMAND_TIMEOUT_MS * 4;
+const PROMPT_WHEN_NEVER_CONNECTED_MS = TEST_COMMAND_TIMEOUT_MS * 4;
/** A known-down socket must not wait for the timeout at all. */
const INSTANT_WHEN_DISCONNECTED_MS = 100;
const READY_TIMEOUT_MS = 5000;
@@ -169,7 +171,8 @@ describe('cache client fail-fast (M18-003)', () => {
const client = track(
createFailFastCacheClient(
'test-never-reachable',
- `redis://127.0.0.1:${port}`
+ `redis://127.0.0.1:${port}`,
+ { commandTimeoutMs: TEST_COMMAND_TIMEOUT_MS }
)
);
@@ -228,6 +231,24 @@ describe('cache client fail-fast (M18-003)', () => {
expect(ms).toBeLessThan(INSTANT_WHEN_DISCONNECTED_MS);
});
+ it('bounds commands at the default timeout unless told otherwise', () => {
+ const defaulted = track(
+ createFailFastCacheClient('test-default-timeout', 'redis://127.0.0.1:1', {
+ commandTimeoutMs: undefined,
+ })
+ );
+ const overridden = track(
+ createFailFastCacheClient('test-custom-timeout', 'redis://127.0.0.1:1', {
+ commandTimeoutMs: 2000,
+ })
+ );
+
+ expect(defaulted.options.commandTimeout).toBe(
+ DEFAULT_CACHE_COMMAND_TIMEOUT_MS
+ );
+ expect(overridden.options.commandTimeout).toBe(2000);
+ });
+
it('leaves the queue client on BullMQ’s mandated settings', () => {
expect(QUEUE_CLIENT_OPTIONS.maxRetriesPerRequest).toBeNull();
expect(QUEUE_CLIENT_OPTIONS.enableOfflineQueue).toBe(true);
diff --git a/packages/redis/redis.ts b/packages/redis/redis.ts
index 32da6e99e..579beb40b 100644
--- a/packages/redis/redis.ts
+++ b/packages/redis/redis.ts
@@ -8,11 +8,11 @@ const options: RedisOptions = {
/**
* The cache client's tail bound, for the fault the offline queue cannot see: a server whose socket is UP and which
- * answers nothing. It has to clear the heaviest legitimate command by a wide margin, or a busy event-buffer flush
- * would fail as if Redis were down and refuse to commit Kafka offsets. 500 ms is roughly 15x the measured p99 of
- * that flush's worst case (`apps/api/e2e/redis-command-cost.ts`). Full numbers: `apps/api/e2e/redis-fail-fast.md`.
+ * answers nothing. It has to clear the heaviest legitimate command by a wide margin. 500 ms did not: in production,
+ * short network stalls and large buffer reads failed as if Redis were down, which stalled the replay buffer and left
+ * Kafka batches unresolved (redelivered as duplicates). `REDIS_CACHE_COMMAND_TIMEOUT_MS` overrides it.
*/
-export const CACHE_COMMAND_TIMEOUT_MS = 500;
+export const DEFAULT_CACHE_COMMAND_TIMEOUT_MS = 5000;
/**
* Fail-fast makes the RECONNECT BACKOFF user-visible. While ioredis is waiting
@@ -112,11 +112,12 @@ const createRedisClient = (
*/
export function createFailFastCacheClient(
name: string,
- url: string
+ url: string,
+ { commandTimeoutMs = DEFAULT_CACHE_COMMAND_TIMEOUT_MS } = {}
): ExtendedRedis {
const client = createRedisClient(name, url, {
...options,
- commandTimeout: CACHE_COMMAND_TIMEOUT_MS,
+ commandTimeout: commandTimeoutMs,
retryStrategy: (attempt) =>
Math.min(
attempt * CACHE_RECONNECT_DELAY_STEP_MS,
@@ -130,9 +131,23 @@ export function createFailFastCacheClient(
}
let redisCache: ExtendedRedis;
+let cacheCommandTimeoutMs = DEFAULT_CACHE_COMMAND_TIMEOUT_MS;
+
+/** Must run before the first `getRedisCache()`: the singleton is built once with whatever is set then. */
+export function configureRedisCache(settings: { commandTimeoutMs: number }) {
+ if (redisCache) {
+ throw new Error(
+ 'configureRedisCache() called after the cache client was created'
+ );
+ }
+ cacheCommandTimeoutMs = settings.commandTimeoutMs;
+}
+
export function getRedisCache() {
if (!redisCache) {
- redisCache = createFailFastCacheClient('redis-cache', REDIS_URL);
+ redisCache = createFailFastCacheClient('redis-cache', REDIS_URL, {
+ commandTimeoutMs: cacheCommandTimeoutMs,
+ });
}
return redisCache;