ProLesson 10.2Advanced4 min readUpdated 31 October 2026
System Design Patterns with Spring Boot
Design resilient, production-grade distributed architectures with Idempotency Keys, Redis Distributed Locks, and the Outbox Pattern.
In senior system design interviews, you are expected to design distributed systems that survive network partitions, duplicate requests, and race conditions.
Here are three foundational patterns you must know how to implement with Spring Boot.
01Idempotent API Design with Redis
An operation is idempotent if applying it multiple times produces the exact same result as applying it once.
The Real-World Problem
A customer clicks "Pay $100". Their mobile connection drops momentarily. The mobile app automatically retries the HTTP POST request. If your payment API is not idempotent, the customer is billed $200.
The Implementation Strategy
- The client generates a unique UUID
Idempotency-Keyheader (e.g.,pay_tx_88921). - An interceptor checks Redis using an atomic
SET key value NX EX secondscommand. - If the key already exists and has a cached response, return the cached HTTP response immediately without processing another charge.
- If the key is new, process the payment, store the response in Redis with a 24-hour TTL, and release the processing lock.
java
package com.veltoryx.interceptor;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import java.time.Duration;
@Component
public class IdempotencyInterceptor implements HandlerInterceptor {
private final StringRedisTemplate redisTemplate;
public IdempotencyInterceptor(StringRedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (!"POST".equalsIgnoreCase(request.getMethod())) {
return true;
}
String idempotencyKey = request.getHeader("Idempotency-Key");
if (idempotencyKey == null || idempotencyKey.isBlank()) {
return true; // Or reject with 400 Bad Request depending on API policy
}
String redisKey = "idemp:" + idempotencyKey;
// Atomic SETNX: returns true only if key did not previously exist
Boolean isFirstRequest = redisTemplate.opsForValue()
.setIfAbsent(redisKey, "IN_PROGRESS", Duration.ofMinutes(10));
if (Boolean.FALSE.equals(isFirstRequest)) {
String cachedResult = redisTemplate.opsForValue().get(redisKey);
if ("IN_PROGRESS".equals(cachedResult)) {
response.setStatus(409); // Conflict: Request already being processed
response.getWriter().write("{"error": "Request currently in flight"}");
return false;
}
// Return cached previous response
response.setStatus(200);
response.setContentType("application/json");
response.getWriter().write(cachedResult);
return false;
}
return true;
}
}Loading the rest of the lesson…