Skip to content

Commit d5a1355

Browse files
authored
Merge pull request #360 from internxt/fix/add-cache-retry-strategy
[_]: fix/add cache retry strategy
2 parents 4c4501e + 818861c commit d5a1355

2 files changed

Lines changed: 33 additions & 1 deletion

File tree

src/services/cache.service.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,24 @@ export default class CacheService {
1111
private readonly redis: Redis;
1212
constructor(config: AppConfig) {
1313
this.redis = new Redis(config.REDIS_HOST, {
14-
retryStrategy: () => undefined,
14+
retryStrategy: (times) => {
15+
if (times > 10) {
16+
Logger.error('[CACHE SERVICE]: Max reconnection attempts reached. Giving up.');
17+
return undefined;
18+
}
19+
return Math.min(times * 500, 30000);
20+
},
21+
enableOfflineQueue: false,
22+
keepAlive: 10000,
23+
maxRetriesPerRequest: 5,
1524
showFriendlyErrorStack: true,
1625
});
1726

1827
this.redis.on('error', (error) => {
1928
Logger.error(`[CACHE SERVICE]: Redis error: ${error.message}`);
2029
});
30+
this.redis.on('close', () => Logger.warn('[CACHE SERVICE]: Connection closed'));
31+
this.redis.on('end', () => Logger.error('[CACHE SERVICE]: Connection ended, no more retries'));
2132
}
2233

2334
private buildSubscriptionKey(customerId: string, userType: UserType = UserType.Individual): string {

tests/src/services/cache.service.test.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,27 @@ describe('Cache Service', () => {
3333
});
3434
});
3535

36+
describe('Retry Strategy', () => {
37+
test('When reconnection attempts are less than 10, then it returns increasing delays', () => {
38+
const newCacheService = new CacheService(config);
39+
const retryStrategy = (newCacheService as any).redis.options.retryStrategy;
40+
41+
expect(retryStrategy(1)).toBe(500);
42+
expect(retryStrategy(2)).toBe(1000);
43+
expect(retryStrategy(5)).toBe(2500);
44+
expect(retryStrategy(10)).toBe(5000);
45+
});
46+
47+
test('When reconnection attempts exceed 10, then it gives up', () => {
48+
const newCacheService = new CacheService(config);
49+
const retryStrategy = (newCacheService as any).redis.options.retryStrategy;
50+
51+
const result = retryStrategy(11);
52+
53+
expect(result).toBeUndefined();
54+
});
55+
});
56+
3657
describe('Safe await error handling', () => {
3758
test('When a Redis operation fails, then the error is logged and null is returned', async () => {
3859
const loggerSpy = jest.spyOn(Logger, 'error');

0 commit comments

Comments
 (0)