Why Message Duplicates Are Inevitable: 4 Idempotency Patterns & 3 Critical Pitfalls
At-least-once delivery makes duplicates unavoidable; this article details four idempotency patterns—database unique index, consumption log table, Redis SETNX, and state machine—with code examples, and warns of seven pitfalls including transaction boundaries, acknowledgment handling, and key selection.
Reading font

Why Duplicates Are Inevitable
There is a counter-intuitive fact: the stricter you configure MQ reliability (acks=all, manual ack, confirm), the more likely duplicate consumption becomes. Mainstream MQs provide at-least-once delivery semantics — they guarantee delivery but may deliver multiple times. Achieving exactly-once is prohibitively expensive and rarely used in production. Therefore the only viable conclusion: prevent loss on the producer side, prevent duplicates on the consumer side, and deduplication must be implemented by the business via idempotency. This is not optional.
Three Sources of Duplicate Messages
Duplicates originate from three unavoidable stages:
【Producer】Network jitter after send, no confirm received → MQ actually received → producer retries
↓ Message ×2
【Broker】Consumer processes successfully, crashes before ack → restart triggers redelivery
↓ Message ×2
【Consumer】Kafka Rebalance / RabbitMQ master-slave switch → partition or queue reassigned → uncommitted offsets reprocessedEach stage corresponds to a "stricter config = more duplicates" scenario:
Producer confirm enabled → timeout triggers retry (even if broker already got it)
Consumer manual ack → crash after processing but before ack → guaranteed redelivery
Cluster Rebalance / failover → partition reassignment → uncommitted messages consumed again
This is the cost of reliability, not a defect of any specific MQ. Switching products does not change it.
Four Deduplication Solutions Compared
Database Unique Index — Highest reliability, zero extra components, must-have fallback
Consumption Record Table — High reliability, one extra table, most universal, preferred for complex business
Redis SETNX — Medium reliability, requires Redis, frontline filter blocking 90%
State Machine Check — High reliability, zero extra components, use when business semantics are naturally idempotent
Recommended production combination: Redis frontline filter (reduce DB load) + Database unique constraint (ultimate fallback) + State machine (semantic protection) , three layers stacked.
Solution 1: Database Unique Index (Most Reliable Fallback)
Leverage "duplicate insert always errors" for business that already persists data:
ALTER TABLE t_order ADD UNIQUE KEY uk_order_no (order_no);public void handle(OrderDto order) {
try {
orderMapper.insert(order); // DuplicateKeyException on duplicate
} catch (DuplicateKeyException e) {
return; // Already exists = processed, treat as success
}
// Subsequent business logic...
}Pros: Database physical layer prevents duplicates, works under multi-node concurrency. Limitation: Only applies when "the duplicate data itself should be persisted".
⚠️ Critical anti-pattern: Check-then-insert
// Wrong
if (orderMapper.selectByNo(order.getOrderNo()) == null) {
orderMapper.insert(order); // Time window between check and insert, concurrent nodes still duplicate
}There is a time window between check and insert; two nodes can both see "not exist" and insert simultaneously. Must let the database unique index decide, do not query yourself.
Solution 2: Consumption Record Table (Most Universal)
Separate "already consumed messages" table, decoupled from business table:
CREATE TABLE mq_consume_record (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
message_key VARCHAR(64) NOT NULL COMMENT 'Business unique key: order_no / message_id',
consumer_group VARCHAR(64) NOT NULL COMMENT 'Consumer group',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY uk_msg (message_key, consumer_group)
) COMMENT 'MQ consumption record table';Note the unique index is on (message_key, consumer_group) — two fields because the same message consumed by different consumer groups is legitimate and must not block each other.
@Component
public class IdempotentHelper {
@Autowired
private MqConsumeRecordMapper recordMapper;
/** true = first consumption; false = duplicate */
public boolean tryConsume(String messageKey, String group) {
MqConsumeRecord record = new MqConsumeRecord();
record.setMessageKey(messageKey);
record.setConsumerGroup(group);
try {
recordMapper.insert(record); // Race insert: insert succeeds = first time
return true;
} catch (DuplicateKeyException e) {
return false; // Unique index conflict = already consumed
}
}
}Usage has an extremely critical point:
@Transactional(rollbackFor = Exception.class)
public void handle(OrderDto order) {
boolean first = idempotentHelper.tryConsume("order:" + order.getOrderNo(), "order-group");
if (!first) {
return; // Duplicate: do not process, normal return → ack committed
}
// Business processing (deduct inventory, record ledger...)
}Two mandatory conditions:
Deduplication record and business in the same transaction. If committed separately, "record inserted but business fails" permanently blocks the message — retries will forever judge "already consumed" and business never executes. Same transaction rolls back record on business failure, allowing retry to re-run.
Duplicate messages must also ack normally. On deduplication hit, return directly (treat as success), do not throw exception. Throwing causes endless retries until dead-letter queue.
Solution 3: Redis SETNX (Frontline Filter, Three Pitfalls)
Lightweight, blocks most duplicates, saves database pressure:
public boolean tryConsume(String messageKey, String group) {
String key = "mq:consumed:" + group + ":" + messageKey;
Boolean ok = redisTemplate.opsForValue()
.setIfAbsent(key, "1", 24, TimeUnit.HOURS);
return Boolean.TRUE.equals(ok);
}Three pitfalls — hitting any breaks idempotency:
Business fails but key not deleted → Retry judged "already consumed", message effectively lost. Fix: Delete key in catch block (still tiny window, so DB fallback required).
TTL too short → Delayed messages / dead-letter retries land after expiry, deduplication fails. Fix: Minimum 24h TTL, cover max retry cycle.
Redis and DB out of sync → Mark in Redis, data in DB, two sides mismatch. Fix: Redis only as filter, never as sole authority.
The essence of the third pitfall: Redis may lose data (restart, eviction) or crash before key deletion. So it can only reduce DB load; final arbitration must remain on the database unique index.
Solution 4: State Machine (Business Semantic Idempotency)
Many businesses have natural state transitions; "already in target state, skip processing" is idempotency:
public void onPaySuccess(Long orderId) {
Order order = orderMapper.selectById(orderId);
if (order == null || order.getStatus() != OrderStatus.UNPAID) {
return; // Already paid / cancelled → skip
}
// Conditional UPDATE, naturally prevents concurrency
int rows = orderMapper.update(null,
new LambdaUpdateWrapper<Order>()
.eq(Order::getId, orderId)
.eq(Order::getStatus, OrderStatus.UNPAID)
.set(Order::getStatus, OrderStatus.PAID));
if (rows == 0) {
return; // Another thread updated first
}
}The key is .eq(Order::getStatus, OrderStatus.UNPAID): Conditional UPDATE is atomic. Two consumers arrive simultaneously; only one succeeds (rows=1), the other gets rows=0 and returns. This is far safer than "check-then-update" and requires no extra table or Redis.
Multi-Node Concurrency: Don't Rely on Local Locks
Same consumer group deployed on 3 nodes; duplicate messages may arrive simultaneously at two different JVMs. Local synchronized, ConcurrentHashMap are completely ineffective.
Only three viable approaches, all relying on atomic operations of database or Redis to arbitrate:
Database unique index / consumption record table: Two nodes insert simultaneously, only one succeeds, the other throws DuplicateKeyException Redis SETNX: Only one can set successfully at a given moment
Distributed lock (Redisson): Works, but overkill for deduplication — first two are lighter
Core principle: Never use "check-then-process"; let database unique constraint or Redis atomic operation decide for you.
Seven Common Pitfalls
Check-then-insert deduplication — Concurrent nodes both judge "not consumed" → Fix: Unique index + catch DuplicateKeyException Deduplication and business in different transactions — Business fails but record exists, message permanently blocked → Fix: Place in same @Transactional Duplicate message not acked — Endless retries, eventually dead-letter → Fix: Treat duplicate as success, normal ack
Message lacks unique key — No basis for deduplication → Fix: Producer must carry business key: Kafka key / RocketMQ KEYS / RabbitMQ messageId
Wrong idempotency key — Using timestamp / random number, different every time → Fix: Use business serial: order_no, payment_flow_no
Redis mark never expires — Keys grow unbounded → Fix: Set TTL, or archive consumption record table periodically
Using local lock for deduplication — Completely fails under multi-node deployment → Fix: Use DB unique constraint / Redis atomic operations
Pitfall #4 must be planned upfront: Idempotency key must be a business key carried by the producer. Discovering the issue later at consumer side leaves historical messages without usable keys.
Checklist
Duplicate consumption is an inevitable result of at-least-once, only solvable by business-side idempotency
Combination: Redis SETNX blocks 90% → Database unique constraint fallback → State machine semantic protection
Most universal: Consumption record table + Unique index + Same transaction as business
Three anti-patterns: Check-then-insert, Deduplication separate transaction, Duplicate message not acked
Idempotency key uses business serial, never timestamp / random number
Multi-node concurrency relies on DB/Redis atomic operations, local locks are useless
A useful self-check when writing idempotent code: "If this message arrives ten times in a row, what happens to my system?" Where you cannot answer is where the next incident will occur.
For questions about attribution, corrections or content rights, please contactand we will review it promptly.