Idempotency Keys and Safe Retries: Implementing Exactly-Once Semantics in Spring Boot APIs

Introduction

In distributed systems, the question is never if a network request will fail — it is when. A payment service processes a charge, the response travels back across the network, and then the connection drops. Did the charge succeed? The client cannot know. If it retries, it risks charging the customer twice. If it does not, the order never completes.

This is the idempotency problem, and it sits at the heart of reliable API design. An idempotent operation is one you can safely repeat without changing the outcome beyond the initial application. The HTTP specification already defines idempotency for GET, PUT, and DELETE — but POST, the workhorse of creation and mutation, is not idempotent by default.

The fix is the Idempotency-Key header pattern, popularised by Stripe and now a de facto industry standard. The client generates a unique key (usually a UUID), attaches it to the request, and the server uses it to deduplicate: on the first request it processes and stores the result; on subsequent retries with the same key it returns the cached result without re-processing.

In this tutorial we build a production-ready idempotency filter for Spring Boot 3.5 using Redis, covering:

  • Atomic key locking to handle concurrent retries
  • Request body fingerprinting to detect key misuse
  • In-flight state tracking for long-running operations
  • Correct TTL and cache serialisation design
  • Integration tests with Testcontainers and Redis

Prerequisites

  • Java 21 or later
  • Spring Boot 3.5+
  • Redis 7+ (or Docker)
  • Maven 3.9+
  • Basic familiarity with Spring MVC and Redis

Project Setup

Create a new Spring Boot project and add these dependencies to pom.xml:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.5.0</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>
    <!-- Test -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.testcontainers</groupId>
        <artifactId>junit-jupiter</artifactId>
        <version>1.20.4</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.redis</groupId>
        <artifactId>testcontainers-redis</artifactId>
        <version>2.2.2</version>
        <scope>test</scope>
    </dependency>
</dependencies>

The application.yml:

spring:
  data:
    redis:
      host: localhost
      port: 6379
      timeout: 2s

idempotency:
  ttl-hours: 24
  require-key: false
  key-header: Idempotency-Key

Understanding the State Machine

Before writing code, understand the state machine a server must implement for each incoming request:

Client sends POST with Idempotency-Key: abc-123

Server checks Redis for key "idmp:abc-123":
  NOT FOUND  -> claim key (SET NX), execute request, store result, return 2xx/4xx
  PROCESSING -> return 409 Conflict ("in flight, retry in a moment")
  DONE:{...} -> return the cached response verbatim

Three outcomes, not two. The PROCESSING state is what prevents race conditions when a client retries immediately (before the first request finishes) or when two retries arrive at the exact same millisecond.


Reading the Request Body Twice

A OncePerRequestFilter runs before your controller. The problem: once you call HttpServletRequest.getInputStream() to hash the body for fingerprinting, the stream is exhausted and the controller receives nothing.

The solution is a caching wrapper that buffers the bytes:

package com.vimleshpandey.demo.idempotency;

import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import java.io.*;

public class CachedBodyRequestWrapper extends HttpServletRequestWrapper {

    private final byte[] body;

    public CachedBodyRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        this.body = request.getInputStream().readAllBytes();
    }

    @Override
    public ServletInputStream getInputStream() {
        ByteArrayInputStream bais = new ByteArrayInputStream(body);
        return new ServletInputStream() {
            public int read() { return bais.read(); }
            public boolean isFinished() { return bais.available() == 0; }
            public boolean isReady() { return true; }
            public void setReadListener(ReadListener l) {}
        };
    }

    @Override
    public BufferedReader getReader() {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    public byte[] getBodyBytes() { return body; }
}

Capturing the Response

Similarly, we need to intercept and buffer the outgoing response so we can store it in Redis before writing it to the client:

package com.vimleshpandey.demo.idempotency;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.WriteListener;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpServletResponseWrapper;
import java.io.*;

public class CachedBodyResponseWrapper extends HttpServletResponseWrapper {

    private final ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    public CachedBodyResponseWrapper(HttpServletResponse response) {
        super(response);
    }

