StackPractices
intermediate By Mathias Paulenko

Message Deduplication Pattern

Prevent duplicate processing by tracking message IDs with idempotency keys. Consumers check a store before processing to skip messages already handled.

Overview

Most message brokers only promise at-least-once delivery, meaning a consumer can see the same message several times. Network retries, consumer crashes during processing, and broker redelivery all cause duplicates. Without deduplication, a payment might be charged twice or a notification sent several times to the same user.

The pattern has the consumer write each message ID down in a store. Before doing anything, the consumer looks up whether that ID was already handled. If it was, skip it; otherwise process the message and record the ID.

When to Use

  • Your message broker only guarantees at-least-once delivery (most do: SQS, RabbitMQ, Kafka)
  • Processing a message twice causes side effects (payments, emails, inventory changes)
  • You need exactly-once processing semantics without a broker that supports it natively
  • Consumer crashes happen and messages get redelivered
  • You process webhooks from third-party services that may retry on network failures
  • You consume from several queues and need cross-queue deduplication

When to Avoid

  • Your broker already does exactly-once natively. Kafka transactions and SQS FIFO with content-based dedup already handle this. Adding application-level dedup is redundant.
  • Messages are idempotent by nature. If processing twice has no side effects (e.g., updating a last-seen timestamp), dedup adds overhead without value.
  • Throughput is critical and every millisecond counts. Redis dedup adds ~0.5ms per message. For ultra-low-latency systems, lean on broker guarantees instead.
  • You can’t afford a dedup store dependency. If Redis downtime is unacceptable and you can’t fall back to idempotent processing, reconsider the architecture.
  • Messages have no natural unique ID. Generating content hashes for every message adds CPU overhead and may dedup incorrectly for same-payload-different-intent cases.

Solution

Python (Redis + SQS)

import redis
import json
import hashlib

r = redis.Redis(host="localhost", port=6379, db=0)
DEDUP_TTL = 86400  # 24 hours

def process_message(message_id, payload):
    # Check if already processed
    dedup_key = f"dedup:{message_id}"
    if r.exists(dedup_key):
        print(f"Skipping duplicate message {message_id}")
        return

    # Process the message
    result = handle_order(payload)

    # Mark as processed with TTL
    r.setex(dedup_key, DEDUP_TTL, "1")
    print(f"Processed message {message_id}")

def handle_order(payload):
    order = json.loads(payload)
    print(f"Charging payment for order {order['order_id']}")
    return {"status": "charged"}

# Simulate duplicate delivery
process_message("msg-001", '{"order_id": 42}')
process_message("msg-001", '{"order_id": 42}')  # Skipped

JavaScript (Redis + BullMQ)

import Redis from "ioredis";
import { Worker } from "bullmq";

const redis = new Redis({ host: "localhost", port: 6379 });
const DEDUP_TTL = 86400; // 24 hours

async function isDuplicate(messageId) {
  const key = `dedup:${messageId}`;
  const result = await redis.set(key, "1", "EX", DEDUP_TTL, "NX");
  // result is "OK" if the key was set (first time), null if it already existed
  return result === null;
}

const worker = new Worker(
  "orders",
  async (job) => {
    const messageId = job.data.messageId;
    const payload = job.data.payload;

    if (await isDuplicate(messageId)) {
      console.log(`Skipping duplicate message ${messageId}`);
      return { status: "skipped" };
    }

    // Process the message
    console.log(`Charging payment for order ${payload.orderId}`);
    return { status: "processed" };
  },
  { connection: { host: "localhost", port: 6379 } }
);

Java (Redis + Spring)

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;

@Component
public class DeduplicatingConsumer {

    private final StringRedisTemplate redis;
    private static final int DEDUP_TTL = 86400; // 24 hours

    public DeduplicatingConsumer(StringRedisTemplate redis) {
        this.redis = redis;
    }

    public void processMessage(String messageId, String payload) {
        String dedupKey = "dedup:" + messageId;

        // Atomic check-and-set: returns true if key was set (first time)
        Boolean wasSet = redis.opsForValue()
            .setIfAbsent(dedupKey, "1", DEDUP_TTL, TimeUnit.SECONDS);

        if (Boolean.FALSE.equals(wasSet)) {
            System.out.println("Skipping duplicate message " + messageId);
            return;
        }

        // Process the message
        System.out.println("Processing message " + messageId + ": " + payload);
        handleOrder(payload);
    }

