Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Write a method that retries a call to a payment gateway up to 3 times with exponential backoff using Spring Retry, and returns a fallback when all attempts fail.

We add @EnableRetry to a configuration class, annotate the gateway method with @Retryable(retryFor = GatewayException.class, maxAttempts = 3, backoff = @Backoff(delay = 200, multiplier = 2)), and write a @Recover method in the same class that takes the exception as its first parameter, then the same arguments, and returns the same type as the fallback. Retry works through a proxy, so the method must be called from another bean, and we only retry a payment call when it is idempotent or carries an idempotency key.

Why this question is asked

Payment gateways fail in ordinary ways: a timeout, a 503 during their deployment, a dropped connection. Retrying a couple of times with a growing pause hides most of those blips from the customer. Interviewers ask for this code because it is short, but it tests three things at once: whether we know the annotations, whether we understand that retries run through a proxy, and whether we realise that retrying a charge can charge the customer twice. In this answer, we will set up Spring Retry, write the retrying method and its fallback, trace exactly when each attempt happens, see why self-invocation breaks it, and make the call safe with an idempotency key.

1Setting Up Spring Retry

Spring Retry is a separate library, so we add org.springframework.retry:spring-retry and, because it applies retries with an aspect, spring-boot-starter-aop (renamed spring-boot-starter-aspectj in Boot 4; check your version). Then we switch it on with @EnableRetry, which registers the machinery that wraps beans with @Retryable methods in a proxy, a generated object that intercepts calls and repeats them when they fail.

Java
@Configuration
@EnableRetry
class RetryConfig { }

Since Spring Framework 7, the core framework also has its own @Retryable in org.springframework.resilience.annotation, enabled with @EnableResilientMethods. Its attributes differ, for example maxRetries instead of maxAttempts. The code below uses the Spring Retry library, which the question names.

2Writing the Retrying Method and Its Fallback

The method itself contains only the happy path. The annotation describes which failures to retry, how many attempts to make and how long to wait between them. The @Recover method is called once all attempts have failed.

Java
@Service
class PaymentClient {
private final GatewayApi gateway;
PaymentClient(GatewayApi gateway) { this.gateway = gateway; }
@Retryable(retryFor = GatewayException.class,
maxAttempts = 3,
backoff = @Backoff(delay = 200, multiplier = 2))
public PaymentResult charge(ChargeRequest req) {
log.info("attempt for {}", req.idempotencyKey());
return gateway.charge(req); // throws GatewayException on timeout or 503
}
@Recover
public PaymentResult chargeFallback(GatewayException e, ChargeRequest req) {
log.warn("gateway down for {}: {}", req.idempotencyKey(), e.getMessage());
return PaymentResult.pending(req.idempotencyKey()); // order waits for a later reconciliation
}
}

Notice the signature of the @Recover method. Its first parameter is the exception type, and the rest match the parameters of charge(), in the same order. Its return type is the same, PaymentResult. Spring Retry finds the recoverer by matching these, so a mismatch, for example returning Object or forgetting the request parameter, means the recoverer is not found and the last exception is thrown instead.

retryFor limits retries to GatewayException. A validation error such as an InvalidCardException is not retried, which is what we want: trying the same declined card three times will not make it valid. (Older code uses the attribute value or include; retryFor is the current name.)

3When Each Attempt Happens

maxAttempts counts the first call, so 3 means one call plus two retries. The backoff starts at delay and is multiplied after each failure.

Java
// gateway fails every time:
// 00.000 attempt for K-42 first call
// 00.200 attempt for K-42 after 200 ms
// 00.600 attempt for K-42 after 400 ms (200 x 2)
// 00.600 gateway down for K-42 @Recover returns PaymentResult.pending
Step throughcharge() with three attempts
  1. Call gatewayattempt 1
  2. GatewayException?other exceptions are not retried
    YesWait 200 ms, attempt 2NoReturn the result
  3. Fails again?
    YesWait 400 ms, attempt 3NoReturn the result
  4. Fails a third time?
    YesCall @RecoverNoReturn the result
  5. Return PaymentResult.pendingfallback value

5 steps in order. Play them, or step through them one at a time.

So the whole thing gives up after about 600 ms plus the time of the three calls. That total matters: if the HTTP timeout is 5 seconds, three timed-out attempts take over 15 seconds, so the gateway client's own timeout must be short enough for the retries to fit inside what the customer will wait. maxDelay can cap the backoff when the multiplier would otherwise grow large.

