SteelReed

Search

Search posts, questions…

7. System Design

Idempotency part 1: at-least-once, unique constraints and an Idempotency-Key on PostgreSQL

Why every distributed system is at-least-once, three ways to make an operation idempotent, an Idempotency-Key implementation tested with 20 concurrent requests on PostgreSQL, a case study of duplicate bookings caused by a non-unique request_id, and why a distributed lock is no substitute for idempotency.

18 Nov 20269 min readSenior

–

1. The problem

POST /bookings stores request_id, but the column has no UNIQUE. Attempt 1 commits and the response is lost; the retry runs the whole flow again, sees the nights already BOOKED, and says "someone else booked this room". The customer books elsewhere: two real bookings, charged twice.

2. Key idea

Senders must retry, so only the receiver can give you exactly-once by deduplicating. People say "exactly-once processing", not "exactly-once delivery". Reverse proxies can also retry on the client's behalf (Nginx proxy_next_upstream with non_idempotent).

Approach Use when Don't use when
Conditional update (WHERE status = 'PENDING') state transitions creating rows, incrementing
Unique constraint, upsert on a business key creating rows with a client-issued or natural key there's no stable key
Dedup table in the same transaction the general case, storing responses for replay a different transaction from the business change
Distributed lock reducing contention as a substitute for idempotency

balance = balance + 100000 adds again on rerun; status = 'PAID' WHERE status = 'PENDING_PAYMENT' reruns with 0 rows. The affected row count tells you whether it's the first time.

2.1 How does an Idempotency-Key work?

A table idempotency_record(client_id, idem_key, request_hash, status, http_status, response_body, expires_at) with primary key (client_id, idem_key).

  • Claimed (1 row inserted): run the business logic, store the response, COMPLETED, commit.
  • Key exists, same body hash: return the stored response.
  • Key exists, different hash: 422, the client misused the key.

PostgreSQL makes a second INSERT wait while an uncommitted transaction holds the unique key, so 20 concurrent requests with the same key create one transaction, no extra lock needed. With an external call (a payment gateway) you can't hold the transaction open: use two phases IN_PROGRESS → COMPLETED, duplicates get 409, and pass the same key down to the external system.

3. In Java

Claim first, before locking any resource, in the same transaction.

JAVA
@Transactional
public BookingResponse book(long userId, BookingRequest req) {
    Long newId = jdbc.query("""
        INSERT INTO booking (user_id, request_id, homestay_id, checkin, checkout)
        VALUES (?, ?, ?, ?, ?)
        ON CONFLICT (user_id, request_id) DO NOTHING
        RETURNING id""",
        rs -> rs.next() ? rs.getLong(1) : null,
        userId, req.requestId(), req.homestayId(), req.checkin(), req.checkout());
    if (newId == null) {                                   // retry: return the first result
        return bookings.findByUserAndRequest(userId, req.requestId()).toResponse();
    }
    availability.lockAndBook(req.homestayId(), req.checkin(), req.checkout(), newId);
    return bookings.findById(newId).toResponse();          // 201, the same booking_id on every retry
}
// Needs: ALTER TABLE booking ADD CONSTRAINT booking_user_request_uq UNIQUE (user_id, request_id);

If nothing is available, lockAndBook throws and the whole transaction rolls back, including the claim. In MySQL use ON DUPLICATE KEY UPDATE id = id, not INSERT IGNORE (which also swallows truncation, type and foreign key errors).

Why a Redis lock can't replace idempotency

A lock like SET key 1 NX PX ttl then DEL:

Gap Consequence
The retry arrives after the lock is released a second charge
The TTL expires while the first run is still going (GC pause, slow DB) two concurrent runs
DEL doesn't compare a token, the value is a constant "1" deleting another client's lock

A durable record (a unique constraint, a dedup table) is idempotency; a lock only reduces contention. If you still need a lock, use a random token and compare-then-delete in Lua; for shared resources add a fencing token or lock in the DB.

The same booking code also sends an email and a Kafka event inside the transaction: if the commit fails, the "success" email is already out. Fix it with a transactional outbox, and downstream consumers must be idempotent.

4. Working with AI

Hand to AI: the migration adding UNIQUE, an Idempotency-Key handler, a test with 20 threads on the same key via CountDownLatch on Testcontainers.

Check in AI-written code:

  • Every request_id or idem_key column has a UNIQUE constraint in the DB.
  • No existsByRequestId then save: claim with INSERT ... ON CONFLICT.
  • The claim is in the same transaction as the business change, before locking resources.
  • A retry returns the result as if the first attempt succeeded, not an error.
  • A distributed lock is not the only duplicate protection.

5. Exercises

Exercise 1: Design a top-up webhook

The bank calls POST /topups whenever money arrives, may call several times, sometimes twice almost simultaneously. Design the table and handler so the wallet is credited once.

Solution to Exercise 1

Table topup(bank_txn_id text PRIMARY KEY, wallet_id, amount, received_at): the bank's transaction id is the natural key.

In one transaction: INSERT INTO topup ... ON CONFLICT (bank_txn_id) DO NOTHING RETURNING bank_txn_id. If a row comes back, UPDATE wallet SET balance = balance + :amount WHERE id = :wallet; if not, it's already processed, return 200. Two simultaneous requests: the second waits on the unique index and then gets "0 rows". Verify the webhook signature before anything else.

Exercise 2: Review "dedup with Redis"

The AI wrote if (redis.setIfAbsent("pay:" + key, "1", Duration.ofSeconds(30))) { charge(); } else { return 409; }, calling it "duplicate-proof". Find two gaps, show how to prove them, fix it.

Solution to Exercise 2
  1. The TTL expires while charge() is still running (a 40 s slow gateway): the retry gets the lock and charges twice. Proof: a fake charge() sleeping 35 s, a retry at second 31.
  2. A retry after 30 s once the first run finished: the Redis key has expired and everything runs again. No durable record says "already charged".

Fix: an idempotency_record table in the DB keyed by (client_id, idem_key), two phases IN_PROGRESS → COMPLETED because of the gateway call; pass the same key to the gateway. Keep Redis as an early filter if you like.

Summary

  • Retries are mandatory; only exactly-once processing exists.
  • Conditional update, unique constraint or dedup table: dedup in the same transaction.
  • Idempotency-Key: claim, replay, 422; duplicates wait on the unique index.
  • request_id without UNIQUE prevents nothing.
  • Locks stop concurrent runs, not repeated ones.

Read more: Part 2: Kafka and payment-gateway IPNs.

Practice interview questions on this topic

All Microservices questions →

Loading comments…