    @Override
    public ServletOutputStream getOutputStream() {
        return new ServletOutputStream() {
            public void write(int b) { buffer.write(b); }
            public boolean isReady() { return true; }
            public void setWriteListener(WriteListener l) {}
        };
    }

    @Override
    public PrintWriter getWriter() {
        return new PrintWriter(new OutputStreamWriter(buffer));
    }

    public byte[] getCapturedBody() { return buffer.toByteArray(); }
}

The Cached Response Record

package com.vimleshpandey.demo.idempotency;

public record CachedResponse(
    int statusCode,
    String contentType,
    String bodyJson,
    String requestBodyHash
) {}

Configuration Properties

package com.vimleshpandey.demo.idempotency;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "idempotency")
public class IdempotencyProperties {
    private int ttlHours = 24;
    private boolean requireKey = false;
    private String keyHeader = "Idempotency-Key";

    public int getTtlHours() { return ttlHours; }
    public void setTtlHours(int v) { this.ttlHours = v; }

    public boolean isRequireKey() { return requireKey; }
    public void setRequireKey(boolean v) { this.requireKey = v; }

    public String getKeyHeader() { return keyHeader; }
    public void setKeyHeader(String v) { this.keyHeader = v; }
}

The Idempotency Service

The service encapsulates all Redis interactions. The critical operation is atomic lock acquisition using Redis SET NX EX — this ensures only one concurrent request with a given key enters the processing path:

package com.vimleshpandey.demo.idempotency;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.util.Optional;

@Service
public class IdempotencyService {

    private static final String PREFIX = "idmp:";
    private static final String PROCESSING = "PROCESSING";

    private final StringRedisTemplate redis;
    private final ObjectMapper objectMapper;
    private final IdempotencyProperties properties;

    public IdempotencyService(StringRedisTemplate redis,
                              ObjectMapper objectMapper,
                              IdempotencyProperties properties) {
        this.redis = redis;
        this.objectMapper = objectMapper;
        this.properties = properties;
    }

    /**
     * Atomically claim the key. Returns true only for the first caller.
     * Uses SET NX EX so claim + TTL are set in one atomic command.
     */
    public boolean tryClaimKey(String key) {
        Boolean claimed = redis.opsForValue()
            .setIfAbsent(PREFIX + key, PROCESSING,
                Duration.ofHours(properties.getTtlHours()));
        return Boolean.TRUE.equals(claimed);
    }

    public Optional<CachedResponse> getCachedResponse(String key) {
        String value = redis.opsForValue().get(PREFIX + key);
        if (value == null || PROCESSING.equals(value)) return Optional.empty();
        try {
            return Optional.of(objectMapper.readValue(value, CachedResponse.class));
        } catch (Exception e) {
            return Optional.empty();
        }
    }

    public boolean isInFlight(String key) {
        return PROCESSING.equals(redis.opsForValue().get(PREFIX + key));
    }

    public void storeResponse(String key, CachedResponse response) {
        try {
            String serialised = objectMapper.writeValueAsString(response);
            redis.opsForValue().set(PREFIX + key, serialised,
                Duration.ofHours(properties.getTtlHours()));
        } catch (Exception ignored) {}
    }

    public void releaseKey(String key) {
        redis.delete(PREFIX + key);
    }
}

The Idempotency Filter

Now the main event — the OncePerRequestFilter that ties it all together:

package com.vimleshpandey.demo.idempotency;

import jakarta.servlet.FilterChain;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HexFormat;

@Component
public class IdempotencyFilter extends OncePerRequestFilter {

    private static final Logger log = LoggerFactory.getLogger(IdempotencyFilter.class);

    private final IdempotencyService service;
    private final IdempotencyProperties properties;

