Skip to content
Prevent Duplicate Orders: 4-Layer Idempotency Defense with Redis Tokens, DB Constraints & AOP

Prevent Duplicate Orders: 4-Layer Idempotency Defense with Redis Tokens, DB Constraints & AOP

This article details a comprehensive four-layer strategy to prevent duplicate order submissions, covering frontend interception, distributed token mechanisms with Redis atomic operations, database unique constraints as ultimate fallback, scheduled reconciliation, and a reusable AOP-based annotation for zero-intrusion idempotency in Spring Boot applications.

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

Core Problem: Interface Idempotency

Duplicate order submission is fundamentally an interface idempotency issue: executing the same request multiple times must produce the same result as a single execution. Common triggers include user double-clicks, network retries, browser refresh/back, RPC framework retries, and message queue redelivery.

First Line of Defense: Frontend Prevention (Lowest Cost, Blocks 80% Mistakes)

Frontend measures reduce backend load but cannot stop malicious direct API calls.

Button disable + loading : Gray out button immediately, show spinner, restore on response. Effectiveness: ★★★★☆. Applies to all form submissions.

Submit debounce : Only execute last submission within 300ms. Effectiveness: ★★★☆☆. Suits rapid clicks.

Page redirect : Redirect to result page on success, disable browser back. Effectiveness: ★★★☆☆. Prevents refresh/back resubmission.

History replacement : Use history.replaceState() to replace current history entry. Effectiveness: ★★☆☆☆. Auxiliary back-button prevention.

Warning : Frontend only stops honest users; backend idempotency is mandatory.

Core Defense: Backend Idempotency (Must Implement, 100% Interception)

1. Distributed Token Mechanism (⭐⭐⭐⭐⭐ Primary Choice)

Most robust, widely used in large-scale distributed systems.

Distributed token flow diagram
Distributed token flow diagram

Key implementation rules:

Use Redis

DEL</command> return value for atomic check-and-delete; never <code>GET

then decide.

Bind token to user ID to prevent token leakage abuse.

Set reasonable TTL (typically 60 seconds) to avoid Redis memory leaks.

2. Database Unique Constraint (⭐⭐⭐⭐ Ultimate Fallback)

Leverages DB unique indexes to physically prevent duplicate rows.

-- Business unique index: same user cannot buy same goods more than once per minute
CREATE UNIQUE INDEX uk_order_user_goods_time ON t_order (user_id, goods_id, FLOOR(UNIX_TIMESTAMP(create_time)/60));

-- Or global unique order number index
CREATE UNIQUE INDEX uk_order_no ON t_order (order_no);

Key points:

Catch DuplicateKeyException and return friendly message.

Choose index columns carefully to avoid over- or under-constraining.

This is the last line of defense and must never be omitted.

3. Distributed Lock (⭐⭐⭐ High-Concurrency Scenarios)

Suitable for concurrent operations on same resource (e.g., flash sales, purchase limits). Example using Redisson:

RLock lock = redissonClient.getLock("order:lock:" + userId);
try {
    if (lock.tryLock(3, 10, TimeUnit.SECONDS)) {
        createOrder();
    } else {
        return Result.fail("Operation too frequent, try later");
    }
} finally {
    if (lock.isHeldByCurrentThread()) lock.unlock();
}

4. State Machine Control (⭐⭐⭐ Complex Business Flows)

Controls operation legality via order state transitions, preventing state rollback.

Order state machine diagram
Order state machine diagram

Ultimate Safety Net: Reconciliation & Compensation

Scheduled reconciliation : Daily job compares order table with payment ledger; auto-refund duplicates.

Payment callback idempotency : Callback endpoint must handle duplicate notifications to avoid multiple shipments.

Manual review : Abnormal orders (same user, multiple identical orders in short time) enter human review queue.

Solution Selection Summary

The author recommends a four-layer stack: Frontend prevention + Distributed Token + Database Unique Constraint + Scheduled Reconciliation .

Priority matrix (simplified from article tables):

Always use : Database unique constraint (low complexity, extreme reliability, all scenarios), Distributed Token (medium complexity, extreme reliability, general order submission), Scheduled reconciliation (medium complexity, extreme reliability, final data verification).

Scenario-specific : Distributed lock (high complexity, high reliability, flash sales/limited purchases), State machine (high complexity, medium reliability, complex order workflows).

Auxiliary : Frontend button disable (trivial complexity, low reliability, blocks honest user mistakes).

Reusable AOP Annotation: @PreventDuplicateSubmit

Zero-intrusion design: annotate any endpoint to enable deduplication.

1. Annotation Definition

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PreventDuplicateSubmit {
    int expireTime() default 60;
    String keyPrefix() default "order:submit:";
    boolean bindUser() default true;
}

2. AOP Aspect Implementation

@Aspect
@Component
@RequiredArgsConstructor
public class PreventDuplicateSubmitAspect {
    private final StringRedisTemplate stringRedisTemplate;
    private final HttpServletRequest request;

