Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 21 additions & 7 deletions apps/sim/lib/core/config/redis.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { createLogger } from '@sim/logger'
import { toError } from '@sim/utils/errors'
import { randomFloat } from '@sim/utils/random'
import Redis from 'ioredis'
import Redis, { type RedisOptions } from 'ioredis'
import { env } from '@/lib/core/config/env'

const logger = createLogger('Redis')
Expand All @@ -16,7 +16,7 @@ const redisUrl = env.REDIS_URL
*
* For DNS hosts: no override needed, default verification works.
*/
function resolveTlsOptions(url: string | undefined): { servername: string } | undefined {
function resolveRedisTlsOptions(url: string | undefined): { servername: string } | undefined {
if (!url) return undefined
let parsed: URL
try {
Expand All @@ -37,6 +37,23 @@ function resolveTlsOptions(url: string | undefined): { servername: string } | un
return { servername: env.REDIS_TLS_SERVERNAME }
}

/**
* Shared connection defaults — keepAlive, connectTimeout, enableOfflineQueue,
* and TLS SNI when REDIS_URL targets an IP. Every Redis client we open should
* spread this; callers add their own retry / timeout policy on top.
*/
export function getRedisConnectionDefaults(
url: string | undefined
): Pick<RedisOptions, 'keepAlive' | 'connectTimeout' | 'enableOfflineQueue' | 'tls'> {
const tls = resolveRedisTlsOptions(url)
return {
keepAlive: 1000,
connectTimeout: 10000,
enableOfflineQueue: true,
...(tls ? { tls } : {}),
}
}

let globalRedisClient: Redis | null = null
let pingFailures = 0
let pingInterval: NodeJS.Timeout | null = null
Expand Down Expand Up @@ -117,18 +134,15 @@ export function getRedisClient(): Redis | null {
if (globalRedisClient) return globalRedisClient

// Outside the try/catch so config errors aren't silently swallowed.
const tls = resolveTlsOptions(redisUrl)
const defaults = getRedisConnectionDefaults(redisUrl)

try {
logger.info('Initializing Redis client')

globalRedisClient = new Redis(redisUrl, {
keepAlive: 1000,
connectTimeout: 10000,
...defaults,
commandTimeout: 5000,
maxRetriesPerRequest: 5,
enableOfflineQueue: true,
...(tls ? { tls } : {}),

retryStrategy: (times) => {
if (times > 10) {
Expand Down
30 changes: 16 additions & 14 deletions apps/sim/lib/events/pubsub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { EventEmitter } from 'events'
import { createLogger } from '@sim/logger'
import Redis, { type RedisOptions } from 'ioredis'
import { env } from '@/lib/core/config/env'
import { getRedisConnectionDefaults } from '@/lib/core/config/redis'

const logger = createLogger('PubSub')

Expand All @@ -31,13 +32,12 @@ class RedisPubSubChannel<T> implements PubSubChannel<T> {

constructor(
redisUrl: string,
connectionDefaults: ReturnType<typeof getRedisConnectionDefaults>,
private config: PubSubChannelConfig
) {
const commonOpts = {
keepAlive: 1000,
connectTimeout: 10000,
...connectionDefaults,
maxRetriesPerRequest: null,
enableOfflineQueue: true,
retryStrategy: (times: number) => {
if (times > 10) return 30000
return Math.min(times * 500, 5000)
Expand Down Expand Up @@ -139,16 +139,18 @@ class LocalPubSubChannel<T> implements PubSubChannel<T> {

export function createPubSubChannel<T>(config: PubSubChannelConfig): PubSubChannel<T> {
const redisUrl = env.REDIS_URL

if (redisUrl) {
try {
logger.info(`${config.label}: Using Redis`)
return new RedisPubSubChannel<T>(redisUrl, config)
} catch (err) {
logger.error(`Failed to create Redis ${config.label}, falling back to local:`, err)
return new LocalPubSubChannel<T>(config)
}
if (!redisUrl) return new LocalPubSubChannel<T>(config)

// Resolve config-derived defaults outside the try so a missing
// REDIS_TLS_SERVERNAME (config error) surfaces instead of silently degrading
// to the in-process EventEmitter — that would break cross-replica pub/sub.
const connectionDefaults = getRedisConnectionDefaults(redisUrl)

try {
logger.info(`${config.label}: Using Redis`)
return new RedisPubSubChannel<T>(redisUrl, connectionDefaults, config)
} catch (err) {
logger.error(`Failed to create Redis ${config.label}, falling back to local:`, err)
return new LocalPubSubChannel<T>(config)
}

return new LocalPubSubChannel<T>(config)
}
Loading