    public IdempotencyFilter(IdempotencyService service,
                             IdempotencyProperties properties) {
        this.service = service;
        this.properties = properties;
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        String method = request.getMethod();
        return HttpMethod.GET.matches(method)
            || HttpMethod.HEAD.matches(method)
            || HttpMethod.OPTIONS.matches(method);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws IOException {
        String idKey = request.getHeader(properties.getKeyHeader());

        if (idKey == null || idKey.isBlank()) {
            if (properties.isRequireKey()) {
                sendError(response, 400, "Idempotency-Key header is required");
                return;
            }
            passThrough(request, response, chain);
            return;
        }

        // 1. Already have a completed cached result?
        var cached = service.getCachedResponse(idKey);
        if (cached.isPresent()) {
            replayCachedResponse(cached.get(), request, response);
            return;
        }

        // 2. Someone else is currently processing this key?
        if (service.isInFlight(idKey)) {
            sendError(response, 409,
                "A request with this Idempotency-Key is already in progress. Retry in a moment.");
            return;
        }

        // 3. Atomically claim the key
        if (!service.tryClaimKey(idKey)) {
            cached = service.getCachedResponse(idKey);
            if (cached.isPresent()) {
                replayCachedResponse(cached.get(), request, response);
            } else {
                sendError(response, 409, "Concurrent request detected. Retry shortly.");
            }
            return;
        }

        // 4. We hold the key — process the request
        CachedBodyRequestWrapper wrappedReq = new CachedBodyRequestWrapper(request);
        CachedBodyResponseWrapper wrappedRes = new CachedBodyResponseWrapper(response);
        String requestBodyHash = sha256Hex(wrappedReq.getBodyBytes());

        try {
            chain.doFilter(wrappedReq, wrappedRes);

            int status = wrappedRes.getStatus();
            String contentType = wrappedRes.getContentType();
            String responseBody = new String(
                wrappedRes.getCapturedBody(), StandardCharsets.UTF_8);

            if (status < 500) {
                // Cache successful and client-error responses.
                // Never cache 5xx — a server error may be transient and
                // the next retry should re-execute, not replay the failure.
                service.storeResponse(idKey,
                    new CachedResponse(status, contentType,
                        responseBody, requestBodyHash));
            } else {
                service.releaseKey(idKey);
            }

            response.setStatus(status);
            if (contentType != null) response.setContentType(contentType);
            response.getOutputStream().write(wrappedRes.getCapturedBody());
            response.getOutputStream().flush();

        } catch (Exception e) {
            service.releaseKey(idKey);
            throw new IOException("Error processing idempotent request", e);
        }
    }

    private void replayCachedResponse(CachedResponse cached,
                                      HttpServletRequest request,
                                      HttpServletResponse response) throws IOException {
        try {
            CachedBodyRequestWrapper wrapped = new CachedBodyRequestWrapper(request);
            String incomingHash = sha256Hex(wrapped.getBodyBytes());
            if (!incomingHash.equals(cached.requestBodyHash())) {
                sendError(response, 422,
                    "Idempotency-Key reused with a different request body");
                return;
            }
        } catch (IOException ignored) {}

        response.setStatus(cached.statusCode());
        if (cached.contentType() != null)
            response.setContentType(cached.contentType());
        response.addHeader("Idempotent-Replayed", "true");
        response.getWriter().write(cached.bodyJson());
    }

    private void passThrough(HttpServletRequest req,
                             HttpServletResponse res,
                             FilterChain chain) throws IOException {
        try { chain.doFilter(req, res); }
        catch (Exception e) { throw new IOException("Filter chain error", e); }
    }

    private void sendError(HttpServletResponse response,
                           int status, String message) throws IOException {
        response.setStatus(status);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.getWriter().write("{\"error\":\"" + message + "\"}");
    }

    private static String sha256Hex(byte[] input) {
        try {
            byte[] hash = MessageDigest.getInstance("SHA-256").digest(input);
            return HexFormat.of().formatHex(hash);
        } catch (Exception e) { return ""; }
    }
}

A Sample Controller

Here is a payment controller that benefits from idempotency without any additional code — the filter handles everything transparently at the HTTP layer:

package com.vimleshpandey.demo;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.UUID;

@RestController
@RequestMapping("/api/v1/payments")
public class PaymentController {

