Spring / Spring7 Intermediate to Advanced Interview questions
How would you implement idempotency-key based duplicate request detection in a Spring REST API?
The client generates a unique key - typically a UUID - once per logical action, and sends it as a header (for example, Idempotency-Key) on the request, reusing the same key if it needs to retry.
@Component public class IdempotencyInterceptor implements HandlerInterceptor { private final StringRedisTemplate redis; public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) { String key = req.getHeader("Idempotency-Key"); if (key == null) return true; Boolean isNew = redis.opsForValue() .setIfAbsent("idem:" + key, "processing", Duration.ofMinutes(10)); if (Boolean.FALSE.equals(isNew)) { res.setStatus(409); // already seen - reject or return cached result return false; } return true; } }
A Redis SETNX-style atomic check-and-set is a natural fit: it's fast, and the built-in expiry means stale keys are cleaned up automatically without a background job. For stronger guarantees than "reject the duplicate," the handler can instead store the first request's actual response body against the key once processing completes, so a genuine retry (not just a rejected duplicate) gets back the exact same result rather than an error - which matters for clients that legitimately need to know the outcome of a request they're not sure succeeded.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
