Quick revision
The short answer
retrying is a higher-order function: it takes a Supplier<T> and returns a new Supplier<T> that, when called, runs the original up to attempts times, returns the first successful result, and rethrows the last RuntimeException if every attempt fails. We use it as Supplier<Rate> r = retrying(() -> client.fetchRate(), 3); r.get();. It must check that attempts is greater than 0, otherwise the loop never runs and last stays null, and production versions add backoff and retry only operations that are safe to repeat.
What to remember
In this answer, we saw that retrying is a higher-order function: it takes a Supplier and returns a new Supplier that runs the original up to attempts times, returning the first success and rethrowing the last failure. The returned supplier is lazy, so building it calls nothing. Checking attempts at construction prevents a confusing NullPointerException from throw last, and production versions add backoff with jitter, retry only temporary failures of safe operations, keep earlier failures as suppressed exceptions and respect interruption.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
retrying is a higher-order function: it takes a Supplier<T> and returns a new Supplier<T> that, when called, runs the original up to attempts times, returns the first successful result, and rethrows the last RuntimeException if every attempt fails. We use it as Supplier<Rate> r = retrying(() -> client.fetchRate(), 3); r.get();. It must check that attempts is greater than 0, otherwise the loop never runs and last stays null, and production versions add backoff and retry only operations that are safe to repeat.
Why this question is asked
Retrying a flaky call is something almost every service needs: a rate service times out, a database connection drops, and one more attempt usually succeeds. Writing the retry loop inline at every call site mixes infrastructure with business logic, while wrapping it in a function that returns a function keeps it reusable and lets the caller decide when the call actually happens. Interviewers ask this to see whether we can write a correct higher-order function with generics and lambdas, and whether we spot its edge cases. In this answer, we will recap higher-order functions, write retrying, use it, walk through how it behaves, fix the zero-attempts bug, and then see what production code adds.
1A Quick Recap of Higher-Order Functions
A higher-order function is a function that takes another function as an argument, returns a function, or both. In Java, "functions" are objects implementing functional interfaces such as Supplier<T>, which has one method, T get(), taking no arguments and producing a value. Lambdas and method references give us those objects concisely.
We already use many higher-order functions: Stream.map takes a function, Comparator.comparing takes a function and returns a Comparator. retrying will do both: it takes a Supplier and returns a Supplier. The returned Supplier is a wrapper; it looks like the original to the caller, but adds behaviour around each call.
2Writing retrying
Here is the function, including the check on attempts that we will discuss shortly.
Notice that retrying itself does not call action at all. It returns a lambda, and the loop only runs when someone calls get() on that lambda. The lambda captures action and attempts, so each returned Supplier carries its own configuration. The generic type T flows through unchanged, so retrying works for any result type.
3Using It
To see the behaviour, we can use a supplier that fails twice and then succeeds, counting its calls.
- Call action.get()attempt i of n
- Did it throw a RuntimeException?YesRemember it as lastNoReturn the result
- Attempts left?YesTry againNothrow last
3 steps in order. Play them, or step through them one at a time.
The first println shows the laziness: building the retrying supplier costs nothing and calls nothing. If we had used retrying(flaky, 2) instead, both attempts would fail and get() would throw the IllegalStateException with the message "timeout on call 2", the last failure, which is usually the most relevant one.
4Why attempts Must Be Greater Than 0
Without the check at the top, retrying(action, 0) would return a supplier whose loop never runs. It would skip straight to throw last with last still null, and in Java, throwing null throws a NullPointerException. The caller would see a confusing NPE from inside the retry helper instead of a clear message about a bad argument.
Notice that the check runs when retrying is called, not when get() is called. That is deliberate: a bad configuration fails at startup, where the supplier is built, rather than later at the first real call.
5What Production Code Adds
The simple version is a good interview answer, but real retry logic needs more. First, backoff: retrying immediately often hits the same overloaded service again, so we wait between attempts, usually with an exponentially growing delay plus some random jitter so that many clients do not retry in lockstep. Second, we should retry only failures that are temporary and only operations that are safe to repeat. Retrying an IllegalArgumentException will never help, and retrying a payment request that may already have succeeded can charge a customer twice unless the operation is idempotent, meaning repeating it has the same effect as doing it once.
Third, we should keep the earlier failures for diagnosis, for example by adding them as suppressed exceptions to the one we throw, and respect thread interruption while waiting. A sketch of the waiting part looks like this.
In real services I would usually reach for an existing library such as Resilience4j, or the retry support in Spring, which recent Spring Framework versions include in the core framework (check your version), because they also handle metrics, configuration and circuit breaking.
6Follow-up questions
Why return a Supplier instead of just running the retries and returning T?
Returning a Supplier separates configuration from execution. We can build the retrying supplier once, pass it to other code, and call it later or many times. It also composes: the result is an ordinary Supplier, so it can be wrapped again, for example with a timing or logging decorator.
Should retrying catch Exception instead of RuntimeException?
Supplier.get() cannot throw checked exceptions, so RuntimeException covers everything a Supplier can throw except Errors. Catching Error, such as OutOfMemoryError, would be wrong, because retrying cannot fix it. Many real versions narrow it further and accept a predicate that decides which exceptions are worth retrying.
Is the returned Supplier thread-safe?
Yes, as long as the action is. The lambda keeps its state, last and the loop counter, in local variables that belong to each call of get(), so two threads calling it at once do not share anything except the captured action and attempts, which never change.
7Conclusion
In this answer, we saw that retrying is a higher-order function: it takes a Supplier and returns a new Supplier that runs the original up to attempts times, returning the first success and rethrowing the last failure. The returned supplier is lazy, so building it calls nothing. Checking attempts at construction prevents a confusing NullPointerException from throw last, and production versions add backoff with jitter, retry only temporary failures of safe operations, keep earlier failures as suppressed exceptions and respect interruption.
Open with
retrying is a higher-order function, meaning it takes a function and returns one. It takes a Supplier of T and the number of attempts, and returns a new Supplier of T.
Then, if they want more
Inside the returned lambda I keep a RuntimeException called last, loop attempts times, and in each iteration try action.get and return immediately if it succeeds. If it throws, I store the exception and go round again. After the loop, I throw last, so the caller sees the most recent failure.
Usage is Supplier of Rate r equals retrying of a lambda calling client.fetchRate, with 3, and then r.get. One nice property is that it's lazy: building the supplier calls nothing, the retries only happen on get, so I can configure it once and pass it around. The edge case is attempts of zero or less.
The loop wouldn't run, last would still be null, and throw null gives a NullPointerException, so I validate attempts up front and throw an IllegalArgumentException when the supplier is built. In production I'd add more. A backoff between attempts, exponential with jitter. Only retrying temporary failures, not something like IllegalArgumentException.
Only retrying operations that are safe to repeat, so a payment needs to be idempotent. Keeping earlier failures as suppressed exceptions, and restoring the interrupt flag. Usually I'd use Resilience4j or Spring's retry support instead of writing my own.
About this answer
- Last updated
- 12 November 2026
- 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.
- Official documentation
- java.util.stream, package documentation, java.util.function, package documentation
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 higher-order function retrying(Supplier<T> action, int attempts) that returns a...": https://scrivio-interview-library.netlify.app/java/functional-design/77b6dfb13e/