    @PostMapping
    public ResponseEntity<PaymentResponse> createPayment(
            @Valid @RequestBody PaymentRequest request) {
        // This method runs only once per unique Idempotency-Key.
        // The filter intercepts all retries before they reach here.
        String transactionId = UUID.randomUUID().toString();
        return ResponseEntity.ok(
            new PaymentResponse(transactionId, "SUCCESS",
                request.amount(), request.currency()));
    }
}

record PaymentRequest(
    @NotNull @Positive BigDecimal amount,
    @NotNull String currency,
    @NotNull String merchantId) {}

record PaymentResponse(
    String transactionId, String status,
    BigDecimal amount, String currency) {}

Testing

Unit Tests for the Filter

package com.vimleshpandey.demo;

import com.vimleshpandey.demo.idempotency.*;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import java.util.Optional;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;

class IdempotencyFilterTest {

    private final IdempotencyService service = mock(IdempotencyService.class);
    private final IdempotencyProperties props = new IdempotencyProperties();
    private final IdempotencyFilter filter = new IdempotencyFilter(service, props);

    @Test
    void whenNoCachedResponse_thenProceedAndStore() throws Exception {
        String key = "test-key-001";
        when(service.getCachedResponse(key)).thenReturn(Optional.empty());
        when(service.isInFlight(key)).thenReturn(false);
        when(service.tryClaimKey(key)).thenReturn(true);

        MockHttpServletRequest req = new MockHttpServletRequest("POST", "/api/v1/payments");
        req.addHeader("Idempotency-Key", key);
        req.setContent("{\"amount\":99.99}".getBytes());
        req.setContentType("application/json");
        MockHttpServletResponse res = new MockHttpServletResponse();

        filter.doFilterInternal(req, res, (rq, rs) -> {
            var r = (jakarta.servlet.http.HttpServletResponse) rs;
            r.setStatus(200);
            r.setContentType("application/json");
            r.getWriter().write("{\"status\":\"SUCCESS\"}");
        });

        verify(service).storeResponse(eq(key), any(CachedResponse.class));
        assertThat(res.getStatus()).isEqualTo(200);
    }

    @Test
    void whenCachedResponseExists_thenReplayWithoutForwarding() throws Exception {
        String key = "test-key-002";
        // SHA-256 of empty bytes
        String emptyHash = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
        CachedResponse cached = new CachedResponse(200, "application/json",
            "{\"status\":\"SUCCESS\"}", emptyHash);
        when(service.getCachedResponse(key)).thenReturn(Optional.of(cached));

        MockHttpServletRequest req = new MockHttpServletRequest("POST", "/api/v1/payments");
        req.addHeader("Idempotency-Key", key);
        MockHttpServletResponse res = new MockHttpServletResponse();

        var chain = mock(jakarta.servlet.FilterChain.class);
        filter.doFilterInternal(req, res, chain);

        verify(chain, never()).doFilter(any(), any());
        assertThat(res.getStatus()).isEqualTo(200);
        assertThat(res.getHeader("Idempotent-Replayed")).isEqualTo("true");
    }

    @Test
    void whenInFlight_thenReturn409() throws Exception {
        String key = "test-key-003";
        when(service.getCachedResponse(key)).thenReturn(Optional.empty());
        when(service.isInFlight(key)).thenReturn(true);

        MockHttpServletRequest req = new MockHttpServletRequest("POST", "/api/v1/payments");
        req.addHeader("Idempotency-Key", key);
        MockHttpServletResponse res = new MockHttpServletResponse();

        filter.doFilterInternal(req, res, (rq, rs) -> {});

        assertThat(res.getStatus()).isEqualTo(409);
    }
}

Integration Test with Testcontainers

package com.vimleshpandey.demo;

import com.redis.testcontainers.RedisContainer;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.springframework.test.web.servlet.MockMvc;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import java.util.UUID;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@SpringBootTest
@AutoConfigureMockMvc
@Testcontainers
class PaymentIdempotencyIntegrationTest {

    @Container
    static RedisContainer redis =
        new RedisContainer(RedisContainer.DEFAULT_IMAGE_NAME.withTag("7.4"));

    @DynamicPropertySource
    static void props(DynamicPropertyRegistry r) {
        r.add("spring.data.redis.host", redis::getHost);
        r.add("spring.data.redis.port", () -> redis.getMappedPort(6379));
    }

    @Autowired MockMvc mockMvc;

