Skip to content
API Idempotency Deep Dive: 8 Patterns, 4-Layer Defense & Production Code

API Idempotency Deep Dive: 8 Patterns, 4-Layer Defense & Production Code

A comprehensive guide to API idempotency covering concept clarification, six sources of duplicate requests, a golden formula (unique key + deduplication storage + atomic operation), four-layer defense architecture, eight implementation patterns with code examples, common pitfalls with solutions, and interview preparation questions.

Rain's Path to Java Mastery
Rain's Path to Java Mastery
Rain's Path to Java Mastery

Clarify What Idempotency Really Means

Standard definition: Same request executed once or N times produces identical side effects . Mathematical expression: f(f(x)) = f(x).

Key distinctions:

Idempotency ≠ Deduplication ≠ Concurrency Control

Deduplication filters duplicate requests ("don't execute")

Idempotency ensures repeated execution yields same side effects ("prevent duplicate charges/orders")

Concurrency control prevents race conditions ("prevent overselling")

Distributed locks ≠ idempotency; locks only block simultaneous requests, not retries after seconds

REST perspective: GET, PUT, DELETE are naturally idempotent; POST is not. Most write operations (create order, pay) use POST — idempotency design patches non-idempotent POST business.

Interface type handling:

Query: Naturally idempotent, no handling needed

Delete: Easy to make idempotent — delete non-existent resource returns success

Create: High-risk area — unique business ID + unique index

Update: High-risk area — state machine / optimistic lock

Six Sources of Duplicate Requests

User double-click (frontend controllable, most basic)

Network timeout retry (client, gateway, Nginx auto-retry; request may have succeeded server-side)

MQ duplicate consumption (consumption failure retry, partition rebalance; "at-least-once" semantics)

RPC framework retry (Dubbo, Feign retry policies; middleware-level resend)

Scheduled task duplicate trigger (multi-node batch competition)

Page back navigation (browser back then resubmit form)

Iron law: As long as "network retry" or "at-least-once delivery" exists, business layer must implement idempotency. Don't expect callers to send only once.

Frontend deduplication is only UX optimization; idempotency must be done server-side.

Golden Formula & Four-Layer Defense

Golden Formula

Idempotency = Unique Identifier + Deduplication Storage + Atomic Operation

Unique Identifier: How to judge "same request"? Business order number or client-generated requestId Deduplication Storage: Record "processed" in Redis, MySQL, or status field

Atomic Operation: Check + write must be single atomic step; otherwise concurrent requests both see "not processed" and both write

Four-Layer Defense (Progressively Stronger)

Frontend layer: Blocks 80% low-level duplicates, solves UX only

Gateway/Framework layer: Generic interception, zero business intrusion

Business layer: State machine, CAS for business-semantic safety net

Data layer: Unique index is final defense, solves 100% correctness

Principle: Any write interface — ask: does this table have a unique constraint to block duplicates? If not, the interface is unsafe.

Idempotency Key Design

Key must be business unique identifier — same business intent, same key regardless of retries.

Sources:

Frontend-generated: via Idempotency-Key header

Business-generated: order number, payment serial, business order number (most reliable)

Gateway-generated: global requestId from X-Request-Id header, full-chain propagation

Recommended keys: bizType + requestId, orderNo + operationType, external payment serial externalTradeNo.

Not recommended: userId + timestamp (drifts, mismatch on retry), fresh UUID per attempt (changes each retry, cannot deduplicate), MQ messageId (may change on redelivery).

String idemKey = "pay:callback:" + externalTradeNo;

Key design principle: bizDomain:operation:businessUniqueId(+paramFingerprint), e.g., idem:pay:ORDER_20261008_001. Too coarse misblocks different requests; too fine fails to catch duplicates.

Callers must be forced to carry same idempotency key on retry, ideally generated by caller and propagated through entire call chain to your unique index.

Solution Selection: Comparison & Decision Flow

Eight Mainstream Solutions Compared

Database Unique Index — Core: unique constraint blocks duplicate insert. Scenarios: insert-type (order creation, payment flow, consumption safety net). Pros: simple, strong consistency, final safety net. Cons: only prevents insert not update; conflict semantics must be distinguished.

Token Mechanism — Core: pre-issue token, atomic verify-and-delete on submit. Scenarios: frontend forms, order pages. Pros: intercepts before business execution, high interception rate. Cons: requires frontend cooperation, extra round-trip.

