Java Interview Questions

Idempotency Design: Tokens, Unique Keys, State Machines

How do you make a "create order" API idempotent under network retries?

Why Interviewers Ask This

Retries are a fact of life (mobile networks, webhook replays). Seniors are expected to design for idempotency, not hope clients "just retry carefully".

How to Answer

  1. 1

    Pattern 1: client sends an idempotency key (UUID) in header. Server stores (key → result). Same key returns cached result.

  2. 2

    Pattern 2: DB unique constraint on business key (e.g. out_trade_no). Duplicate insert throws, catch and treat as success.

  3. 3

    Pattern 3: state-machine guard — UPDATE … WHERE status = 'PENDING' — only the first update flips state, later ones affect 0 rows.

  4. 4

    Pattern 4: Redis SETNX with TTL as a lightweight lock — first request wins, later retries see the token.

  5. 5

    Pattern 5: pessimistic lock (SELECT … FOR UPDATE) on the aggregate. Simple but kills throughput under contention.

Sample Answer

For 'create order' I'd combine two patterns: client includes an Idempotency-Key header (UUID the SDK generates), and the orders table has a unique constraint on that key. Server does INSERT … ON CONFLICT DO NOTHING RETURNING *. If rows=1, new order; if rows=0, we SELECT and return the existing order — both paths deterministic. Idempotency-Key rows auto-expire after 24h via a background job. For downstream effects (charge card, reserve inventory), I layer a state machine on the order — transitions are WHERE status = 'PREV' so a duplicate event can't double-charge. Belt-and-suspenders, but every part of the chain has its own retry behavior and I want the system to survive all of them misbehaving at once.

Pro Tips

  • Never trust "client says don't retry" — proxies, load balancers, and users all retry anyway.

  • Make idempotency keys scoped per user — cross-user collision is a security hole.

  • HireMe AI (即答侠) stacks these patterns from cheap to expensive so you answer cost-aware, not just correctness-aware.

Frequently Asked Questions

GET is naturally idempotent right?

By spec yes, but in practice caches, analytics side-effects, and read-after-write caching can make a GET non-idempotent. Design as if nothing is free.

Idempotent vs exactly-once?

Idempotent means safe to retry; exactly-once means the effect happens exactly one time. The second is a stronger guarantee and usually involves dedup windows + idempotency together.

Worried About Going Blank in Your Interview?

HireMe AI listens to your interview in real-time, detects questions, and generates instant answer suggestions — so you never freeze up again.

Try HireMe AI Free