    @Test
    void duplicateRequestWithSameKeyReturnsIdenticalResponse() throws Exception {
        String key = "pay-" + UUID.randomUUID();
        String body = "{\"amount\": 150.00, \"currency\": \"EUR\", \"merchantId\": \"merchant-01\"}";

        var first = mockMvc.perform(post("/api/v1/payments")
                .header("Idempotency-Key", key)
                .contentType(MediaType.APPLICATION_JSON)
                .content(body))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.transactionId").exists())
            .andReturn();

        String firstBody = first.getResponse().getContentAsString();

        // Second request with same key — must return identical body
        mockMvc.perform(post("/api/v1/payments")
                .header("Idempotency-Key", key)
                .contentType(MediaType.APPLICATION_JSON)
                .content(body))
            .andExpect(status().isOk())
            .andExpect(header().string("Idempotent-Replayed", "true"))
            .andExpect(content().json(firstBody));
    }
}

Running the Application

Add a docker-compose.yml:

services:
  redis:
    image: redis:7.4-alpine
    ports:
      - "6379:6379"
    command: redis-server --maxmemory 256mb --maxmemory-policy allkeys-lru

Start Redis and the application:

docker compose up -d redis
./mvnw spring-boot:run

Test idempotency manually with curl:

# Generate a stable key for testing
IKEY="pay-$(uuidgen | tr -d '-' | head -c 16)"

# First request — processes the payment
curl -X POST http://localhost:8080/api/v1/payments \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $IKEY" \
  -d '{"amount": 150.00, "currency": "EUR", "merchantId": "merchant-01"}'

# Second request — returns the cached result with Idempotent-Replayed: true
curl -v -X POST http://localhost:8080/api/v1/payments \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $IKEY" \
  -d '{"amount": 150.00, "currency": "EUR", "merchantId": "merchant-01"}'

Common Pitfalls and Tips

1. Never cache a 5xx response

A server error is often transient — an overloaded database, a temporary network glitch. If you cache the 500 and replay it, the client can never recover by retrying. Always release the key on a 5xx so the next attempt re-executes.

2. The split-brain problem

The filter stores the idempotency record in Redis and the business data in a relational database. If the Redis write succeeds but the database write fails (or vice versa), the two stores disagree. For critical operations like payments, consider storing the idempotency record inside the same database transaction as the business data, using a dedicated table rather than Redis. Redis is simpler and faster but cannot participate in a 2-phase commit.

3. Side effects happen only on the first call

Emails, SMS messages, webhooks, and audit events must only fire on the original request. The filter handles this automatically — once the response is cached, the downstream controller never runs on retries. But if your controller triggers side effects before the response is serialised (e.g., sending a confirmation email at the start of the method), you must guard those calls explicitly with a flag.

4. Namespace keys by user

If you store keys globally, two different users who happen to send the same Idempotency-Key value will share a cached response — a data leak. Extend IdempotencyService to prefix keys with the authenticated user's ID: idmp:{userId}:{idempotencyKey}. Read the user principal from the Spring Security context inside the filter.

5. TTL design matters more than you think

Stripe uses 24 hours. Payment systems often keep keys for 7 days. Your TTL must be longer than your longest possible retry window. A client retrying after 25 hours with a 24-hour TTL will re-execute the operation — which may be safe or catastrophic depending on the endpoint. Financial systems generally err toward longer TTLs.

6. Idempotency is not exactly-once

No distributed system can truly guarantee exactly-once delivery across process boundaries. The pattern here gives you effectively-once processing: the operation executes at most once per unique key at the application layer, provided Redis and the database are both healthy. That is a strong enough guarantee for payments, order creation, and most mutation endpoints.


Conclusion

Idempotency keys transform fragile POST endpoints into retry-safe operations that distributed systems and mobile clients can rely on. The implementation here — a OncePerRequestFilter with Redis-backed atomic locking, request body fingerprinting, and in-flight state tracking — covers the cases that simpler tutorials miss: concurrent retries, 5xx replay prevention, key misuse detection, and correct TTL management.

The filter is cross-cutting: register it once and it protects every mutation endpoint automatically. Pair it with a client library that generates stable UUIDs for each logical operation and reuses them on retries, and you have a foundation solid enough for financial transactions and anything else where duplicates are expensive.