    private void handleOrder(String payload) {
        // Business logic here
    }
}

How It Works

The pattern relies on an atomic check-and-set operation (Redis SET NX EX) to decide whether a message has been processed. Atomicity is what makes this safe: only one consumer can set the key, so two consumers handling the same message can’t both proceed.

flowchart diagram: Message arrives<br>with unique ID
  1. Message arrives with a unique ID. First thing the consumer does is pull the dedup key out of the message, usually a producer-assigned UUID or a hash of the content.
  2. Atomic check-and-set. The consumer attempts SET NX EX on the dedup key in a shared store. If the key doesn’t exist, the consumer sets it and proceeds. If it’s already there, someone processed it before and the consumer skips it.
  3. Only the key winner processes. Concurrent consumers holding the same message ID fail the SET NX and skip.
  4. TTL expiry bounds the store. After the configured TTL the key expires, so the store doesn’t grow indefinitely. Set the TTL above the broker’s maximum redelivery window (typically 24 hours for SQS, or the queue’s retention period).

There’s one subtlety worth knowing: marking the key before processing means a crash after SET NX but before the work finishes loses the message (it’s flagged as done). Marking after processing means a crash causes reprocessing. Most teams accept the first option and pair it with idempotent handlers, since at-least-once delivery already assumes you can see the same message twice.

Variants

The right dedup store depends on your durability needs and existing infrastructure. The table compares the common options; Redis is the usual default, but a database unique constraint is a solid alternative when durability matters more than latency.

VariantStoreUse CaseTradeoff
Redis SET NXRedisFast, shared across consumersExternal dependency, TTL-based expiry
Database Unique ConstraintSQL DBDurable, transactionalSlower, adds DB load
Content HashingAny storeDedup by payload contentSame payload always deduped, even if different intent
Broker NativeSQS FIFOBuilt-in dedupOnly with FIFO queues, limited throughput
In-Memory SetProcess memorySingle consumer, fastLost on restart, not shared across instances

For high-throughput systems the difference is significant: a Redis check costs sub-millisecond, while a database insert check runs 5-10ms. Redis is what most teams reach for first, but the right call is whichever store matches your latency budget and the failures you can absorb.

Best Practices

  • For a deeper guide on the receiving side, see the Idempotent Consumer Pattern.
  • Use atomic check-and-set. With Redis SET NX EX two concurrent consumers can’t both win. Check-then-set in two calls is a classic race.
  • Prefer producer-assigned IDs over content hashes. Content hashes dedup identical payloads, which is wrong when the same payload means different logical operations. IDs track identity, not content.
  • Fall back to content hashes when messages lack IDs. When the producer can’t assign an ID, hashing the payload beats doing nothing, though it comes with real limits.
  • Keep consumers idempotent as a second layer. Even if dedup fails or the TTL expires early, processing twice shouldn’t cause harm. The message idempotency recipe covers handler-side techniques.
  • Log every skipped duplicate with its ID and timestamp. That’s how you debug redelivery issues and track your duplicate rate.
  • Watch the dedup hit rate. Half the traffic showing up as duplicates points to something wrong upstream: the producer is retrying too aggressively or the consumer is too slow to acknowledge.
  • Use FIFO queues when available. SQS FIFO and Kafka partition keys give ordering and dedup at the broker level, reducing the need for application-level checks.
  • Plan graceful degradation on dedup store failure. If Redis is down, decide between processing with idempotency or rejecting. Document the choice and alert on it.

Common Mistakes

  • Check-then-set without atomicity: Two consumers check simultaneously, both see no key, both process. Always use atomic SET NX.
  • TTL too short: If the TTL expires before the broker stops redelivering, duplicates slip through. Set TTL to at least 2x the redelivery window.
  • Using process memory for dedup: Lost on restart, not shared across consumer instances.
  • Not planning for dedup store failures: when Redis goes down, dedup goes down with it. Decide whether to process (risk duplicates) or reject (lose messages).
  • Dedup key built on mutable fields: put a field that changes into the key and the same logical message ends up with different keys, so it gets processed twice.

Real-World Examples

Stripe Payment Webhooks

