Why did you get the same notification twice? Designing a notification system
Build a notification system one failure at a time. Timeouts, queues, the outbox, idempotency keys, retries with jitter, dead-letter queues, channels, fan-out and tracing, and why the goal was never to prevent duplicates, only to make them harmless.
15:40 video14 min read
- 1 architecture diagram
- 1 sequence flow
- 2 code samples
- 2 interviewer follow-ups
- 3 self-checks
at-least-once
what a standard queue promises, so duplicates are normal
1 key
one idempotency key per notification and channel, decided at the source
10M
phones one event can reach when a creator goes live (illustrative)
On this page12 sectionsHLDSenior depth
- Why a timeout is silence and not a no, and what that forces you to choose between.
- How a queue and the outbox pattern take the provider off the payment path, and what duplicate they leave.
- How an idempotency key makes a duplicate harmless, and why the check must be one atomic step.
- How retries, dead-letter queues, channels, fan-out and rate limits fit around that core.
Your phone buzzes: payment successful. A second later it buzzes again. Same words, same amount. You check your bank: one charge. Your money is fine. The system that told you about it is not.
That system did nothing careless. It sent a message, the provider went quiet, and it did the responsible thing and tried again. The first message had already arrived.
The simplest notification system is one function call. The payment service finishes a charge and calls a notification service, which calls an SMS provider, which hands the text to a carrier, and the phone buzzes. Every arrow waits for the next box.
It works until the network goes quiet. You give the provider three seconds and nothing comes back. What do you know? Maybe your request never arrived. Maybe they sent the text and their reply was lost. Maybe they are still sending it. From your side all three look the same: a timeout is silence, not a no.
So you choose. Never retry, and some users never get their message, including the one-time password they need to log in: that is at-most-once. Always retry, and some users get it twice: at-least-once. There is no third switch labelled exactly once. Most real systems pick at-least-once, because a missing password locks someone out while a duplicate receipt is a raised eyebrow.
There is a second problem. The payment service is waiting on the provider. If the provider takes ten seconds, checkout takes ten seconds. A company you do not control sets how fast your customers can pay. The notification has to leave the payment path.
A queue turns now into soon. The payment service stops calling anyone and writes one small message onto a queue: who, what happened, which template. That takes milliseconds whether the provider is healthy or on fire. Workers pull messages off, call the provider, and only when the provider accepts do they acknowledge. If a worker dies first, the queue hands the message to someone else. Nothing is lost.
One hop is still unprotected: the one into the queue. If the payment commits and the service crashes before writing to the queue, the customer paid and nobody tells them. Swap the order and it is worse: a message goes out, the payment rolls back, and someone is told their payment worked when no money moved. The fix is the outbox pattern: save the message in the same database transaction as the payment, in an outbox table, so both happen or neither does. A relay reads the outbox and publishes each row. If the relay crashes after publishing but before marking the row done, it publishes that row again. Remember that shape.
Now the double buzz. A worker pulls the message, calls the provider, the text goes out, and the worker is killed before it acknowledges, by a deploy or a memory limit. The queue sees no acknowledgement and does exactly what it was built to do: another worker gets the message and sends it again.
That is not a flaw in the queue. Almost every queue you will use promises at-least-once delivery, because redelivery is how it guarantees nothing is lost. Amazon SQS standard queues say so in their documentation, and tell you to make processing idempotent. The price of never losing a message is sometimes seeing it twice.
Idempotent means doing something twice has the same effect as doing it once. Give every notification a name decided at the source, in the same transaction that wrote the outbox row, built from things that never change: this payment, this event, this user, this channel. If the relay publishes that row twice, both copies carry the same name.
Before calling the provider, a worker asks a small, fast store one question: have we seen this key? If not, it claims the key in one atomic step, sends, and marks it sent. A redelivered copy asks the same question, hears "already sent", acknowledges the message and drops it. The phone stays quiet.
Three details matter. Atomic: if two workers check and then write as two steps, both can see nothing and both send; one conditional write (Redis SET NX, or an insert that fails on a unique key) lets exactly one win. Long enough: keep keys for longer than any retry or replay could take, days not minutes, or a late duplicate walks through. The channel is part of the key: otherwise the email goes out, marks the key sent, and the push is thrown away as a duplicate.
using System;
using System.Collections.Generic;
public enum Claim { Acquired, InProgress, AlreadySent }
public sealed class IdempotencyStore
{
private readonly Dictionary<string, (bool Sent, DateTime At)> _keys = new Dictionary<string, (bool Sent, DateTime At)>();
private readonly TimeSpan _lease;
private readonly Func<DateTime> _now;
private readonly object _gate = new object();
public IdempotencyStore(TimeSpan lease, Func<DateTime> now) { _lease = lease; _now = now; }
/// <summary>One atomic step that decides who may send. In production: a conditional write in Redis, or an insert that can fail on a unique key.</summary>
public Claim TryClaim(string key)
{
lock (_gate)
{
if (_keys.TryGetValue(key, out var entry))
{
if (entry.Sent) return Claim.AlreadySent;
if (_now() - entry.At < _lease) return Claim.InProgress; // another worker holds the claim
// The lease ran out: the worker may have died after sending. Claim it again and accept that risk.
}
_keys[key] = (false, _now());
return Claim.Acquired;
}
}
public void MarkSent(string key)
{
lock (_gate) _keys[key] = (true, _now());
}
}
public sealed class Worker
{
private readonly IdempotencyStore _store;
public Worker(IdempotencyStore store) { _store = store; }
public int Sends { get; private set; } // texts actually handed to the provider
/// <summary>Handle one delivery of a message. True means it can be acknowledged to the queue.</summary>
public bool Handle(string key, bool crashAfterSending = false)
{
switch (_store.TryClaim(key))
{
case Claim.AlreadySent: return true; // a duplicate: acknowledge it and do nothing
case Claim.InProgress: return false; // someone else is on it: leave it for later
}
Sends++; // call the provider
if (crashAfterSending) return false; // died before marking it sent or acknowledging
_store.MarkSent(key);
return true;
}
}The test replays the incident, then the one gap that remains:
using System;
using System.Diagnostics;
var clock = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var store = new IdempotencyStore(TimeSpan.FromSeconds(30), () => clock);
var worker = new Worker(store);
// The queue delivers the same message twice, after a missing acknowledgement: one text goes out.
bool first = worker.Handle("pay-8472-user-9-sms");
bool second = worker.Handle("pay-8472-user-9-sms");
Debug.Assert(first && second && worker.Sends == 1);
// The same payment on another channel is a different key, so it is not dropped as a duplicate.
worker.Handle("pay-8472-user-9-push");
Debug.Assert(worker.Sends == 2);
// A worker dies after sending, before marking it sent. While its claim is fresh, others wait.
bool crashed = worker.Handle("pay-8473-user-9-sms", crashAfterSending: true);
bool retryNow = worker.Handle("pay-8473-user-9-sms");
Debug.Assert(!crashed && !retryNow && worker.Sends == 3);
// When the lease runs out it is retried. A second text is possible here: the window shrinks to this, it does not close.
clock = clock.AddSeconds(31);
bool retryLater = worker.Handle("pay-8473-user-9-sms");
Debug.Assert(retryLater && worker.Sends == 4);That last case is the honest answer about exactly-once. Exactly-once delivery would mean guaranteeing that an external effect happens once despite failures, and with replies that can vanish and a phone you do not control, nobody can promise it. What you can build is idempotent processing: the message may arrive twice and takes effect once. Some providers close the gap further. Stripe's API, for example, takes an idempotency key and returns the saved result of the first request when you retry with it. Where a provider does not, you have shrunk the window, not closed it. For a login code you may accept a rare second text; for a marketing email you may choose not to send again.
Idempotent retries are safe, but safe is not the same as smart. Split failures in two. Temporary ones, a timeout, a server error, a provider telling you to slow down, deserve another try. Permanent ones, a number that does not exist, a user who unsubscribed, an address that bounced, never will, so fail them at once.
For temporary failures, do not retry immediately: if a provider is struggling and a thousand workers hit it again a second later, a slowdown becomes an outage. Wait one second, then two, then four, then eight (exponential backoff), and add randomness to each wait (jitter) so those thousand workers spread out instead of returning as one wave. The queues lesson has a tested C# retry policy, and the AWS Builders' Library explains why jitter matters.
Some messages will never succeed: the provider is down for an hour, or a template bug crashes on one user's name. After a set number of attempts, stop but do not delete. Move the message to a dead-letter queue with the reason it failed. That queue is an inbox, not a bin: alert when it grows, read it, fix the cause, then replay it into the main queue. Keys make the replay safe, because the messages that actually went out on their last attempt are stopped at the door.
Email, SMS and push look like one feature, but they fail differently. Users have opinions too: one wants receipts by email only, another mutes push after ten at night, another unsubscribed from everything except security alerts.
So after the queue a message meets a router that reads the user's preferences and quiet hours and decides where it goes. Each channel gets its own queue and workers, because SMS is slow and expensive while push is fast and nearly free, and in a shared queue a stalled SMS provider would leave push messages stuck behind texts that cannot move. Workers talk to an adapter, not the provider: every provider has its own request format and error codes, and the adapter turns them into three answers a worker understands: sent, try later, or give up. Adapters also make a backup provider easy.
Failing over to a backup provider is where a duplicate gets in a third time. Provider A times out, you switch to provider B, and B sends the text. But A had sent it too. Your key store cannot help, because it knows what you asked for, not what A did after you stopped listening. Fail over only when you can tolerate that ambiguity: an explicit rejection or a refused connection is easy to reason about, a timeout is not. Usually the safer move is to retry the same provider with the same key.
A payment notifies one person. A creator going live notifies everyone who follows them: one event, ten million phones. You do not write ten million messages from the request that started it. A fan-out worker walks the follower list a few thousand at a time and writes each batch to the queue; if it crashes on batch 400 it resumes there, and the keys make sure batch 399 does not go out twice.
Those messages are heading for providers with limits, so each lane sits behind a rate limiter that releases messages only as fast as the provider accepts them. It is the rate limiter turned around: this time we are the traffic, and someone else's system needs protecting from us. The queue holds the rest. There is a limit for users too: nobody wants forty buzzes an hour, so cap non-urgent ones per person and bundle the rest.
Then split by priority as well as channel. While ten million live alerts drain through push, someone tries to log in, and their password code cannot wait behind a celebrity. Security codes and receipts get a fast lane that marketing can never block. Ordering mostly does not matter; where it does ("shipped" before "delivered"), send one user's messages through the same partition, or put a version on each update and let the app ignore anything older than what it shows.
A notification system you cannot trace turns every complaint into a mystery: "I got my receipt twice", or worse, "I never got my code". With visibility you search for the key and watch its whole life: created, queued, routed to SMS and push, claimed, sent to the provider, accepted, and then the step teams forget, delivered.
Delivered comes from the provider later, as a delivery report, a callback saying the phone got it or the number bounced. These arrive late, out of order and sometimes twice, so the same rule applies: each has an id, and if you have seen it, ignore it. Then watch the whole system. Not just how many messages are queued but how old the oldest one is: a deep queue that is moving is fine, and a shallow one that is stuck is an outage. Track error rates per provider and the depth of the dead-letter queue.
Start with the failure, not the boxes: "A timeout does not tell me whether the message was sent, so I have to choose at-most-once or at-least-once, and I choose at-least-once." Then build in order: take the provider off the critical path with a queue, make publishing atomic with an outbox, make duplicates harmless with an idempotency key, retry with backoff and jitter, dead-letter what cannot succeed, then channels, fan-out, rate limits, priorities and tracing. Say out loud what each piece costs.
Interviewer follow-upL6You fail over from SMS provider A to provider B after a timeout. Why can that send two texts, and what do you do?How to answer
A timeout does not tell you whether A sent the text. If A did and B also sends, the user gets two, and your key store cannot see what A did outside your system. Prefer retrying the same provider with the same key. Fail over on explicit failures, such as a refused connection or a rejection, where it is clear nothing was sent. If you must fail over on a timeout, accept the ambiguity for low-stakes messages, and for critical ones (a login code) pick the policy deliberately and say which duplicate you prefer to the risk of no message.
Interviewer follow-upL7A creator with ten million followers goes live. How do you send without overloading providers or blocking password codes?How to answer
Fan out asynchronously: a worker batches the follower list into the queue, resumable and keyed, so a crash does not duplicate or skip. Put a rate limiter per provider lane so the flood is released at the rate the provider accepts, letting the queue absorb the rest. Cap and bundle non-urgent messages per user. Separate lanes by priority so security codes and receipts never wait behind a broadcast, and monitor the age of the oldest message in each lane, since that, not depth, shows whether users are waiting.
QuestionWhy is a timeout not the same as "the message was not sent", and what choice does that force?Reveal answer
A timeout is silence: the request may not have arrived, may have been processed with the reply lost, or may still be in progress. You cannot tell them apart, so you must choose between never retrying (at-most-once, which can lose messages) and always retrying (at-least-once, which can duplicate them). Most systems choose at-least-once.
QuestionWhy must the idempotency check and claim be one atomic step?Reveal answer
If two workers check and then write as separate steps, both can see no key and both send. A single conditional write, such as Redis SET NX or an insert that fails on a unique key, lets exactly one worker win, and the other sees the key and stops.
QuestionWhy does each channel get its own queue and workers?Reveal answer
Channels fail and perform differently. In a shared queue, a stalled SMS provider would leave fast push messages stuck behind texts that cannot move. Separate lanes mean one bad provider only hurts its own channel.
The queues and async work lesson covers delivery guarantees, idempotency, the outbox and a tested retry policy, and the rate limiting lesson covers the limiter that protects each provider lane. For the full design from a blank page, with a tested ledger, priority lanes, a circuit breaker and the traffic a campaign sends back to your own API, see the notification service case study.
- Amazon SQS, FAQs (opens in a new tab): standard queues deliver each message at least once, so applications should be idempotent.
- Amazon Builders' Library, Timeouts, retries, and backoff with jitter (opens in a new tab) and Making retries safe with idempotent APIs (opens in a new tab).
- Stripe, Idempotent requests (opens in a new tab): an idempotency key returns the saved result of the first request.
- Chris Richardson, Pattern: Transactional outbox (opens in a new tab).
Spot a mistake, or have a question?
Accuracy matters here. Tell me what looks wrong or unclear and I will fix it and credit you.