4Why Self-Invocation Is Not Retried

Like @Transactional and @Async, @Retryable works only when the call goes through the proxy. If another method in PaymentClient calls charge(req), that is this.charge(req), a plain call on the real object, so it runs once and throws on the first failure.

The fix is the same as for other proxy-based features: call charge() from a different bean, such as a CheckoutService that injects PaymentClient. The method must also be public and not final, because the proxy is usually a generated subclass that cannot override private or final methods.

5Retrying Payments Safely

Retrying is only safe when doing the operation twice has the same effect as doing it once. This property is called idempotency. A charge is not naturally idempotent: if the first attempt reached the gateway and charged the card, but the response was lost to a timeout, our retry charges the card again.

Most payment gateways solve this with an idempotency key: a unique value per logical payment, sent as a header. The gateway remembers the key, and a second request with the same key returns the result of the first one instead of charging again. So we generate the key once, when the customer confirms the order, store it with the order, and send the same key on every attempt.

Java
record ChargeRequest(String idempotencyKey, long amountMinor, String currency, String cardToken) {}
var req = new ChargeRequest(order.paymentKey(), 4999, "EUR", token); // key stored with the order
paymentClient.charge(req);
// attempt 1: charged, response lost to a timeout
// attempt 2: gateway sees K-42 again and returns the same charge, no second debit

Without such a key, the safe choice is to retry only errors where we know the request did not reach the gateway, such as a connection refused, and treat timeouts as unknown, to be resolved by asking the gateway for the payment status.

6Follow-up questions

How would you add jitter to the backoff?

Jitter is randomness added to each delay so that many clients that failed at the same moment do not retry at the same moment. In Spring Retry, @Backoff(delay = 200, multiplier = 2, random = true) uses ExponentialRandomBackOffPolicy, which picks each sleep randomly between the current delay and the delay times the multiplier, so the waits become something like 200 to 400 ms, then 400 to 800 ms. Spring Framework 7's own @Retryable has a jitter attribute for the same purpose.

What happens if no @Recover method matches?

After the last attempt, Spring Retry throws the last exception, wrapped in an ExhaustedRetryException when it looked for a recoverer and found none that fits. That is a common sign that the recover signature does not match the retryable method.

Would you use Resilience4j instead?

For a single retry, Spring Retry or Framework 7's built-in retry is enough. When we also want a circuit breaker, rate limiter and time limiter with shared metrics, Resilience4j combines them and integrates with Micrometer, so many teams use it for outbound calls.

7Conclusion

In this answer, we enabled Spring Retry with @EnableRetry, retried only GatewayException with three attempts and exponential backoff of 200 then 400 ms, returned a pending result from a matching @Recover method, saw that self-invocation skips the proxy, and made the retry safe with an idempotency key.

What to say in the interviewAbout 90 seconds aloud

Open with

I'd add spring-retry and AOP, put @EnableRetry on a configuration class, and annotate the gateway call with @Retryable, using retryFor equals GatewayException.class, maxAttempts equals 3 and backoff equals @Backoff with delay 200 and multiplier 2. maxAttempts includes the first call, so that's one call and two retries, waiting 200 milliseconds and then 400.

Then, if they want more

I only retry the gateway's transient exception, never a declined card or a validation error. In the same class I'd write a @Recover method whose first parameter is the GatewayException, followed by the same ChargeRequest parameter, returning the same PaymentResult type. Spring Retry matches on that signature, so if it doesn't match, the last exception is thrown instead.

My fallback would return a pending result so the order can be reconciled later rather than failing outright. Two important caveats. Retry works through a proxy, so the method must be public and called from another bean; a call from inside PaymentClient runs once.

And a payment isn't naturally idempotent: if the first attempt charged the card but the response timed out, a retry could charge it again. So I'd generate an idempotency key when the order is confirmed and send it on every attempt, so the gateway returns the original charge.

I'd also add jitter with random equals true, and keep the HTTP timeout short enough for all attempts to fit.

About this answer

Last updated
12 November 2026
Versions it names
Spring Framework 7
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write a method that retries a call to a payment gateway up to 3 times with exponential...": https://scrivio-interview-library.netlify.app/spring-boot/spring-utilities/9ac342bc69/