Quick revision
The short answer
RetryingPriceService implements PriceService, receives the real PriceService (the delegate) and a maximum number of attempts in its constructor, and in price() calls delegate.price(sku) in a loop, catching only retryable exceptions, waiting with a growing backoff between attempts and rethrowing the last failure when attempts run out. A decorator is better than a subclass because it works with any PriceService implementation and can be stacked at run time with other decorators such as caching or metrics, while subclassing would need one subclass per implementation and per combination of behaviours.
What to remember
In this answer, we wrote RetryingPriceService, a decorator that implements PriceService, takes a delegate and a retry count in its constructor, and loops around delegate.price(sku), catching only retryable exceptions, backing off with jitter, keeping the interrupt flag and rethrowing the last failure. Decorators stack at run time with caching and metrics, and the JDK's java.io streams are classic examples. A subclass would bind retry to one implementation and explode into one class per combination, which is why the decorator is the better design.
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.
RetryingPriceService implements PriceService, receives the real PriceService (the delegate) and a maximum number of attempts in its constructor, and in price() calls delegate.price(sku) in a loop, catching only retryable exceptions, waiting with a growing backoff between attempts and rethrowing the last failure when attempts run out. A decorator is better than a subclass because it works with any PriceService implementation and can be stacked at run time with other decorators such as caching or metrics, while subclassing would need one subclass per implementation and per combination of behaviours.
Why this question is asked
Retry is one of the first cross-cutting behaviours every service needs, because remote calls fail now and then for reasons that go away a moment later. Interviewers ask us to write it as a decorator because the exercise tests three things at once: correct retry logic, including the edge cases most people forget, understanding of the decorator pattern, and the reasoning about composition over inheritance. In this answer, we will recap the decorator idea, write RetryingPriceService step by step, look at what each detail protects against, stack it with other decorators, and explain why a subclass would be the wrong tool.
1A Quick Recap of the Decorator Pattern
A decorator is an object that implements the same interface as the object it wraps, holds a reference to it, and adds behaviour before or after passing calls on. The wrapped object is usually called the delegate. Because the decorator has the same interface, the caller cannot tell whether it has the real service or a decorated one, and it does not need to.
Our interface is as small as an interface can be: interface PriceService { Price price(String sku); }. There may be several implementations, for example a RemotePriceService that calls a pricing API over HTTP and a FixedPriceService used in tests.
2Writing RetryingPriceService
Here is the decorator. It takes the delegate, the maximum number of attempts and the initial backoff in its constructor, and implements price() with a loop.
Let us walk through the decisions. The loop counts total attempts, so maxAttempts of 3 means one call and two retries; naming it this way avoids an off-by-one argument in review. We catch only PriceUnavailableException, an exception the remote implementation throws for timeouts and 5xx responses. A ProductNotFoundException or an IllegalArgumentException will fail the same way every time, so retrying it only wastes time and load; it passes straight through.
The backoff doubles after each failure, and we add jitter, a small random extra delay, so that 500 instances that failed at the same moment do not all retry at the same moment and overload the pricing service again. We do not sleep after the last attempt, because nobody is waiting for it. When attempts run out we rethrow the last exception, so the caller sees the real cause rather than a generic retry error. Finally, if the thread is interrupted while sleeping, we restore the interrupt flag and stop, because an interrupt usually means the application is shutting down or the request was cancelled.
3Seeing It Work
A quick test with a fake delegate that fails twice and then succeeds shows the behaviour.
- Call delegate.price(sku)
- Did it succeed?YesReturn the priceNoCheck the exception
- Retryable and attempts left?
PriceUnavailableExceptionand attempt < maxYesSleep backoff plus jitter, double backoffNoRethrow the last exception - Try the next attemptback to the first step
4 steps in order. Play them, or step through them one at a time.
Notice that the test needs no network and no framework. The decorator is ordinary Java, so it is tested like any other class.
4Stacking Decorators at Run Time
The real strength of decorators shows when we combine them. Each one adds one behaviour, and we choose the combination when we wire the application.
Each class stays small and testable on its own, and we can change the combination, or the order, without changing any of them. The JDK uses the same idea in java.io: new BufferedInputStream(new FileInputStream(file)) adds buffering by wrapping, and a GZIPInputStream can wrap that to add decompression. Order matters, and choosing it is a design decision of its own.
5Why a Subclass Is the Wrong Tool
The subclass approach would be class RetryingRemotePriceService extends RemotePriceService, overriding price() to loop around super.price(sku). It works for exactly one implementation. If we also want retry around another implementation, we need another subclass. If we then want caching, we need CachingRemotePriceService, and for both, CachingRetryingRemotePriceService. With three behaviours and two implementations, that is up to 14 classes, and the number grows with every new behaviour. This is the class explosion that the decorator pattern exists to avoid.
Subclassing also ties the behaviour to the parent's internals, so a change in RemotePriceService can break the subclass, and it cannot be applied to a class that is final or that we do not own, such as a client generated by a library. A decorator depends only on the interface, so it works with any implementation, including ones written later.
| Question | Subclass | Decorator |
|---|---|---|
Works with every PriceService? | No, one implementation each | Yes |
| Combine retry, caching, metrics | One class per combination | Stack at wiring time |
| Works on final or library classes | No | Yes |
| Coupled to implementation details | Yes, via super | No, only the interface |
6Follow-up questions
Would you write this by hand in a Spring application?
For a coding exercise, yes. In production I would usually use a library such as Resilience4j or Spring Retry, which provide the same decorator idea with configuration, metrics and well-tested edge cases. Writing it by hand once is still the best way to understand what those libraries do.
Is it safe to retry any call?
Only idempotent ones, calls that have the same effect when repeated. Reading a price is idempotent. Charging a card is not, unless the API accepts an idempotency key so that a repeated request is recognised and not executed twice.
Where should the retry count and backoff come from?
From configuration, passed into the constructor by the composition root or a Spring configuration class. Keeping them as constructor parameters makes the decorator easy to test with tiny delays, as we did above.
7Conclusion
In this answer, we wrote RetryingPriceService, a decorator that implements PriceService, takes a delegate and a retry count in its constructor, and loops around delegate.price(sku), catching only retryable exceptions, backing off with jitter, keeping the interrupt flag and rethrowing the last failure. Decorators stack at run time with caching and metrics, and the JDK's java.io streams are classic examples. A subclass would bind retry to one implementation and explode into one class per combination, which is why the decorator is the better design.
Open with
I'd write RetryingPriceService implementing PriceService, with the delegate, the max number of attempts and an initial backoff passed in the constructor. In price, a for loop calls delegate.price and returns immediately on success.
Then, if they want more
It catches only the exception that means a transient failure, say PriceUnavailableException for timeouts and 5xx, so a product-not-found error passes straight through instead of being retried pointlessly.
Between attempts it sleeps with exponential backoff plus some random jitter, so many instances don't retry in lockstep, it doesn't sleep after the final attempt, and when attempts run out it rethrows the last exception so the caller sees the real cause. If the sleep is interrupted, it restores the interrupt flag and stops.
As for why a decorator rather than a subclass: the decorator depends only on the interface, so it wraps any implementation, including final classes or generated clients, and I can stack it with caching or metrics decorators at wiring time, exactly like BufferedInputStream wraps another stream in java.io.
With subclassing I'd need a subclass per implementation and per combination of behaviours, which is a class explosion, and it would be coupled to the parent's internals. Also, I'd only retry idempotent calls.
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 official documentation for the version you use. 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 decorator that adds retry around this interface:": https://scrivio-interview-library.netlify.app/java/structural-patterns/27fa2fee21/