Tech Interview RoomStudy guides

Spring Microservices

Make a payment or order POST endpoint idempotent. Compare no protection, a unique business key, and an Idempotency-Key store.

Advanced · 2 min read · Lesson 5 of 5 in Spring Microservices

Problem

A mobile client times out and retries POST /payments. Without protection the customer is charged twice. Design the endpoint so retries are safe.

Client
Mobile app (same Idempotency-Key on retry)
↓1. POST /payments
API
PaymentController
↓2. claim key (SETNX or unique row)
Store
Redis or idempotency_record table
↓3. first request only
Processing
Payment Service🌐 Payment provider (same key)
↓4. save response for replays
Store again
🗄️ Stored response

Approach 1: No protection (wrong)

Every retry creates a new payment: double charges, duplicate orders.

Approach 2: A unique business key in the database

The client sends its own reference (clientOrderRef); a unique constraint rejects the duplicate insert, and the handler returns the existing record. Simple and robust, but it protects only resources that have a natural key, and concurrent duplicates still race until the constraint fires.

java
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import java.util.Optional;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

@Entity
class Payment {
    @Id @GeneratedValue Long id;
    @Column(unique = true, nullable = false) String clientRef;
    long amountPaise;
    String status;
    protected Payment() {}
    Payment(String clientRef, long amountPaise) { this.clientRef = clientRef; this.amountPaise = amountPaise; this.status = "CREATED"; }
}

interface PaymentRepository extends JpaRepository<Payment, Long> {
    Optional<Payment> findByClientRef(String clientRef);
}

@Service
class UniqueKeyPaymentService {
    private final PaymentRepository payments;
    UniqueKeyPaymentService(PaymentRepository payments) { this.payments = payments; }

    Payment create(String clientRef, long amount) {
        try {
            return payments.saveAndFlush(new Payment(clientRef, amount));
        } catch (DataIntegrityViolationException duplicate) {
            return payments.findByClientRef(clientRef).orElseThrow();   // retry: return the original
        }
    }
}

Approach 3: Idempotency-Key header with a shared store (optimal, Stripe-style)

The client generates a UUID per logical operation and resends it on retries. The server atomically claims the key (Redis SET NX with a TTL), processes once, stores the response, and replays it for later requests with the same key. A request with the same key but a different body is rejected with 422; a concurrent duplicate while the first is still running gets 409.

java
import java.time.Duration;
import java.util.HexFormat;
import java.security.MessageDigest;
import java.nio.charset.StandardCharsets;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

record PaymentRequest(String customerId, long amountPaise) {}
record PaymentResponse(String paymentId, String status) {}

@RestController
class IdempotentPaymentController {
    private static final Duration TTL = Duration.ofHours(24);
    private final StringRedisTemplate redis;
    private final UniqueKeyPaymentService service;

    IdempotentPaymentController(StringRedisTemplate redis, UniqueKeyPaymentService service) {
        this.redis = redis;
        this.service = service;
    }

    @PostMapping("/payments")
    ResponseEntity<String> create(@RequestHeader("Idempotency-Key") String key, @RequestBody PaymentRequest request) throws Exception {
        String fingerprint = sha256(request.toString());
        String redisKey = "idem:payments:" + key;

        Boolean claimed = redis.opsForValue().setIfAbsent(redisKey, "IN_PROGRESS|" + fingerprint, TTL);
        if (Boolean.FALSE.equals(claimed)) {
            String stored = redis.opsForValue().get(redisKey);
            if (stored == null) return ResponseEntity.status(HttpStatus.CONFLICT).body("retry");
            String[] parts = stored.split("\\|", 3);
            if (!parts[1].equals(fingerprint)) return ResponseEntity.unprocessableEntity().body("Idempotency-Key reused with a different request");
            if (parts[0].equals("IN_PROGRESS")) return ResponseEntity.status(HttpStatus.CONFLICT).body("request still processing");
            return ResponseEntity.status(HttpStatus.CREATED).header("Idempotent-Replayed", "true").body(parts[2]);   // replay
        }

        try {
            Payment p = service.create(key, request.amountPaise());          // the key doubles as the business key
            String body = "{\"paymentId\":\"" + p.id + "\",\"status\":\"" + p.status + "\"}";
            redis.opsForValue().set(redisKey, "DONE|" + fingerprint + "|" + body, TTL);
            return ResponseEntity.status(HttpStatus.CREATED).body(body);
        } catch (RuntimeException e) {
            redis.delete(redisKey);                                          // allow a clean retry after a failure
            throw e;
        }
    }

    private static String sha256(String s) throws Exception {
        return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(s.getBytes(StandardCharsets.UTF_8)));
    }
}

Feasible → optimal

  • No protection: duplicates on every retry.
  • Unique business key: strong and simple where a natural key exists; the database is the final guard.
  • Idempotency-Key store: works for any POST, returns the same response to retries, detects misuse and concurrent duplicates. Combine it with the unique constraint as a last line of defence, and pass the same key to the payment provider so their side is idempotent too.

Follow-up questions interviewers ask

Try answering each one before you open it.

Related: where should the idempotency logic live: controller, filter or aspect?

For one or two endpoints, a controller or service method is clearest. For many endpoints, move it into a HandlerInterceptor or a custom annotation (@Idempotent) handled by an aspect, which needs access to the request body (wrap it with ContentCachingRequestWrapper) and to the response to store it. Keep the store pluggable (Redis for speed, a database table when the record must be transactional with the business write).

Related: what is the difference between idempotency and deduplication of Kafka messages?

Idempotency is a property of an operation: performing it twice has the same effect as once (PUT, "set status to SHIPPED", an idempotency key). Deduplication is a technique: remembering processed message ids and skipping repeats. Kafka consumers usually combine both: naturally idempotent writes where possible, plus a processed-messages table for side effects that are not.