Stripe fires webhooks for payment events. Network failures cause Stripe to retry, delivering the same webhook several times. Stripe’s own recommendation is to dedup on event IDs: look the event ID up in a store before you process anything. Without dedup, a single payment could trigger several order fulfillments.

SQS + Lambda Order Processing

An e-commerce site runs its order processing as Lambda functions off an SQS queue. SQS may redeliver messages if Lambda fails to acknowledge in time. The platform uses Redis SET NX with the order ID as the dedup key. Duplicate deliveries get skipped, so no customer is charged or shipped twice.

Kafka Consumer with Redis Dedup

A streaming pipeline pulls events off Kafka and lands them in a database. Kafka only promises at-least-once, so a consumer can pick up the same event twice. The consumer checks Redis before writing to the database. This gives exactly-once semantics without Kafka transactions.

Troubleshooting

These are the failure modes specific to deduplication, not generic queue problems:

  • Duplicates still get processed: verify the dedup key is stable across retries. If the key embeds a timestamp, attempt counter, or any mutable field, each redelivery gets a new key and the check never fires.
  • Dedup store grows unbounded: a missing or oversized TTL fills Redis with stale keys. Monitor memory usage and keep TTL at roughly 2x the broker’s redelivery window.
  • Crash between check and mark: the consumer sets the key, dies mid-work, and the message is lost even though nothing ever got processed. Either accept this and pair it with idempotent handlers, or mark after processing and tolerate one reprocessing on crash.
  • False positives with content hashing: two different logical operations with identical payloads get collapsed into one. Switch to producer-assigned IDs, or include an intent field (operation type) in the hash input.
  • Dedup checks die during a Redis outage: you’ve got to choose the failure mode upfront. Fail-open processes with idempotency as the safety net; fail-closed rejects and retries, protecting against duplicates at the cost of availability.
  • Duplicate rate suddenly spikes: the dedup pattern is working but something upstream changed. Check producer retry configuration, consumer ack timeouts, and whether a new consumer group rejoined the topic.

Further Reading

Frequently Asked Questions

Is deduplication the same as idempotency?

Related, sure, but not the same thing. Deduplication prevents a message from being processed twice. Idempotency means processing a message twice has the same effect as once. Both matter: dedup as the first line of defense, idempotency as the safety net.

Should I use content hashing or producer-assigned IDs?

Producer-assigned IDs are better when the same logical message should always be deduped. Hashing dedupes identical payloads, which backfires when the same payload shows up in different logical operations.

What if Redis goes down?

Then the dedup layer can't check anything. You've got three options: fail fast and retry later, process anyway and lean on idempotency, or keep a fallback store. Most teams go with the second and make their consumers idempotent.

How do I choose the right TTL for dedup keys?

Find your broker's maximum redelivery window and double it, minimum. SQS can hold a message for up to 14 days, so 172800 seconds (48 hours) makes a safe default. For RabbitMQ, check the queue's message TTL and set dedup TTL higher.

Can I use a database instead of Redis for dedup?

Yep, a unique constraint works. Just a table with a unique constraint on the message ID. Insert before processing; if the insert fails with a duplicate key, skip the message. It's durable and transactional but slower than Redis and adds load to the database.

How do I handle dedup with several consumer instances?

All instances must hit the same shared store (Redis or a database) so they check the same keys. In-memory sets per instance don't cut it: each instance only sees its own keys and misses what the others handled.

What is the performance impact of dedup?

Redis SET NX EX is sub-millisecond, so the overhead is negligible next to message processing. A database check costs roughly 5-10ms each time, which is why high-throughput systems almost always land on Redis.

Can I use SQS FIFO dedup instead of Redis?

Yep, and the broker does the work for you. FIFO already does content-based dedup for you. If you produce messages with a MessageDeduplicationId, SQS dedupes within a 5-minute window. That removes the Redis dependency, at the cost of a 300 TPS ceiling.

What is the relationship between dedup and exactly-once semantics?

Dedup alone isn't exactly-once. You also need idempotent producers so duplicates never get created in the first place, and atomic consumer commits where processing and the offset commit land in one transaction. Dedup is the safety net on top of that stack.

How do I test deduplication?

Fire the same message ID twice and confirm only one went through. Send different IDs and confirm they all go through. Run concurrent consumers against the same ID. And kill Redis on purpose to see whether your fallback strategy actually holds.