File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff 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 {
Original file line number Diff line number Diff 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' ) ;
You can’t perform that action at this time.
0 commit comments