Skip to the content
Krizaka Java
Skip to Content
Krizaka Java

Idempotency keys

krizaka-idempotency — an HTTP action runs at most once per Idempotency-Key; a retry replays its response.

<dependency>
  <groupId>com.krizaka</groupId>
  <artifactId>krizaka-spring-boot-starter-idempotency</artifactId>
</dependency>

A client whose connection dropped after your service accepted a request cannot tell whether it ran. Retrying blind pays twice, not retrying loses the order. With an Idempotency-Key header the retry is safe — promoted from Sovkora, where every paid run start works this way.

krizaka:
  idempotency.store: jdbc
spring.sql.init.schema-locations: classpath:com/krizaka/idempotency/schema-postgresql.sql
@PostMapping("/api/v1/orders")
ResponseEntity<Order> create(@RequestBody NewOrder order, @AuthenticationPrincipal Jwt caller,
    @RequestHeader(value = IdempotencyKeys.KEY_HEADER, required = false) String key) {
  return idempotency
      .execute(new IdempotentRequest("orders.create", caller.getSubject(), key, order),
          Order.class, () -> orders.create(order))
      .toResponse(HttpStatus.CREATED);
}

The contract

RequestAnswer
first, with a keythe action runs; its response is stored in the action's transaction
retry, same key, same requestthe stored response, with Idempotent-Replayed: true — the action does not run
same key, another request422 Problem Details, code idempotency-key-reused
two at once, same keythe second waits on the key, then replays the first
the action failsnothing is recorded: the retry runs for real
no keythe action runs, every time
a malformed key400 Problem Details, code invalid-idempotency-key (1 to 255 visible ASCII characters)

A key belongs to a scope and a subject: one customer's key never replays another's. The request is fingerprinted as the SHA-256 of its canonical JSON, so the order of its fields is not a difference. Keys are kept krizaka.idempotency.ttl (24 hours) and purged on a schedule.

Proven

JdbcIdempotencyIT runs it on PostgreSQL — replay, reuse, rollback, two concurrent requests on one key, purge — and the example app proves it over HTTP. Every execution is observed as krizaka.idempotency (see Observability).

Configuration

PropertyDescription
krizaka.idempotency.purge-intervalDurationdefault 1hDelay between two purges of the keys older than the time-to-live.
krizaka.idempotency.storeStoreno defaultWhere keys and their responses are kept: 'jdbc' (PostgreSQL, in the action's transaction, shared by every instance) or 'memory' (one instance). Required to get the Idempotency bean; never inferred from the classpath.jdbcmemory
krizaka.idempotency.tableStringdefault idempotency_keysTable the keys are kept in when the store is 'jdbc'.
krizaka.idempotency.ttlDurationdefault 24hHow long a key replays its response; after it, the same key runs the action again.

On this page