Sub topic 11
Avoiding duplicate notifications
A user who gets the same "Your order shipped" push three times loses trust in the app. Duplicates are also costly for SMS, where each message is billed. This chapter explains why duplicates happen in a notification pipeline and how to prevent them with idempotency keys.
This chapter assumes you know how message queues work, including acknowledgements and redelivery. It also assumes you can read short Python snippets and know what a key-value store is.
Why duplicates happen
Most queues and retry mechanisms promise at-least-once delivery. The system guarantees a message is processed one or more times, never zero. The alternative, at-most-once delivery, can lose messages. For notifications, losing an alert is usually worse than sending it twice, so pipelines choose at-least-once. Duplicates are the price of that choice.
Duplicates enter at several points:
- Producer retries. A service sends an event to the ingestion API, the response times out, and the service sends it again. The first request had actually succeeded.
- Queue redelivery. A worker takes a message and sends it, then crashes before it acknowledges the message. After the visibility timeout expires, the queue gives the message to another worker.
- Retries after an ambiguous failure. The worker calls the provider and the call times out. The provider may have accepted the request. A retry sends a second message.
- Fan-out bugs. A user has two registered devices, or an event is routed to the same channel twice by two rules.
The third case is the hardest. A timeout does not tell you whether the send happened.
Idempotency
An operation is idempotent if doing it several times has the same effect as doing it once. Sending a notification is not naturally idempotent, so you make it so. You attach an idempotency key to each unit of work. Before doing the work, a worker checks whether that key was already handled.
The key must identify the logical send, not the attempt. A retry of the same send must produce the same key. A different send must produce a different key.
Choosing the key
The event from the earlier chapters has a unique event_id. A good key combines it with the recipient and the channel:
{event_id}:{user_id}:{channel}For example, evt-1001:user-42:push. Each part matters:
| Part | Why it is in the key |
|---|---|
| `event_id` | Separates one business event from another. |
| `user_id` | One event can fan out to many users, such as a broadcast. |
| `channel` | The same event may legitimately go out by push and by email. |
If a user has several devices, add the device token to the push key, or you will send to only the first device.
Two points about where the event_id comes from:
- The producer should generate it. If the ingestion API generates a new id for every request, a producer retry gets a new id and the duplicate passes through. Let the producer supply a stable id, such as an order id plus the event type, and have the API reject or ignore a repeat.
- Do not use a timestamp or a random value generated inside the worker. These change on every attempt and defeat the key.
Claiming a key
The simplest deduplicator remembers keys in memory and tells the caller whether a key is new:
class Deduplicator:
def __init__(self):
self._seen = set()
def claim(self, key):
"""Return True the first time a key is seen, False afterwards."""
if key in self._seen:
return False
self._seen.add(key)
return True
dedup = Deduplicator()
key = "evt-1001:user-42:push"
if dedup.claim(key):
print("send")
else:
print("skip duplicate")This works in one process. It fails in production for three reasons:
- Several workers run in parallel, and each has its own memory. Worker 2 never sees what worker 1 claimed.
- Memory is lost on restart.
- The set grows without bound.
The production version keeps keys in a shared store such as Redis, with two properties.
- Atomic set-if-absent. Checking and writing must be one operation. If a worker reads "not present" and then writes, two workers can both read before either writes, and both send. Redis provides
SET key value NX EX 86400, which writes only if the key does not exist and attaches an expiry in one step. A database unique constraint on the key column gives the same guarantee. - An expiry. Keys only need to live as long as a duplicate could plausibly arrive. That window covers the producer retry period, the queue's retention, and the retry schedule. Twenty-four hours is a common choice. After that, the key expires and storage stays bounded.
The claim-then-send problem
Claiming a key before sending creates a new failure. A worker claims the key, then crashes before sending. The redelivered message finds the key claimed and is skipped. The notification is lost.
You have to pick which error you prefer, because you cannot remove both with a simple key check.
| Approach | Failure it prevents | Failure it allows |
|---|---|---|
| Claim, then send | Duplicates | A lost notification if the worker crashes in between |
| Send, then record | Lost notifications | A duplicate if the worker crashes in between |
A common refinement is to store a state with the key instead of a bare marker:
- Claim the key with state
in_progressand a short expiry, such as 60 seconds. - Send.
- Update the state to
sentwith the long expiry.
If a worker crashes, the in_progress claim expires, and the redelivered message can retry. Meanwhile a concurrent duplicate sees in_progress and backs off instead of sending. A crash between a successful send and the update to sent can still produce a duplicate. That window is small, and you can often shrink it further with the provider's own idempotency support.
Using provider idempotency
Some providers accept a client-supplied identifier and ignore repeats within a time window. Email APIs often support this through a header or a request field. Others do not, and push services such as APNs and FCM have limited support. A collapse key or notification identifier can replace an older message on the device instead of stacking a new one. Check the provider documentation, because the window length and behavior differ.
Passing your idempotency key to the provider is cheap and closes the ambiguous-timeout case. Do not rely on it alone, since you may switch providers or use one without support.
Interaction with retries
Retries and deduplication must cooperate. Consider the retry loop from the previous chapter:
import random
import time
class TransientError(Exception):
"""A failure worth retrying, such as a timeout or a 5xx from a provider."""
def send_with_retry(send, max_attempts=5, base=0.5, cap=30.0):
for attempt in range(1, max_attempts + 1):
try:
return send()
except TransientError:
if attempt == max_attempts:
raise
delay = random.uniform(0, min(cap, base * 2 ** (attempt - 1)))
time.sleep(delay)The key is claimed once, outside the loop. Each attempt reuses the same key when it calls the provider. If the claim were made inside the loop, the second attempt would see its own earlier claim and skip itself.
Common mistakes
- Treating the check and the write as two steps. Use one atomic operation.
- Keys that include the attempt number or a timestamp. Every retry looks new.
- Keys that are too coarse. Using only
user_id:typedrops a legitimate second shipment notification for a different order. Include the specific event. - A key lifetime shorter than the retry window. A late retry arrives after the key expired and is sent again.
- No deduplication at the producer boundary. Duplicates then enter the queue in the first place.
- Assuming exactly-once delivery. Exactly-once is not achievable across a network and a third-party provider. The goal is to make repeated work harmless.
Exercise
A worker claims the key "evt-9:user-3:sms" with a 24-hour expiry, calls the SMS provider, and crashes before acknowledging the queue message. The queue redelivers the message. What happens, and which design change lets a crash before the send be recovered without sending twice after a successful send?
Show answer
The second worker finds the key already claimed and skips the send. If the first worker crashed before it called the provider, the user never gets the SMS. If it crashed after, skipping is correct. Because the two cases look the same, store a state with the key. Claim it as in_progress with a short expiry, send, then mark it sent with the long expiry. A crash before the send lets the short claim expire so the redelivered message can retry. Passing the key to the provider as its idempotency identifier covers the case where the send succeeded but the update did not.
Exercise
Why must "check whether the key exists" and "store the key" be a single atomic operation when several workers run in parallel?
Show answer
With two separate steps, two workers can both check before either stores, both see the key as absent, and both send. An atomic set-if-absent, such as Redis SET with NX and EX or a unique constraint, lets exactly one worker succeed in claiming the key.