State Machine — Core: only allow legal state transitions, CAS update. Scenarios: orders, approvals, payment callbacks. Pros: business-aligned, naturally idempotent, zero extra components. Cons: only for businesses with state transitions.

Optimistic Lock (version) — Core: WHERE version = ? conditional update. Scenarios: inventory, balance updates. Pros: no lock blocking, good performance. Cons: only for update-type; failure needs retry strategy.

Pessimistic Lock — Core: SELECT ... FOR UPDATE row lock. Scenarios: strong consistency, low concurrency. Pros: strong consistency guarantee. Cons: poor performance, deadlock risk.

Distributed Lock — Core: Redis/Redisson serialize. Scenarios: multi-step complex business orchestration. Pros: high generality. Cons: lock expiry, accidental deletion risk; only prevents concurrency, not idempotency .

Idempotency Table — Core: dedicated dedup table + unique index + status + result snapshot. Scenarios: generic scenarios, financial core paths. Pros: zero business table intrusion, result replay. Cons: extra table, needs periodic cleanup.

MQ Deduplication Table — Core: consumer deduplicates by message business unique key. Scenarios: MQ consumption. Pros: simple, effective. Cons: must be in same transaction as business.

Selection Mnemonic

Insert uses unique index, update uses optimistic lock, flow uses state machine, generic uses idempotency table + Redis annotation, frontend adds Token/button disable as safety net.

Real Project Combo Example — Payment Callback Triple Insurance

DB unique constraint on out_trade_no as final safety net

Redis distributed lock on out_trade_no at business entry to prevent concurrent callbacks

State machine constraint on order status update: only WAIT_PAY → PAID allowed

Core Code Implementations

Database Unique Index: Hardest Safety Net