    @Around("@annotation(preventDuplicateSubmit)")
    public Object around(ProceedingJoinPoint joinPoint, PreventDuplicateSubmit preventDuplicateSubmit) throws Throwable {
        String key = generateKey(joinPoint, preventDuplicateSubmit);
        Long deleteCount = stringRedisTemplate.delete(key);
        if (deleteCount == null || deleteCount == 0) {
            throw new BusinessException("Do not submit order repeatedly");
        }
        try {
            return joinPoint.proceed();
        } finally {
            // Optional: restore token on business failure
            // stringRedisTemplate.opsForValue().set(key, "1", preventDuplicateSubmit.expireTime(), TimeUnit.SECONDS);
        }
    }

    private String generateKey(ProceedingJoinPoint joinPoint, PreventDuplicateSubmit preventDuplicateSubmit) {
        StringBuilder key = new StringBuilder(preventDuplicateSubmit.keyPrefix());
        if (preventDuplicateSubmit.bindUser()) {
            Long userId = SecurityUtils.getCurrentUserId();
            key.append(userId).append(":");
        }
        String token = request.getHeader("X-Duplicate-Token");
        if (StringUtils.isBlank(token)) {
            throw new BusinessException("Idempotency token cannot be empty");
        }
        key.append(token);
        return key.toString();
    }
}

3. Token Generation Endpoint

@RestController
@RequestMapping("/api/token")
@RequiredArgsConstructor
public class TokenController {
    private final StringRedisTemplate stringRedisTemplate;

    @GetMapping("/generate")
    public Result<String> generateToken() {
        Long userId = SecurityUtils.getCurrentUserId();
        String token = UUID.randomUUID().toString().replace("-", "");
        String key = "order:submit:" + userId + ":" + token;
        stringRedisTemplate.opsForValue().set(key, "1", 60, TimeUnit.SECONDS);
        return Result.success(token);
    }
}

4. Order Controller Usage

@RestController
@RequestMapping("/api/order")
@RequiredArgsConstructor
public class OrderController {
    private final OrderService orderService;

    @PostMapping("/create")
    @PreventDuplicateSubmit(expireTime = 120, keyPrefix = "order:create:")
    public Result<OrderVO> createOrder(@RequestBody CreateOrderDTO dto) {
        OrderVO orderVO = orderService.createOrder(dto);
        return Result.success(orderVO);
    }
}

5. Global Exception Handler

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(DuplicateKeyException.class)
    public Result<Void> handleDuplicateKeyException(DuplicateKeyException e) {
        log.error("Database unique constraint violation: ", e);
        return Result.fail("Order submission failed, please retry");
    }

    @ExceptionHandler(BusinessException.class)
    public Result<Void> handleBusinessException(BusinessException e) {
        return Result.fail(e.getMessage());
    }
}

Technical Challenges & Solutions

Concurrency atomicity : Traditional check-then-act races under load. Solution: Redis atomic DEL or Lua script merging check+delete. Forbidden :

if (redis.hasKey(key)) { throw; } else { redis.delete(key); }

. Recommended : if (redis.delete(key) == 0) { throw; }.

Distributed consistency : Local locks don't span services. Solution: Redis distributed lock or Redisson with auto-renewal and deadlock protection.

Token leakage : Tokens could be stolen. Solution: Bind to user ID + IP, short TTL (60-120s), single-use invalidation, transmit via header not URL.

TTL tuning : Too short blocks legitimate requests; too long wastes memory. Solution: Per-scenario config: normal orders 60s, complex orders 120s, flash sales 10s.

Unique index performance : Unique indexes slow writes on large tables. Solution: Use short columns, avoid large varchar(255), choose proper time granularity. Recommended composite: user_id + goods_id + floor(create_time/60).

MQ redelivery : Payment callbacks, inventory deductions may repeat. Solution: Consumer-side idempotency via message ID (Redis SETNX) or DB unique index on message_id.

Cross-service idempotency : Order service calling payment/inventory may retry. Solution: Every service implements idempotency; pass global request ID (e.g., from Sleuth/SkyWalking); downstream uses request ID for deduplication.

Resource leaks on exceptions : Locks/tokens not released when business throws. Solution: Release in finally; set Redis key expiry; prefer Redisson auto-renewal.

Technical Highlights

Low intrusion : AOP + annotation, zero business code pollution, easy maintenance.

Atomic guarantee : Redis atomic commands eliminate high-concurrency race conditions.

Generalized capability : Configurable for different scenarios, high reusability.

Multi-layer defense : Frontend + backend + database + reconciliation ensures end-to-end consistency.

Friendly error handling : Unified exception handling returns clear messages.

Interview Simulation: Key Q&A

Interviewer : User clicks order button multiple times due to lag; backend creates duplicate orders and charges multiple times. How to prevent end-to-end?

Candidate : Core is idempotency . Defense in depth: Frontend → Gateway/Service → Database . Principle: "Get token first, then do work."

