Video in progress

A client retries a request after a network error. How do you prevent duplicate rows and operations executed twice in a Hibernate-based service?

The database has to guarantee idempotency: a unique constraint on the idempotency key the client sends (or on a business key), store the first result and return it for the repeated request. Just "check first, then write" (existsBy + save) does not work with parallel retries.

📖 Answer

The situation: a mobile app sent a request to create a payment, the server saved the order, but the response got lost on the network. The app retries, and now there are two payments.

My approach:

  1. The client sends an Idempotency-Key (a UUID) for every operation. The server writes it to a separate table:
create table idempotency_key (
  key uuid primary key,
  request_hash text not null,
  status text not null,          -- IN_PROGRESS / DONE
  response jsonb,
  created_at timestamptz not null default now()
);
  1. Inside the transaction, the first thing to do is insert that key:
@Transactional
public PaymentResult create(UUID key, CreatePayment cmd) {
    int inserted = keys.insertIfAbsent(key, hash(cmd));   // insert ... on conflict do nothing
    if (inserted == 0) {
        return keys.findDone(key).orElseThrow(InProgressException::new);
    }
    PaymentResult r = payments.create(cmd);
    keys.markDone(key, r);
    return r;
}

If two parallel retries arrive, the second one waits at the on conflict (until the first transaction commits) and then gets the existing result. The key and the payment are in one transaction, so one cannot be saved while the other is lost.

  1. A unique constraint at the business level too: unique (merchant_id, external_order_id). Even if the client sends no key, the most important duplicates are stopped by the database.

What does not work: existsByKey() + save() is a race; "update if it exists" with Hibernate merge() is the same race; a cache in application memory alone is useless with several instances.

Trade-offs: the key table grows, so it needs cleanup with a TTL (say, 24-72 hours). If you call an external system (a payment provider), that call has to be idempotent too, so I pass the same key on to the provider. Kafka consumers use the same approach: a "processed_event" table keyed by event id.