Java tutorial · Intermediate · 15 min

A reliable payments API with Spring Boot: validation, idempotency, outbox

The network drops right after a transfer is sent: the client does not know whether it went through and sends the request again. Without precautions, the account is debited twice. Here is how to build a payments API with Spring Boot that validates its input, never processes the same request twice and publishes its events without losing any.

Tested source code, free to use: GitHub, Scopas-Team/java-finance-tutorials (Apache 2.0 licence)

The examples are written for Spring Boot 3.5 and Java 21 or later; they apply to Spring Boot 4 with few changes.

1. Validate the request at the door

public record TransferRequest(
        @NotBlank @Pattern(regexp = "[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}") String debtorIban,
        @NotBlank @Pattern(regexp = "[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}") String creditorIban,
        @NotNull @Positive @Digits(integer = 13, fraction = 2) BigDecimal amount,
        @NotBlank @Pattern(regexp = "[A-Z]{3}") String currency,
        @Size(max = 140) String reference) {
}

Jakarta Validation annotations reject malformed requests before they reach the business logic. Format alone is not enough for an IBAN: add a custom constraint that checks the check digits (modulo 97). The amount is a two-decimal BigDecimal, never a double (see our tutorial on money in Java).

2. An idempotency key supplied by the client

The client generates a unique ID per transfer and sends it again unchanged if it retries. The server keeps track of the keys already processed and returns the same response.

@RestController
@RequestMapping("/transfers")
class TransferController {

    private final TransferService service;

    TransferController(TransferService service) {
        this.service = service;
    }

    @PostMapping
    ResponseEntity<TransferCreated> create(@RequestHeader("Idempotency-Key") UUID key,
                                           @Valid @RequestBody TransferRequest request) {
        return ResponseEntity.status(HttpStatus.CREATED).body(service.create(key, request));
    }
}

3. Write everything in a single transaction

@Service
class TransferService {

    @Transactional
    public TransferCreated create(UUID key, TransferRequest request) {
        String fingerprint = Fingerprints.sha256(request);

        Optional<ProcessedRequest> existing = processedRequests.findById(key);
        if (existing.isPresent()) {
            if (!existing.get().getFingerprint().equals(fingerprint)) {
                throw new KeyReusedException(key);          // same key, different request
            }
            return existing.get().getResult();              // replay: same response, no new debit
        }

        Transfer transfer = transfers.save(Transfer.from(request));
        TransferCreated result = new TransferCreated(transfer.getId(), transfer.getStatus());

        processedRequests.save(new ProcessedRequest(key, fingerprint, result));
        outbox.save(OutgoingEvent.transferCreated(transfer));   // see step 4
        return result;
    }
}

The transfer, the key record and the event to publish are written together: either everything is saved, or nothing is. If two requests with the same key arrive at the same time, both pass the check, but the unique constraint on the key makes the second fail at commit. Map that error (DataIntegrityViolationException) to a 409 response: the client retries and gets the stored response.

4. Publishing events without losing any: the outbox

After a transfer, other systems must be told (accounting, notifications, fraud prevention). Sending the Kafka message directly from the service causes a problem: if the database commits and the send fails, or the reverse, the two systems diverge. The answer is to write the event to an outbox table, in the same transaction, then publish it separately:

@Component
class OutboxPublisher {

    @Scheduled(fixedDelay = 1000)
    @Transactional
    public void publish() {
        for (OutgoingEvent e : outbox.findTop100ByPublishedFalseOrderByIdAsc()) {
            kafka.send("transfers", e.getKey(), e.getPayload()).join();   // waits for Kafka's ack
            e.markPublished();
        }
    }
}

5. Readable errors with ProblemDetail

@RestControllerAdvice
class ErrorHandling {

    @ExceptionHandler(KeyReusedException.class)
    ProblemDetail keyReused(KeyReusedException e) {
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT,
                "This idempotency key has already been used for a different transfer request.");
        problem.setTitle("Idempotency key reused");
        return problem;
    }
}

With spring.mvc.problemdetails.enabled=true, Spring also returns validation errors in the standard application/problem+json format (RFC 9457), which clients know how to read.

6. Prove idempotency with a test

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Testcontainers
class TransferIdempotencyTest {

    @Container
    @ServiceConnection
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:17");

    @Autowired TestRestTemplate rest;
    @Autowired TransferRepository transfers;

    @Test
    void replayedRequestCreatesOnlyOneTransfer() {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Idempotency-Key", UUID.randomUUID().toString());
        HttpEntity<TransferRequest> request = new HttpEntity<>(validRequest(), headers);

        var first = rest.postForEntity("/transfers", request, TransferCreated.class);
        var second = rest.postForEntity("/transfers", request, TransferCreated.class);

        assertThat(second.getBody()).isEqualTo(first.getBody());
        assertThat(transfers.count()).isEqualTo(1);
    }
}

Testcontainers starts a real PostgreSQL, and @ServiceConnection wires the application to it with no configuration. Add a test that sends both requests in parallel to check the concurrent case.

7. The rest of the production checklist

Key points

Payment APIs to build or make reliable?

Our Java consultants work on your Spring Boot projects in banking and insurance, from design to go-live.

Contact us All tutorials

Worth a look