CREATE TABLE `t_order` (  `id` BIGINT NOT NULL AUTO_INCREMENT,  `order_no` VARCHAR(64) NOT NULL COMMENT 'business order number',  `user_id` BIGINT NOT NULL,  `amount` DECIMAL(10,2) NOT NULL,  `status` TINYINT NOT NULL DEFAULT 0 COMMENT '0 pending 1 paid 2 cancelled',  `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,  PRIMARY KEY (`id`),  UNIQUE KEY `uk_order_no` (`order_no`)  -- idempotency final defense) ENGINE=InnoDB;
public Order createOrder(CreateOrderCmd cmd) {  try {    Order order = buildOrder(cmd);    orderMapper.insert(order);    // unique index safety net    return order;  } catch (DuplicateKeyException e) {    // Not error, but "duplicate request, return existing order"    return orderMapper.selectByOrderNo(cmd.getOrderNo());  }}
Interview favorite: Why not select then insert ? Because check-then-act is unsafe under concurrency — two threads both see "not exist" then both insert. Correct approach: optimistic insert — insert directly, query on conflict . Unique index pushes "judgment" into DB atomic operation.

Detail: DuplicateKeyException ≠ always idempotent scenario. Must distinguish "duplicate request" from "real business conflict" (e.g., two people grabbing same order number). Combine business semantics, don't blindly swallow exception.

Token Anti-Duplicate: Classic Frontend-Backend Cooperation

Wrong naive implementation:

// Wrong: two steps not atomic, both requests pass check under concurrencyif (redisTemplate.hasKey(tokenKey)) {  redisTemplate.delete(tokenKey);  // execute business...}

Correct: Lua script merges "verify + delete" into one atomic operation:

@Servicepublic class TokenService {  // Lua: verify value matches then delete, Redis single-threaded = naturally atomic  private static final DefaultRedisScript<Long> CHECK_AND_DEL =    new DefaultRedisScript<>(      "if redis.call('GET', KEYS[1]) == ARGV[1] then " +      "return redis.call('DEL', KEYS[1]) else return 0 end", Long.class);  @Resource  private StringRedisTemplate redisTemplate;  /** Apply Token: SET with expiry in one command, avoids non-atomic SET then EXPIRE */  public String createToken() {    String token = UUID.randomUUID().toString();    redisTemplate.opsForValue().set("idem:token:" + token, token, 5, TimeUnit.MINUTES);    return token;  }  /** Verify and delete Token, only proceed if true */  public boolean checkToken(String token) {    Long r = redisTemplate.execute(CHECK_AND_DEL, List.of("idem:token:" + token), token);    return r != null && r > 0;  }}
Technical highlights: GET + DEL via Lua script eliminates classic pitfall of "two concurrent requests both pass verification". Similarly, issuing Token must use SET with expiry in one command; if SET then EXPIRE separately, crash leaves zombie Token that never expires.

Why Redis not DB? High-frequency verification, auto TTL, performance; true consistency guaranteed by DB unique index.

State Machine CAS: Soul of Orders & Payment Callbacks

Stateful businesses: state machine is most elegant idempotency. Order status flows one-way only.

Rule: Only allow "untraversed" edges to be traversed again; repeated traversal of same edge ignored.

Core SQL merges "judge status" and "update status" into single atomic statement:

UPDATE t_orderSET status = 'PAID', update_time = NOW()WHERE order_no = #{orderNo}AND status = 'WAIT_PAY';  -- CAS with expected status

Payment callback is idempotency hotspot — third party may push N times. Complete implementation:

@Transactional(rollbackFor = Exception.class)public void payCallback(PayNotify notify) {  // 1. Unique index safety net: pay_no unique, duplicate callback hits key conflict  payRecordMapper.insertIgnore(PayRecord.of(notify));  // 2. CAS update, affected rows = 0 means already processed or illegal state  int rows = orderMapper.casToPaid(notify.getOrderNo(), notify.getPayNo());  if (rows == 0) {    log.warn("Order already paid or abnormal state, ignore callback: {}", notify.getOrderNo());    return;  }  // 3. Derived actions (coupons/points/notify) via reliable MQ delivery  eventPublisher.publish(new OrderPaidEvent(notify.getOrderNo()));}
Why not SELECT judge then UPDATE ? Time window between: two callback threads both see WAIT_PAY , each executes update, causing points/inventory deducted twice. CAS pushes judgment into DB row lock, naturally atomic. Payment platform callbacks 10 times, only processed once.

Optimistic Lock: Inventory & Balance Update Posture

// With version anti-ABA, with num >= delta anti-oversell@Update("UPDATE t_stock SET num = num - #{delta}, version = version + 1 " +  "WHERE sku_id = #{skuId} AND num >= #{delta} AND version = #{version}")int deductStock(@Param("skuId") Long skuId, @Param("delta") int delta,  @Param("version") int version);

Return affected rows 0 means either insufficient stock or concurrent grab, upper layer retries or returns "out of stock", never oversell .

Advanced detail: rows == 0 has two meanings, must distinguish:

if (rows == 0) {  Order latest = orderMapper.selectByOrderId(orderId);  if ("PAID".equals(latest.getStatus())) {    return;  // Already paid: idempotent, return success  }  throw new BizException("Concurrent conflict, please retry");  // Version conflict: retryable}
WHERE

condition: status for business idempotency, version for concurrency control — one DB interaction solves both.

Distributed Lock: Protect Complex Business Blocks

RLock lock = redissonClient.getLock("lock:pay:" + orderNo);try {  if (!lock.tryLock(0, 10, TimeUnit.SECONDS)) {    return Result.error("Request processing, please retry later");  }  // Execute business logic} finally {  if (lock.isHeldByCurrentThread()) {    lock.unlock();  }}

Redisson benefits: Watchdog auto-renewal (renews every 1/3 expiry after success, lock won't expire mid-business); release validates holder identity, avoids deleting others' locks.

But remember: Lock only solves "simultaneous", idempotency solves "repeated". After lock release, retry seconds later still repeats execution, so lock must combine with unique index, state machine — it cannot bear idempotency alone.

Idempotency Table: Result Safety Net, Replay First Result on Duplicate

Core paths (finance, payment, marketing rewards) — add idempotency record table storing status and result:

CREATE TABLE t_idempotent (  id BIGINT AUTO_INCREMENT PRIMARY KEY,  biz_type VARCHAR(64) NOT NULL COMMENT 'business type',  idempotent_key VARCHAR(128) NOT NULL COMMENT 'idempotency key',  status VARCHAR(16) NOT NULL COMMENT 'PROCESSING / SUCCESS / FAIL',  response TEXT COMMENT 'business result snapshot',  create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,  update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,  UNIQUE KEY uk_biz_key (biz_type, idempotent_key),  KEY idx_create_time (create_time)  -- for scheduled cleanup) COMMENT 'idempotency record table';

Processing flow:

public Object executeWithIdempotent(String bizType, String key, Supplier<Object> biz) {  IdempotentDO record = new IdempotentDO(bizType, key, "PROCESSING");  try {    idempotentMapper.insert(record);  // atomic placeholder, unique index guarantees  } catch (DuplicateKeyException e) {    IdempotentDO old = idempotentMapper.selectByKey(bizType, key);    if (old.isSuccess()) {      return JSON.parse(old.getResponse());  // replay historical result    }    if (old.isProcessing()) {      throw new BizException("Request processing, do not resubmit");    }    throw new BizException("Last request failed, please retry later");  }  try {    Object result = biz.get();    idempotentMapper.markSuccess(bizType, key, JSON.toJSONString(result));    return result;  } catch (Throwable e) {    idempotentMapper.markFail(bizType, key);    throw e;  }}
Technical highlight: Redis handles fast interception, idempotency table handles result persistence. True idempotency isn't just "don't re-execute" — it's duplicate requests also return first result — first order succeeds, duplicate shouldn't error but return that same order. This is complete semantics of f(f(x)) = f(x) : even return values must match.

Highlight: @Idempotent Annotation + AOP Generic Component

Encapsulate "unique ID + Redis dedup + Lua atomic + result replay" into one annotation, business integrates in one line — best resume highlight.

Annotation definition:

@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface Idempotent {  /** Idempotency key, supports SpEL, e.g. "#req.orderNo" */  String key() default "";  /** Business prefix */  String prefix() default "idem";  /** Deduplication window (seconds) */  int expire() default 30;  /** Duplicate request message */  String message() default "Do not resubmit";  /** Whether to replay first result on duplicate */  boolean replay() default true;}

Aspect implementation, note Lua script three-state return:

@Aspect@Component@RequiredArgsConstructorpublic class IdempotentAspect {  private final StringRedisTemplate redis;  /**   KEYS[1]=idempotency key  ARGV[1]=param fingerprint  ARGV[2]=expiry (seconds)   Returns: 1=first request proceed | 2=duplicate | 0=same key different params */  private static final DefaultRedisScript<Long> SCRIPT =    new DefaultRedisScript<>(      "if redis.call('SET', KEYS[1], ARGV[1], 'NX', 'EX', ARGV[2]) then return 1 " +      "elseif redis.call('GET', KEYS[1]) == ARGV[1] then return 2 " +      "else return 0 end", Long.class);  @Around("@annotation(idem)")  public Object around(ProceedingJoinPoint pjp, Idempotent idem) throws Throwable {    // 1. SpEL parse business idempotency key, append user + method dimension to prevent cross-user interference    String bizKey = SpELUtil.parse(idem.key(), pjp);    String redisKey = idem.prefix() + ":" + userId() + ":"      + pjp.getSignature().toShortString() + ":" + bizKey;    // 2. Param fingerprint: same orderNo changed amount = different request    String fingerprint = DigestUtils.md5DigestAsHex(JSON.toJSONBytes(pjp.getArgs()));    Long r = redis.execute(SCRIPT, List.of(redisKey), fingerprint, String.valueOf(idem.expire()));    if (r == null || r == 0) {      throw new BizException("Same idempotency key with different params, check request");    }    if (r == 2) {      // Duplicate: replay first result, not simple error      return idem.replay() ? replayResult(redisKey) : Result.fail(idem.message());    }    try {      Object result = pjp.proceed();      cacheResult(redisKey, result, idem.expire());  // result snapshot for replay      return result;    } catch (Throwable e) {      // 3. Only "explicit failure and retryable" exceptions release placeholder      if (isRetryableException(e)) {        redis.delete(redisKey);      }      throw e;    }  }  private boolean isRetryableException(Throwable e) {    // Param validation, normal biz exceptions retryable; network timeout, unknown result exceptions must not release lightly    return e instanceof BizException;  }}

Business usage, one annotation:

@Idempotent(prefix = "order:create", key = "#req.orderNo", expire = 600,  message = "Order processing, please wait")public Order createOrder(CreateOrderRequest req) {  return orderService.create(req);}

Four highlights:

SET key value NX EX single command placeholder , eliminates deadlock from crash between SETNX and EXPIRE Param fingerprint prevents "fake idempotency" : same orderNo changed amount → exception, not silently treated as duplicate

Result snapshot replay : duplicate returns first success result — correct idempotency semantics

Business failure deletes placeholder key : allows genuinely failed requests to be retried, not permanently blocked — common blind spot

MQ Consumption Idempotency: Lifesaver for At-Least-Once Delivery

MQ "at-least-once" semantics mandates consumer-side idempotency. Dedup table + same transaction is most stable:

CREATE TABLE mq_consume_log (  msg_id VARCHAR(64) NOT NULL COMMENT 'message business unique key',  biz_key VARCHAR(64) NOT NULL COMMENT 'business primary key',  gmt_create DATETIME NOT NULL,  PRIMARY KEY (msg_id)) ENGINE=InnoDB;
@Transactional(rollbackFor = Exception.class)public void onMessage(Message msg) {  try {    consumeLogMapper.insert(msg.getBizKey());  // same DB, same transaction as business  } catch (DuplicateKeyException e) {    log.warn("Duplicate message, already consumed: {}", msg.getBizKey());    return;  // direct ACK, achieves idempotency  }  doBiz(msg);}
Critical: Dedup record must be in same local transaction as business. Otherwise insert succeeds, business fails rollback, message redelivered → misjudged as "already consumed", data lost.

RabbitMQ manual ACK template:

@RabbitListener(queues = "order.pay.queue")public void onMessage(PayMessage msg, Channel channel,  @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws IOException {  // Idempotency key = business unique ID, don't rely on MQ messageId (may change on redelivery)  String bizNo = msg.getOrderNo() + ":" + msg.getPayType();  if (!tryInsertDedup(bizNo)) {    channel.basicAck(tag, false);  // duplicate, direct ACK    return;  }  try {    payService.handlePaySuccess(msg);    channel.basicAck(tag, false);  } catch (Exception e) {    channel.basicNack(tag, false, !isFatal(e));  // only retryable goes back to queue  }}

Technical Pitfalls & Troubleshooting Guide

Concurrency & Atomicity

Check-then-act race : Two requests both see "not exist", both write → Push judgment into atomic op: unique index / SET NX / conditional update

Token check-then-delete non-atomic : Two requests both GET succeed, both proceed → Lua script merges GET + DEL SETNX then EXPIRE non-atomic : Crash in between leaves permanent lock → SET key val NX EX single command, or Lua

Accidental lock deletion : A deletes B's lock → Store UUID in value, Lua verify on delete

Multi-instance local dedup fails : JVM memory, local cache not shared across instances → Unified Redis/DB global storage

Expiry & Release

Lock expires before business finishes : Placeholder invalid, duplicate enters → Reasonable TTL estimate; Redisson watchdog auto-renewal

Business fails but placeholder not released : User retry permanently blocked → Delete key on exception, or idempotency table mark FAIL Release not unconditional : Timeout result unknown, release may cause re-execution → Only "explicit failure and retryable" releases; payment/deduction unknown result — don't release, rely on CAS + unique index for retry safety

Delete placeholder before or after? : Before: failure can't retry; After: concurrent duplicates enter → Placeholder before business, compensatory delete on failure, final consistency via unique index

Idempotency key expires : Out-of-window duplicates penetrate to DB → TTL ≥ max retry window (gateway retry + MQ redelivery total); DB unique index safety net

Storage & Performance

Redis down : Interception completely lost → DB unique index safety net; Sentinel/cluster for HA

Idempotency table bloats : History data unlimited growth → TTL + scheduled archive (7-30 days) + cold-hot separation, sharding

Unique index hotspot : High concurrency conflicts, DB CPU spikes → Front Redis verification; INSERT ... ON DUPLICATE KEY UPDATE Sharding breaks unique constraint : Uniqueness only within single shard → Idempotency key must contain shard key; global ID generator; route by shard key to fixed shard

Extreme high concurrency performance : Unique index becomes write bottleneck → Unique key suffix sharding to scatter hotspot; Bloom filter pre-filter; non-financial can degrade to Redis dedup (eventual consistency)

Chain & Semantics

Duplicate request returns inconsistent : First success but response timeout, retry gets "duplicate" error → Result snapshot: cache first result, duplicate replays

MQ at-least-once : Message consumed repeatedly → Business unique key dedup table + same transaction; state machine safety net

Upstream/downstream idempotency key mismatch : Caller retries with different key, dedup useless → Enforce Idempotency-Key in protocol; gateway rejects without key; full-chain propagate same transaction ID

Cross-system/cross-DB idempotency : Local transaction can't control external systems → Local message table / transactional messages + downstream idempotency, eventual consistency

Batch partial success : Batch request can't be atomic idempotent → Decompose to single-record granularity dedup, record each status, support partial failure retry

Unique key conflict ≠ always idempotent : Two people grab same orderNo = business conflict, not duplicate request → Combine business semantics, don't blindly swallow exception

Non-idempotent SQL : num = num - 1 repeated execution different result → Rewrite to absolute value SET balance = #{newValue}; or flow table + unique index on account_id + biz_no, accumulation becomes "insert flow + aggregate", naturally dedupable

Async processing user retries : Request returned but processing slow, user clicks again → Persist to DB return "processing", frontend polls / callback for final state

Four High-Frequency Deep Dives

Deep Dive 1: Duplicate Request Must Return Same Result (True Idempotency)

Scenario: Frontend submits order → backend succeeds writes DB → network timeout frontend no response → user retries → backend returns "duplicate" → frontend shows "order failed" but order actually created.

Solution: Cache first result, replay on retry:

public Result createOrder(String requestId, OrderDTO dto) {  // 1. Check existing result  String cacheKey = "result:" + requestId;  String cached = redisTemplate.opsForValue().get(cacheKey);  if (cached != null) {    return JSON.parseObject(cached, Result.class);  // return identical result  }  // 2. Idempotent placeholder, execute business  Order order = orderService.create(dto);  Result result = Result.success(order);  // 3. Cache result, expiry covers max retry window  redisTemplate.opsForValue().set(cacheKey, JSON.toJSONString(result), 1, TimeUnit.HOURS);  return result;}

Deep Dive 2: Failure Release Placeholder, Mind Transaction Boundary

"Delete key on business exception" sounds fine, but if aspect outside transaction: transaction committed, partial data persisted, then exception deletes key → retry re-executes on existing data. Two countermeasures: 1) Use TransactionSynchronization to decide release after transaction commits ; 2) Accept "release may cause retry", rely on unique index and state machine to guarantee retry safety — why DB safety net cannot be omitted.

Deep Dive 3: Global Unique ID Clock Drift

Idempotency keys often rely on Snowflake, which depends on machine clock. Three clock drift strategies: small drift throw exception wait for clock catch-up; use historical max timestamp continue issuing; switch to Meituan Leaf segment mode, fetch segments from DB, zero time dependency.

Deep Dive 4: Non-Idempotent SQL Refactoring

UPDATE t_account SET balance = balance + 10

inherently non-idempotent, executes twice = adds twice. Two refactor paths: absolute value SET balance = #{newValue}; or introduce flow table, each change inserts record with unique index on account_id + biz_no, accumulation becomes "insert flow + aggregate", naturally dedupable.

Interview Follow-up Cheatsheet

Idempotency key expired? TTL ≥ max retry window; core business doesn't rely on Redis, unique index final safety net

Redis down = idempotency lost? Redis is "performance layer", unique index is "correctness layer", separate responsibilities

MQ consumption idempotency? Business unique ID as key + dedup table same transaction; or state machine judge if processed

High concurrency Redis bottleneck? SET NX single command + sharding; core paths still DB unique constraint safety net

Why Token in Redis not DB? High-frequency verify, auto TTL, high performance; consistency by DB unique index

Check-then-insert for idempotency? No, check-then-act has race; correct is optimistic insert, conflict then query

Snowflake clock drift? Throw exception wait / historical max timestamp / switch Leaf segment mode

Measure idempotency effectiveness? Monitor: duplicate interception rate, duplicate charge incidents (must be 0), dedup table hit rate

Summary: One Lock, Two Unique, Three State, Four Result

Idempotency isn't a single component's job, but "frontend anti-mistake → gateway intercept → business CAS → DB unique constraint" four-layer defense. First three layers solve 99% performance and UX; last layer unique index solves 100% correctness.

Landing four-piece set:

Entry dedup with Redis Token / SETNX Storage safety net with unique index

Business safety net with state machine CAS

Result safety net with idempotency table storing snapshots

No silver bullet — select and combine per business.

30-second mnemonic:

Form double-click, token apply firstAPI generic, fingerprint + SETNXSafety net unique, conflict = successState uses CAS, don't check-then-updateMessage must dedup, same transaction landLock only prevents concurrency, idempotency separate account

Landing priority suggestions:

Audit existing write interfaces : All tables creating data — check unique constraints, add missing immediately

Core paths add idempotency table : Finance, payment, marketing rewards — result snapshot + three states, none missing

Encapsulate team-unified @Idempotent component : Standardize, prevent everyone writing own

Add monitoring : Interception rate, incident count, dedup hit rate — idempotency not done at launch, must be measurable

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

distributed-systemsbackend-architecturedatabaseredispayment-systemsconcurrency-controlidempotencyinterview-preparation
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.