Frontend : Button disable ( disabled=true), debounce (300ms-2s), redirect to result page with history.replaceState(). Stops honest users only.

Idempotent Token (One-time Token) : 1. Get token : Pre-call endpoint, server generates globally unique token (Snowflake ID), stores in Redis as idempotent:order:uid:123 with 5-min TTL, returns to frontend. 2. Submit with token : Order request must carry token. 3. Atomic verification : Never check-then-delete (race window). Use Lua script to atomically GET+DEL:

if redis.call("GET", KEYS[1]) == ARGV[1] then
    return redis.call("DEL", KEYS[1])
else
    return 0
end

Script returns 1 only for first caller; others get 0 and receive "Order processing, do not resubmit". Guarantees only one thread proceeds even under 10 concurrent requests.

Redis failure / token bypass : Database fallback . Unique index on order_no or (user_id, sku_id, time_window). Use INSERT IGNORE or ON DUPLICATE KEY UPDATE; catch DuplicateKeyException, log, return "Order already exists". Physical guarantee even if all prior layers fail.

MQ duplicate consumption : Consumer uses business unique ID (order_no) as Redis key, SETNX before processing; success keeps key until expiry. Or rely on DB unique constraint with transaction rollback.

Selection summary : Layered table comparing strategy, layer, UX, reliability, notes. Multi-layer ensures if one leaks, next catches.

Additional Code Walkthrough

1. Token Generation Endpoint (Snowflake ID)

@RestController
public class IdempotentTokenController {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("/order/token")
    public Result<String> getOrderToken(@RequestParam Long userId) {
        String token = SnowflakeIdWorker.nextIdStr();
        String key = "idempotent:order:" + userId;
        redisTemplate.opsForValue().set(key, token, 5, TimeUnit.MINUTES);
        return Result.success(token);
    }
}

Highlights: Snowflake ID for unique, ordered, high-performance tokens; 5-min TTL balances UX and safety.

2. Lua Script Atomic Check-and-Consume

private static final DefaultRedisScript<Long> TOKEN_CHECK_SCRIPT;
static {
    TOKEN_CHECK_SCRIPT = new DefaultRedisScript<>();
    TOKEN_CHECK_SCRIPT.setLocation(new ClassPathResource("lua/token_check.lua"));
    TOKEN_CHECK_SCRIPT.setResultType(Long.class);
}

public boolean checkAndConsumeToken(String key, String token) {
    Long result = redisTemplate.execute(TOKEN_CHECK_SCRIPT, Collections.singletonList(key), token);
    return result != null && result == 1L;
}

Lua script ( token_check.lua) same as above. Loaded once as static resource to avoid recompilation.

Why Lua? Java if (get(key) == token) del(key) has race window. Lua executes atomically in Redis single-threaded engine, closing the gap.

3. Order Placement Logic (Token Check + DB Fallback)

@Transactional
public Order placeOrder(OrderDTO dto) {
    String idempotentKey = "idempotent:order:" + dto.getUserId();
    String token = dto.getToken();
    if (!checkAndConsumeToken(idempotentKey, token)) {
        throw new BizException("Order processing, do not resubmit");
    }
    Order order = buildOrder(dto);
    try {
        orderMapper.insertIgnore(order);
    } catch (DuplicateKeyException e) {
        throw new BizException("Order already exists, cannot create duplicate");
    }
    return order;
}

MyBatis mapper:

@Insert("INSERT IGNORE INTO orders (order_no, user_id, ...) VALUES (#{orderNo}, #{userId}, ...)")
int insertIgnore(Order order);

Table schema (critical):

ALTER TABLE orders ADD UNIQUE INDEX uniq_order_no (order_no);
-- Or business-composite unique index
ALTER TABLE orders ADD UNIQUE INDEX uniq_user_sku_time (user_id, sku_id, create_time_hour);

Why DB is the final wall? Redis may crash, scripts timeout, network partition. Unique index is physical guarantee: no two identical orders can ever be persisted.

Technical Challenges & Solutions Summary

Concurrency penetration : Multiple requests pass token check. Fix: Lua atomic check+delete, Redis single-threaded execution.

Redis failure degradation : Token service down halts business. Fix: DB unique index fallback; Redis loss only removes early interception, not data consistency.

Token expiry : User fills form slowly, token expires in 5 min. Fix: Frontend periodic renewal or silent refresh before submit; re-fetch on expiry.

Distributed clock drift : Snowflake ID relies on machine clock; backward clock causes duplicates. Fix: Snowflake algorithm handles clock rollback (wait or throw).

Frontend bypass : Attackers call API directly. Fix: Backend enforces token validation, never trusts frontend data.

MQ duplicate consumption : Consumer retries cause duplicate orders. Fix: Consumer uses business ID for Redis SETNX idempotency or DB unique constraint.

End-to-end idempotency architecture diagram
End-to-end idempotency architecture diagram
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.

reconciliationAOPRedisSpring Bootdistributed lockIdempotencyLua scriptdatabase unique indexdistributed tokenduplicate submission prevention
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.