Retry Strategies
Message retry strategies allow you to specify how much of a delay should occur before retrying a message.
Delays between retries can be useful when messages fail handling due to race conditions, service unavailability, or concurrency reasons.
By default, @node-ts/bus uses a DefaultRetryStrategy that exponentially increases the delay between each retry attempt. Additionally, it will introduce a random variance of 10% for each delay to help unblock messages that are failing when processed at the same time.
Additional strategies can be implemented to suit your application.

Choosing a Retry Strategy

A retry strategy can be provided to the bus configuration on initialization by using .withRetryStrategy()
For example:
1
const bus = await Bus.configure()
2
.withRetryStrategy(DefaultRetryStrategy)
3
.initialize()
Copied!

Custom retry strategies

A custom retry strategy can be provided by implementing the RetryStrategy from @node-ts/bus-core.`
retry-strategy.ts
1
export type Milliseconds = number
2
​
3
/**
4
* Defines how a message retry strategy is to be implemented that calculates the delay between subsequent
5
* retries of a message.
6
*/
7
export interface RetryStrategy {
8
/**
9
* Calculate the delay between retrying a failed message
10
* @param currentAttempt How many attempts at handling the message have failed
11
* @returns The number of milliseconds to delay retrying a failed message attempt
12
*/
13
calculateRetryDelay (currentAttempt: number): Milliseconds
14
}
15
​
Copied!
An example of a retry strategy is as follows
default-retry-strategy.ts
1
import { Milliseconds, RetryStrategy } from './retry-strategy'
2
​
3
const MAX_DELAY_MS = 2.5 * 60 * 60 * 1000 // 2.5 hours
4
const JITTER_PERCENT = 0.1
5
​
6
/**
7
* A default message retry strategy that exponentially increases the delay between retries
8
* from 5ms to 2.5 hrs for the first 10 attempts. Each retry delay includes a jitter of
9
* up to 10% to avoid deadlock-related errors from continually blocking.
10
*/
11
export class DefaultRetryStrategy implements RetryStrategy {
12
calculateRetryDelay (currentAttempt: number): Milliseconds {
13
const numberOfFailures = currentAttempt + 1
14
const constantDelay: Milliseconds = Math.pow(5, numberOfFailures)
15
16
const jitterAmount = Math.random() * JITTER_PERCENT * constantDelay
17
const jitterDirection = Math.random() > 0.5 ? 1 : -1
18
const jitter = jitterAmount * jitterDirection
19
20
const delay = Math.round(constantDelay + jitter)
21
return Math.min(delay, MAX_DELAY_MS)
22
}
23
}
24
​
Copied!
​