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.
More Related questions...