Designing a notification system: fan-out, queues, retries and idempotency
One event, a thousand users, three channels, and providers that fail. I built a small notification system in Go on Postgres 18 with per-user preferences, dedupe keys, retries with jittered backoff and a dead letter state, then ran it against flaky fake providers.
Sending one email is easy. Sending "your order has shipped" to the right people, on the channels each of them picked, exactly once, while the email provider returns 503 for a few minutes, is a small system of its own. In this blog we will design that system and build a working core of it in Go on Postgres.
This is an intermediate post. You should know Go and SQL. I used Go 1.27.3, Postgres 18 and pgx v5.13.0. The providers are fakes that fail on purpose, so everything here runs on a laptop without an AWS account.
The format is the same as the rest of the series: requirements, estimates, diagram, deep dive, trade-offs.
Requirements
- Channels: email, mobile push and SMS.
- Users choose channels. Someone who turned off SMS never gets one.
- One event (an order shipped, a password changed) can go to one user or to thousands.
- No duplicates. Sending the same OTP twice is annoying, sending a marketing push twice gets the app uninstalled.
- Retries for temporary failures, with a limit.
- Messages that can't be sent end up somewhere visible, not silently dropped.
- Sending must not slow down the code that raised the event.
Out of scope for today: templates and translations, quiet hours, and digests ("5 new comments" in one email). They fit into the same design later.
Estimates
Say 1 million users and an average of 3 notifications per user per day across channels. That's 3 million a day, about 35 a second on average. Notifications are bursty though. A broadcast to all users at 9 a.m. is 1 million rows in one go, and that's the case to design for.
Storage: a notification row with its payload is around 500 bytes, so 1.5 GB a day. Keep 30 days for support questions ("did the email go out?") and partition by month, as in the sharding and partitioning post, so old months are dropped instead of deleted.
The providers are actually the real limit. Email and SMS providers all have send rate limits per account, often in the tens or hundreds per second. So a 1 million broadcast is not sent in a second whatever we build. It's sent over minutes or hours, and the queue holds the rest.
High-level design
order service notification service providers
+-------------+ +---------------------------------------+
| event: | | fan-out |
| order | --> | event x users x enabled channels |
| shipped | | -> notifications rows (pending) |
+-------------+ | | +--------+
| workers, one pool per channel | ---> | email |
| claim due rows (SKIP LOCKED) | ---> | push |
| send -> sent / retry later / dead | ---> | SMS |
+---------------------------------------+ +--------+
The event reaches the notification service through a queue or, if it comes from another service's database, through the outbox pattern. Inside the service I keep one table, notifications, which is both the record of what was sent and the work queue for the workers. One row per user per channel per event.
Separate worker pools per channel matter more than they look. If the SMS provider is down and SMS jobs are retrying, email and push carry on. That's a bulkhead, from designing for failure.
The tables
CREATE TABLE IF NOT EXISTS user_channels (
user_id bigint NOT NULL,
channel text NOT NULL CHECK (channel IN ('email', 'push', 'sms')),
address text NOT NULL, -- email address, device token, phone number
enabled boolean NOT NULL DEFAULT true,
PRIMARY KEY (user_id, channel)
);
CREATE TABLE IF NOT EXISTS notifications (
id uuid PRIMARY KEY DEFAULT uuidv7(),
dedupe_key text NOT NULL UNIQUE, -- event id + user + channel
user_id bigint NOT NULL,
channel text NOT NULL,
address text NOT NULL,
template text NOT NULL,
payload jsonb NOT NULL,
status text NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'sent', 'dead')),
attempts int NOT NULL DEFAULT 0,
next_attempt_at timestamptz NOT NULL DEFAULT now(),
last_error text,
created_at timestamptz NOT NULL DEFAULT now(),
sent_at timestamptz
);
CREATE INDEX IF NOT EXISTS notifications_due
ON notifications (channel, next_attempt_at) WHERE status = 'pending';
The dedupe_key is the heart of it only. It's built from the event id, the user and the channel, so the same event can only ever make one row per user per channel. The address is copied into the row on purpose: if the user changes their email a minute later, we still know where this one went.
Fan-out
func FanOut(ctx context.Context, db *pgxpool.Pool, e Event) (int64, error) {
payload, err := json.Marshal(e.Payload)
if err != nil {
return 0, err
}
tag, err := db.Exec(ctx, `
INSERT INTO notifications (dedupe_key, user_id, channel, address, template, payload)
SELECT $1 || ':' || uc.user_id || ':' || uc.channel,
uc.user_id, uc.channel, uc.address, $2, $3
FROM user_channels uc
WHERE uc.user_id = ANY($4) AND uc.channel = ANY($5) AND uc.enabled
ON CONFLICT (dedupe_key) DO NOTHING`,
e.EventID, e.Template, payload, e.UserIDs, e.Channels)
if err != nil {
return 0, err
}
return tag.RowsAffected(), nil
}
The preferences check is just a JOIN-like filter in the SELECT, so the whole fan-out is one statement. The obvious version is a Go loop over users and channels with an insert each. For a thousand users that's three thousand round trips, for a broadcast it's a few million. One INSERT ... SELECT per batch of users is much kinder. For a real broadcast I would page through users in batches of 10,000 or so, so no single statement runs for minutes.
ON CONFLICT DO NOTHING makes fan-out safe to repeat. Events come from queues, queues deliver at least once, so the same "order shipped" will arrive twice one day.
In my test the first fan-out for 1,000 users made 1,567 rows and publishing the exact same event again made none:
notify_test.go:155: fan-out: first=1567 rows, repeat=0 rows
1,000 emails, 500 pushes and 67 SMS. 100 users had a phone number, but 33 of them had switched SMS off, and the filter skipped them without any extra code.
Workers, retries and the dead letter state
Each worker claims a batch of due rows for its channel with FOR UPDATE SKIP LOCKED, the same trick as in the Postgres job queue post. Then for each row it calls the sender and records the result.
func (w *Worker) record(ctx context.Context, tx pgx.Tx, n Notification, sendErr error) error {
attempts := n.Attempts + 1
switch {
case sendErr == nil:
_, err := tx.Exec(ctx, `UPDATE notifications
SET status = 'sent', attempts = $2, sent_at = now(), last_error = NULL
WHERE id = $1`, n.ID, attempts)
return err
case errors.Is(sendErr, ErrPermanent) || attempts >= w.MaxAttempts:
// Dead letter: kept in the same table, visible and replayable.
_, err := tx.Exec(ctx, `UPDATE notifications
SET status = 'dead', attempts = $2, last_error = $3
WHERE id = $1`, n.ID, attempts, sendErr.Error())
return err
default:
_, err := tx.Exec(ctx, `UPDATE notifications
SET attempts = $2, last_error = $3,
next_attempt_at = now() + $4 * interval '1 microsecond'
WHERE id = $1`, n.ID, attempts, sendErr.Error(), w.Backoff(attempts).Microseconds())
return err
}
}
There are three outcomes. Sent. Retry later. Or dead.
Errors come in two kinds and the sender has to say which. A 503 or a timeout is temporary, try again. An invalid email address, a phone number that can't take SMS or a push token the platform says is gone will fail forever, so retrying just burns attempts and provider quota. The sender wraps those in ErrPermanent and they go straight to dead. For push, a gone token should also disable that user_channels row so we stop trying next time.
The backoff is exponential with full jitter:
func (w *Worker) Backoff(attempt int) time.Duration {
d := w.BaseDelay << min(attempt, 20)
if d <= 0 || d > w.MaxDelay {
d = w.MaxDelay
}
return time.Duration(rand.Int64N(int64(d)) + 1)
}
See, without the jitter, a thousand emails that failed together at 9:00:00 all retry together at 9:00:02, hit the same struggling provider, fail together again, and so on. With a random wait between zero and the cap they spread out. I wrote about plain backoff a while ago in exponential backoff in go, this is the same thing with randomness added. In production I'd use something like 30 seconds base, 1 hour cap and 8 attempts. In the tests below it's 5 ms, 200 ms and 5 so the run takes seconds.
The dead letter "queue" here is a status, not a separate queue. I like that. Dead rows stays in the same table with their last error, support can see them, and replaying them is one UPDATE.
Running it against flaky providers
The test creates 1,000 users. Everyone has email, every second user has push, every tenth opted in to SMS, a few turned SMS off again, and every 50th phone number is a landline that can never get an SMS. The fake sender fails 20% of all sends with "provider returned 503" and rejects landlines as permanent. Two email workers, one push, one SMS.
docker run -d --name notify-pg -e POSTGRES_PASSWORD=dev -p 127.0.0.1:5432:5432 postgres:18-alpine
# the test creates a "notify" database on that server
DATABASE_URL=postgres://postgres:dev@127.0.0.1:5432/postgres go test -v -count=1 ./notify
A small confession first. These numbers came from Postgres 18.6 from Postgres.app on the Mac, not the Docker image. Halfway through writing this post Docker on my laptop stopped answering, docker ps itself hung, so I started a throwaway cluster with initdb and pg_ctl on a spare port and pointed the test at it. Same code, same SQL.
notify_test.go:165: drained in 126ms, 1922 send calls
notify_test.go:133: email sent 1000 max attempts 5
notify_test.go:133: push sent 500 max attempts 4
notify_test.go:133: sms dead 14 max attempts 1
notify_test.go:133: sms sent 53 max attempts 4
notify_test.go:174: delivered=1553, delivered more than once=0
1,922 send calls for 1,553 deliveries, so roughly a fifth were retries, which is what a 20% failure rate should give. One unlucky email needed all 5 attempts and got through on last one. The 14 dead SMS are the landlines, each tried exactly once (max attempts 1), because the error was permanent. Nobody got anything twice.
The second test has the email provider down completely. All three emails go dead after 5 attempts. Then the provider "comes back" and I replay only the dead letters that died of a 5xx:
UPDATE notifications
SET status = 'pending', attempts = 0, next_attempt_at = now()
WHERE status = 'dead' AND last_error LIKE 'provider returned 5%';
notify_test.go:133: email dead 3 max attempts 5
notify_test.go:196: replayed 3
notify_test.go:133: email sent 3 max attempts 1
Basically, filtering on last_error matters there. You want to replay the outage, not the landlines.
I ran it a second time and the numbers moved a bit (1,940 calls, 173 ms) because the failures are random, but the sent and dead counts were the same.
Exactly once is a lie, at the edge
The dedupe key stops duplicate rows. It doesn't stop a duplicate send in one case: the worker calls the provider, the provider sends the email, and the worker dies before it records sent. The row is still pending with the lock released, and another worker sends it again. Same shape as the relay crash in the outbox post.
You can't fully close that gap from your side. What helps is passing the notification id to the provider as an idempotency key where the provider supports one, and for push, a collapse key so the phone shows only the latest copy. Keep the batch small too, because a worker holds its row locks and its transaction open while it sends. With 50 rows and a 5 second timeout per send that is fine; with 5,000 rows it is not. A bigger system would claim rows by setting a lease (locked_until) in a short transaction and send outside it.
Trade-offs
Postgres as the queue is the simple choice and it holds up well into hundreds of sends a second, especially since the providers are slower than that anyway. Past that, or if many services publish notifications, put SQS or another broker between fan-out and the workers, one queue per channel. The notifications table then stays as the record and the dedupe check.
Provider rate limits need their own limiter per provider account, shared by all workers. That's the Redis rate limiter again, keyed by provider instead of by API key.
Priority matters once broadcasts exist. An OTP stuck behind a million marketing emails is a broken login. Give transactional and bulk messages separate worker pools, or at least separate channel values like email_tx and email_bulk.
For email itself I use SES, and the SES SMTP with Terraform post covers getting the domain verified and out of the sandbox. Bounces and complaints from SES are the main source of permanent errors, so they should flip enabled off on the address.
Start with the table, the dedupe key and the three outcomes. The rest can come later.