When the Same Message Arrives Twice: The Idempotent Consumer Pattern

On Monday morning, a customer representative came to us with a screenshot: at 04:12, within a single minute, the customer's phone had received 7 SMS messages with identical content. "Your vehicle has exited zone X." Seven times. The customer had asked, quite reasonably, "has your system lost its mind?" We checked the logs: the exit event had been produced once and written to the queue once. But the notification consumer had restarted seven times at 04:12 that night; because of a memory leak, the supervisor kept bringing it back up again and again. With each rebirth, it took the same message from the queue, sent the SMS, and died just before it could ack.

The queue system had done its job flawlessly. Redelivering a message that hasn't been acked is the very essence of its contract. The flaw was ours: we had written the consumer around the fantasy that every message would arrive exactly once.

There Is No Such Address as Exactly Once

In messaging systems, delivery guarantees are three doors: at-most-once (messages may be lost, but never duplicated), at-least-once (nothing is lost, but duplicates can happen) and the exactly-once that everyone wants. Behind the third door, in practice, is an empty room: as long as the "I processed it" acknowledgment itself can get lost on the network, the sender has to choose between retrying and accepting the loss. Brokers' exactly-once promises hold only within their own boundaries, and those boundaries don't cover the HTTP call you make to your SMS provider. The clear decision we came away with was this: ask the delivery layer for at-least-once, and hand the job of dealing with duplicates to the consumer. A consumer that deals with duplicates has a name: an idempotent consumer, one for which processing the same message once or seven times makes no observable difference.

At-most-once carries the risk of loss, at-least-once the risk of duplicates; exactly-once doesn't exist in practice, so the consumer handles duplicates.
At-least-once was requested from delivery, and the consumer handled duplicates.

Identity First: Giving a Message a Name

The prerequisite for idempotency is being able to recognize what we mean by "the same message." A randomly generated UUID won't do: it stays the same on redelivery, but if the producer side publishes the same event twice, two different UUIDs are born. We derived the key from the nature of the event itself: device ID + the device's packet sequence number + event type. This triple corresponds to exactly one real event in the world; whatever path the event takes and however many times it arrives, its key doesn't change. Deterministic identity became the foundation of everything we built afterward.

Once we had that question settled, we went through every consumer in the system one by one and drew up a risk inventory. Of fourteen consumers, four were already naturally idempotent, seven needed a dedup layer, and three were in the most dangerous class: the ones that produce side effects in the outside world, namely SMS, email, and a webhook going to a customer's ERP. The priority order formed by itself, and the first sprint was spent entirely on those three consumers.

The Dedup Table: Boring and Unshakable

The core mechanism is embarrassingly simple: a table called processed_messages with a unique index on the message key. When the consumer processes a message, it writes the dedup record in the same database transaction as the rows written by the business logic. If the key already exists, the insert fails with a unique violation, and the consumer reads that not as an error but as "I've already done this work," and quietly acks the message. The atomicity of the transaction is critical: the dedup record either comes into existence together with the business data or not at all. If you keep dedup as a separate step, let alone in a separate store, the chance of a crash between the two writes cracks the door open again.

The table doesn't need to grow forever; in practice, redeliveries happen within minutes. We delete records older than 7 days with a nightly job, and the table hovers at around 40 million rows without bothering anyone.

The message key is derived, the dedup record is written in the same transaction as the business data, a unique violation reveals the duplicate and the message is acknowledged.
The dedup record either exists along with the business data or not at all.

As an alternative to the dedup table, there are places where we use what we call "natural idempotency," and an honest post should cover both. Some operations can be written so that they're inherently resistant to repetition. For example, the consumer that updates the table holding each vehicle's last location writes with INSERT ... ON DUPLICATE KEY UPDATE and a condition that only accepts a newer timestamp. Even if the same message arrives seven times, the result is identical down to the bit, and no dedup record is needed. Operations like incrementing a counter, deducting from a balance or sending an email, on the other hand, aren't naturally idempotent, and a dedup layer is a must. On the team, the distinction became clear: if a write can be framed as "setting state," frame it that way; if it can't, lean on the dedup table. The most dangerous zone is the gray area of operations that are assumed to be idempotent but aren't. "Add to list" looks innocent, but run it twice and the list has two entries.

What About SMS? The Outside World Doesn't Do Transactions

That's how we brought database writes under control, but the wound in our case was SMS, and an SMS that has been sent can't be rolled back. Here we built two layers of defense. The first is using an idempotency key on the call to the provider: our provider doesn't turn a second request with the same key into a new SMS but returns the result of the first. The second is splitting sending into two phases on our own side: first, inside the dedup transaction, a record saying "I've acquired the right to send this notification," then the physical send, then an update with the result. If the process dies right after sending, on redelivery we find the claim record already filled in and don't repeat the send. A theoretical window still exists (if we crash between sending and recording, an SMS can go out twice), but that window has shrunk from an embarrassment of seven messages to a single case seen about once a year.

We also ran into duplication's sibling: ordering. A redelivered message sometimes arrives after its siblings, that is, out of order. After a vehicle's ignition-off event has been processed, the ignition-on event from two minutes earlier can show up. In the first version, this left a ghostly "running" status on the vehicle status screen. The solution again came from the sequence number in the event identity: consumers that update state don't use a message whose sequence number is lower than that of the record they hold to update state; they only write it to the history table. The late-arriving truth isn't lost, but it can't rewrite the present either. When idempotency and order tolerance are designed together, the consumer becomes something that can shrug off every whim of the queue: duplicates, delays and scrambled order alike.

The provider idempotency key, two-phase sending and a sequence number check handle SMS duplicates and out-of-order messages.
An SMS can't be rolled back, so a two-layer defense was built.

Duplication Isn't a Bug, It's the Weather

After rolling the pattern out widely, we added a metric to our monitoring: the duplicate_dropped counter. On normal days it sits at around 0.01 percent of total traffic; on deploy days, while consumers restart, it climbs as high as 0.4 percent. At first, the fact that the counter wasn't zero bothered the team; then we realized it's the exact opposite. If the counter is zero, your dedup mechanism isn't being tested, and you'll only find out whether it works on the day the first real duplicate arrives. A ticking counter means the parachute is being tested every day with small jumps.

Once the pattern had settled in, we carried it beyond the queue too. Our mobile apps retry requests on weak networks, and every request where the "save" button was tapped but no response came back is a potential duplicate record. We added an Idempotency-Key header to the API's write endpoints: the client generates a key for each logical operation, and when a second request arrives with the same key, the server returns the stored response of the first. The infrastructure is exactly the same as in the queue consumer: a key, a unique index and a stored result. A pattern learned once and put to work in three separate layers must be the hallmark of a good pattern.

Today, the team rule works like this: every new consumer that reads from a queue is greeted in code review with a single question, "what happens if I call this handler twice with the same message?" If the answer isn't "the same result," the design goes back. Starting to ask this question did more to raise our trust in our messaging infrastructure than the brand of the queue software ever did. If you're dealing with a wound opened by duplicate messages in your distributed system, our contact page is open. After hearing the seven-SMS story, nobody is embarrassed about their own case.