Backoff is a strategy for dealing with failures, conflicts, or resource competition.
The core logic is: when an operation fails or encounters a limitation, it will pause for a period of time before trying again, and the retry interval is usually adjusted dynamically to avoid increasing system pressure or conflicts.
let’s see how spring-framework implement it.
BackOff
Strategy interface for providing a BackOffExecution that indicates the rate at which an operation should be retried.
1 2 3 4 5 6
@FunctionalInterface publicinterfaceBackOff{
BackOffExecution start();
}
BackOffExecution
An executable instance of a given BackOff strategy.
privatelongapplyJitter(long interval){ long jitter = getJitter(); if (jitter > 0) { long initialInterval = getInitialInterval(); long applicableJitter = jitter * (interval / initialInterval); long min = Math.max(interval - applicableJitter, initialInterval); long max = Math.min(interval + applicableJitter, getMaxInterval()); return min + (long) (Math.random() * (max - min)); } return interval; }
}
}
Usage
1 2 3 4 5 6 7 8 9 10 11 12 13
ExponentialBackOff backOff = new ExponentialBackOff();
BackOffExecution execution = backOff.start();
// In the operation recovery/retry loop: long waitInterval = execution.nextBackOff(); if (waitInterval == BackOffExecution.STOP) { // do not retry operation } else { // sleep, for example, Thread.sleep(waitInterval) // retry operation }