Card 06/ 09

GotchaDifficulty: Intermediate1 min

Why Your Retry Policy Tried Four Times

The configuration says three retries. The support ticket has four attempts in the log, four charges on the card, and a customer who is unhappy about the fourth.

java
int maxRetries = 3;
int attempt = 0;

while (attempt <= maxRetries) {
    send(payment);
    attempt++;
}

attempt starts at zero, so the body runs for 0, 1, 2 and 3 — four passes for a limit of three. <= on a counter that starts at zero always runs one more time than the number on the right.

What each bound does to a counter starting at zero, with a limit of three
ConditionHighest valuePassesOutcome
attempt < maxRetries23Three attempts, as configured
attempt <= maxRetries34One attempt too many
attempt < maxRetries - 112One attempt too few, and nothing says so

Start the counter at zero and compare with <, or start it at one and compare with <=. Mixing the two is where every loop that is one out comes from, and picking one convention and keeping it is cheaper than checking each loop.