Notifications
Many services want to reach a user. One service decides whether, when and how. The user gets each message once, at a sane hour, on a channel they allow.
- 1Store each request once under its idempotency key, in the same statement that creates its messages. Producer retries and job restarts then add nothing.
- 2Give each channel a queue per priority. A campaign then waits behind sign-in codes, not the other way round.
- 3Treat providers as unreliable: caps before sending, backoff with jitter for transient errors, a dead-letter list for permanent ones, a breaker and a second provider.
- 4Respect the user: preferences, quiet hours and digests decide what is sent before any queue sees it.
"Design a system that sends push, SMS and email to users from many producing services, with rate caps and retries."
| question | answer assumed |
|---|---|
| Who calls it? | About 50 internal services, plus a campaign tool. |
| How many users? | 50 million daily, 200 million in total. |
| How many messages? | 500 million a day: 80% push, 19.5% email, 0.5% SMS. |
| Largest campaign? | Every daily user, 50 million, within 4 hours. |
| How fast is a code? | Handed to the provider within 1 s, even during a campaign. |
| Duplicates? | Never two copies of one notification from our side. |
| In-app inbox? | Out of scope; a follow-up. |
Before I draw anything, I confirm the channels, the volume, how fast a code must arrive, and how large a campaign gets.
| functional |
|---|
| Send a templated message to a user on push, SMS or email. |
| Honour opt-outs per category and channel, and quiet hours. |
| Cap messages per user per channel; batch low-priority ones into digests. |
| Track each message: queued, sent, delivered, capped, dead. |
| Send campaigns to large audiences. |
| non-functional | target |
|---|---|
| Transactional, accept to provider | p99 < 1 s |
| Accept API availability | 99.95% |
| Delivery from our side | At most once per notification and channel |
| Accepted messages lost | 0 |
| Campaign of 50 M | < 4 h |
The hard requirement is isolation: a campaign of 50 million must not delay one sign-in code.
| quantity | arithmetic | result |
|---|---|---|
| Messages | 500 M a day ÷ 86,400 | ≈ 5,800/s; 3× peak ≈ 17,000/s |
| Campaign | 50 M users ÷ (4 h × 3,600) | ≈ 3,500/s on top |
| SMS | 0.5% × 500 M | 2.5 M a day ≈ 29/s |
| Message rows | 500 M × 400 B | 200 GB a day; 30 days ≈ 6 TB |
| A whole campaign queued at once | 50 M × 50.4 B (measured) | ≈ 2.5 GB, so feed it in pages |
| Receipts | one webhook per sent message | ≈ 5,800/s inbound |
| Dispatchers at peak | 17,000 ÷ 6,000 per dispatcher (measured) | 3, run twice that |
Inputs are the assumed answers in panel A. Bytes per queued message and the dispatcher rate were measured on Redis and Postgres in the lab. Method: R2.
About 5,800 messages a second on average and 17,000 at peak. A paced campaign adds about 3,500 a second, so it fits beside the daily traffic.
| call | for | retry safe by | success | errors |
|---|---|---|---|---|
| POST /v1/notifications {user_id, template, data} + Idempotency-Key | send one | the key, unique per producer | 202 + id; 200 + first id on a repeat | 400, 404 template, 422 |
| POST /v1/campaigns {template, audience, start_at, rate} | send to many | the campaign id in each key | 202 + campaign_id | 400, 409 running |
| GET /v1/notifications/{id} | status per channel | a read | 200 | 404 |
| PUT /v1/users/{id}/preferences | opt-outs, quiet hours | PUT is idempotent | 204 | 400 |
| POST /v1/providers/{name}/receipts | delivery receipts | a conditional update | 204 | 401 bad signature |
- Producers name a template and pass data. Only the notification service holds addresses, templates and preferences.
- Receipt webhooks are signed and checked, like any inbound webhook (O6).
Every send carries an idempotency key. A repeat returns the first result and sends nothing new.
| Redis key | holds |
|---|---|
| q:{channel}:{priority} | List of message payloads, oldest first. Nine queues. |
| retry | Sorted set, scored by the time a retry is due. |
| deferred | Sorted set, scored by the end of the user's quiet hours. |
| dg:{user}, dg:due | The user's buffered likes, and when each window closes. |
| rl:{channel:user}:log | Send times in the last window: the cap. |
| dlq:{channel} | Dead letters for review and replay. |
CREATE TABLE recipients (
user_id bigint PRIMARY KEY,
email text,
phone text,
push_token text,
tz_minutes smallint NOT NULL DEFAULT 0, -- offset from UTC
quiet_start smallint1, -- minute of the local day, e.g. 1320 = 22:00
quiet_end smallint -- e.g. 420 = 07:00; the window may wrap midnight
);
CREATE TABLE opt_outs (
user_id bigint NOT NULL REFERENCES recipients (user_id),
category text NOT NULL, -- security, orders, social, marketing
channel text NOT NULL, -- push, sms, email
PRIMARY KEY (user_id, category, channel)
);
CREATE TABLE templates (
name text NOT NULL,
channel text NOT NULL,
category text NOT NULL,
priority text NOT NULL, -- transactional, social, bulk
body text NOT NULL, -- "Your code is {{code}}"
PRIMARY KEY (name, channel)
);
CREATE TABLE notifications (
id bigserial PRIMARY KEY,
producer text NOT NULL,
idem_key text NOT NULL,
user_id bigint NOT NULL,
template text NOT NULL,
created_at timestamptz NOT NULL,
UNIQUE (producer, idem_key)2 -- a retried request finds this row and stops
);
CREATE TABLE messages (
id bigserial PRIMARY KEY,
notification_id bigint NOT NULL REFERENCES notifications (id),
channel text NOT NULL,
priority text NOT NULL,
status text NOT NULL, -- queued, deferred, buffered, sent, delivered,
-- capped, dead, digested
body text NOT NULL,
provider text,
attempts int NOT NULL DEFAULT 0,
digest_id bigint4 REFERENCES messages (id),
release_at timestamptz, -- deferred by quiet hours until this time
sent_at timestamptz,
delivered_at timestamptz,
UNIQUE (notification_id, channel)3
);
CREATE INDEX messages_open ON messages (status, release_at) WHERE status IN ('queued', 'deferred')5;- 1Quiet hours in the user's local time. The offset turns them into UTC at send time.
- 2The idempotency check. Two producers may use the same key without a clash.
- 3At most one message per channel per notification.
- 4A folded like points at the digest message that carried it.
- 5A small partial index: the sweeper finds open messages without scanning sent ones.
A notification is one request, unique by producer and key. A message is one channel of it, and it carries the status.
Step 1: Accept
- A producer posts user, template, data and an Idempotency-Key.
- One statement inserts the notification and one message per channel. A repeated key inserts nothing.
- Return 202 with the ID, or 200 with the first ID for a repeat.
If it fails
Postgres is down: return 503; the producer retries with the same key. The repeat finds the row and stops.
The API stores and routes; Redis holds the queues and schedules; dispatchers send through providers and write outcomes back to Postgres.
| tool | capability | what it gives this design | also used for |
|---|---|---|---|
| Postgres | UNIQUE key with INSERT ... ON CONFLICT DO NOTHING | Idempotency in the insert itself. No read-then-write race. | Payments, any API with keys |
| Postgres | Data-modifying CTEs: INSERT ... RETURNING feeds the next INSERT | Notification and messages in one statement. A repeat inserts neither. | Outbox rows with their change |
| Postgres | UPDATE ... FROM unnest(arrays) | Every status change of a tick in one statement. | Bulk updates from a batch job |
| Postgres | Conditional UPDATE (WHERE status = 'sent') | Repeated receipts change nothing. | State machines |
| Postgres | Partial index; partitions by day | The sweeper reads open rows only; old days drop as whole partitions. | Job tables, logs |
| Redis | Lists: RPUSH, LPOP with a count | A queue per channel and priority; one round trip pops a batch. | Work queues (B6) |
| Redis | Sorted sets scored by time; ZRANGE BYSCORE | Retries, quiet-hours holds and digest windows, all released by time. | Delay queues, schedulers |
| Redis | Lua script: sliding log | An exact cap per user and channel, checked and counted in one call. | API rate limits (B3) |
| Service | Circuit breaker; backoff with full jitter | A failing provider gets probes, not traffic; retries spread out. | Any remote call (O2) |
| Providers | Two per channel; an idempotency key where offered | Failover; a repeat of one message ID is not sent twice. | Payments, shipping |
Postgres gives me idempotency and status in single statements. Redis gives me queues, schedules by time, and an atomic cap check.
| design | during a campaign | status |
|---|---|---|
| One FIFO queue per channel | Codes wait behind the campaign: p99 18.6 s in the lab. | Not approved |
| A queue per priority, strict order | Codes first. A long busy hour can stall bulk. | Low transactional load |
| A queue per priority, bulk keeps a share | Codes p99 200 ms; campaign done at 28.7 s, not 26.0 s. | Approved |
| Separate dispatchers and provider accounts for bulk | Full isolation, also of provider throttles. | At large scale |
| Enqueue the whole audience at once | 2.5 GB of Redis for 50 M users. | Not approved |
| Page the audience at the send rate | The bulk backlog stays a few pages long. | Approved |
- Room per tick is the sum of the providers whose breaker is not open. A slow provider shrinks the room; it does not grow the queue of codes.
- Many tenants or teams sharing bulk room need fair shares between them (O6).
take(channel, room): // once a tick1
reserve = bulk waiting ? max(1, room x 10%)2 : 0
FOR priority IN transactional, social, bulk3:
want = room - taken
IF priority != bulk: want = want - reserve
taken += LPOP q:{channel}:{priority} want4
RETURN taken- 1A tick is 100 ms in the lab. Room per tick is what the providers accept in that time.
- 2Bulk always moves while it waits, so a campaign finishes even in a busy hour.
- 3Highest first. Codes never wait behind likes or campaigns.
- 4LPOP with a count: one round trip pops a batch from one list.
Tested source Go: take
// take pops up to room messages of one channel. With a queue per priority, transactional goes
// first, then social, then bulk; bulk keeps a small share while it waits. With one shared queue,
// messages leave in arrival order, whatever their priority.
func (d *Dispatcher) take(ctx context.Context, ch string, room int) ([]Msg, error) {
if room <= 0 {
return nil, nil
}
if d.S.SharedQueue {
return d.pop(ctx, d.S.Keys.Queue(ch, "all"), room)
}
reserve := 0
if d.S.waitingIn(ch, Bulk) > 0 {
reserve = max(1, int(float64(room)*d.BulkShare))
}
var out []Msg
for _, p := range Priorities {
n := room - len(out)
if p != Bulk {
n -= reserve
}
if n <= 0 {
continue
}
got, err := d.pop(ctx, d.S.Keys.Queue(ch, p), n)
if err != nil {
return nil, err
}
out = append(out, got...)
}
return out, nil
}
I give each channel a queue per priority and pop transactional first, with 10% of the room kept for bulk. In the lab that held code p99 at 200 ms during a campaign.
See it: a campaign, an outage, a flood
recorded: 3,000 users, 60 s on a virtual clock, real Postgres and Redis| second 12 to 13 | value |
|---|---|
| Waiting: transactional / social / bulk | 43 / 0 / 1,306 |
| Transactional sent; p99 | 10; < 0.1 s |
| Sent: push / sms-a / sms-b | 15 / 5 / 0 |
| Sent: email-a / email-b | 0 / 99 |
| email-a breaker | open |
| Failed calls, scheduled for retry | 0 |
| Capped / dead letters / folded into digests | 0 / 1 / 25 |
- Campaign job starts: 3,000 users, 500 a page.
- Campaign job crashes after 3 pages and restarts from page 1.
- The idempotency key drops 1,500 repeated campaign requests.
- Provider email-a starts to fail every call.
- The email-a breaker opens. Email fails over to email-b.
- A probe call fails. The email-a breaker stays open 5 s more.
- Order burst: 100 orders in 1 s.
- A probe call fails. The email-a breaker stays open 5 s more.
- A probe call fails. The email-a breaker stays open 5 s more.
- The campaign queues are empty.
- One producer sends 20 codes to one user in 2 s. The cap lets 3 through.
- Provider email-a recovers.
- 3 probe calls succeed. The email-a breaker closes.
| whole run, both designs | One queue per channel | A queue per priority |
|---|---|---|
| Transactional p50 / p99 / max | < 0.1 s / 18.6 s / 19.6 s | < 0.1 s / 200 ms / 200 ms |
| Campaign queues empty at | 26.0 s | 28.7 s |
| Messages delivered twice | 0 | 0 |
| Most sends to one user in 60 s: push / sms / email | 6 / 3 / 4 (caps 6 / 3 / 4) | 6 / 3 / 4 (caps 6 / 3 / 4) |
| Interrupting messages in quiet hours | 0 (441 held until 07:00) | 0 (441 held until 07:00) |
7,148 requests, 1,566 of them repeats that the idempotency key dropped. 1,064 likes went out as 183 digests. The flood user got 3 of 20 codes. During the outage, email-a saw 13 calls in 20 s.
Same traffic in both runs: 7,148 requests from 4 producers, a campaign at 5 s, 100 orders at 20 s, and 20 codes to one user at 30 s. A tenth of codes and orders are sent twice by their producer. Providers: push 400/s, SMS 2 × 50/s, email 150/s and 100/s. After each run the lab checks four things. No message went out twice, and no cap was exceeded in any 60 s window. Nothing that rings went out in quiet hours, and no message stayed queued.
With one queue, the campaign pushed code latency to many seconds. With a queue per priority, codes stayed under the target, and every invariant held in both runs.
| a repeat comes from | what stops it | lab |
|---|---|---|
| A producer retries after a timeout | UNIQUE (producer, idem_key) | 66 dropped |
| The campaign job restarts from page 1 | Key = campaign:user | 1,500 dropped |
| A dispatcher crashes after popping | Status stays queued; the sweeper pushes it again once | not run |
| A provider sends a receipt twice | UPDATE ... WHERE status = 'sent' | 364 ignored |
| A provider accepts, then times out; failover sends again | Message ID as the provider's key; the client drops a seen ID | not run |
- Exactly once to the device is not possible across providers. Deliver at least once and drop repeats by ID (T9).
- Keep the key per producer: two services may both use "order-17".
accept(producer, key, user, template, data):
INSERT notification (producer, key) ON CONFLICT DO NOTHING1
IF no row inserted: RETURN 200 + the first id // a repeat
FOR EACH channel of the template, unless opted out2:
status = deferred IF quiet hours AND it can wake the user3
buffered IF priority = social // digest
queued otherwise
INSERT message (channel, status, rendered body) // same statement4
after commit5: RPUSH q:{channel}:{priority} msg // or a schedule
RETURN 202 + id- 1The insert is the check. Two concurrent repeats race on the unique index, and one wins.
- 2Opt-outs are a NOT EXISTS in the same statement, per category and channel.
- 3Push and SMS, except security messages. Email waits in an inbox.
- 4A data-modifying CTE. A repeated key inserts no notification, so it inserts no messages.
- 5Redis sees only what Postgres stored. A crash before the push leaves a queued row for the sweeper.
Tested source Go: accept · SQL: accept
// Accept stores requests that share one template (one request, or one page of a campaign) and
// routes each new message: to quiet hours, to a digest window, or to its queue. Postgres decides
// what is new; Redis only ever sees messages that Postgres stored.
func (s *Service) Accept(ctx context.Context, now time.Time, producer, template string, reqs []Request) (Accepted, error) {
tpl, ok := s.templates[template]
if !ok {
return Accepted{}, fmt.Errorf("accept: unknown template %q", template)
}
var (
keys, chKeys, channels, bodies, statuses []string
users []int64
releases []*time.Time
)
for _, r := range reqs {
rc, ok := s.recipients[r.User]
if !ok {
return Accepted{}, fmt.Errorf("accept: unknown user %d", r.User)
}
keys, users = append(keys, r.Key), append(users, r.User)
quiet, until := QuietUntil(rc, now)
for _, t := range tpl {
status, release := StatusQueued, (*time.Time)(nil)
switch {
case quiet && Interrupts(t.Channel, t.Category):
status, release = StatusDeferred, &until
case t.Priority == Social:
status = StatusBuffered
}
chKeys, channels = append(chKeys, r.Key), append(channels, t.Channel)
bodies, statuses = append(bodies, Render(t.Body, r.Data)), append(statuses, status)
releases = append(releases, release)
}
}
rows, err := s.DB.Query(ctx, Q("accept"), producer, keys, users, template, now,
tpl[0].Priority, chKeys, channels, bodies, statuses, releases, tpl[0].Category)
if err != nil {
return Accepted{}, fmt.Errorf("accept %s: %w", template, err)
}
defer rows.Close()
var out Accepted
seen := map[int64]bool{}
release := map[int64]time.Time{}
for rows.Next() {
var nid, user, mid int64
var channel, status string
if err := rows.Scan(&nid, &user, &mid, &channel, &status); err != nil {
return Accepted{}, fmt.Errorf("scan accepted: %w", err)
}
if !seen[nid] {
seen[nid] = true
out.Fresh++
}
if mid == 0 {
continue // opted out of every channel
}
m := Msg{ID: mid, User: user, Channel: channel, Priority: tpl[0].Priority, Category: tpl[0].Category, Accepted: now.UnixMilli()}
out.Messages = append(out.Messages, m)
if status == StatusDeferred {
_, until := QuietUntil(s.recipients[user], now)
release[mid] = until
}
}
if err := rows.Err(); err != nil {
return Accepted{}, fmt.Errorf("accept %s: %w", template, err)
}
out.Dups = len(reqs) - out.Fresh
pipe := s.RDB.Pipeline()
for _, m := range out.Messages {
switch until, deferred := release[m.ID]; {
case deferred:
pipe.ZAdd(ctx, s.Keys.Deferred(), redis.Z{Score: float64(until.UnixMilli()), Member: m.Encode()})
out.Deferred++
case m.Priority == Social:
pipe.RPush(ctx, s.Keys.Digest(m.User), m.Encode())
pipe.ZAddNX(ctx, s.Keys.DigestDue(), redis.Z{Score: float64(now.Add(s.DigestWindow).UnixMilli()), Member: m.User})
out.Buffered++
default:
pipe.RPush(ctx, s.queueOf(m), m.Encode())
s.waiting(m, 1)
out.Queued++
}
}
if len(out.Messages) == 0 {
return out, nil
}
if _, err := pipe.Exec(ctx); err != nil {
return Accepted{}, fmt.Errorf("route accepted messages: %w", err)
}
return out, nil
}
-- One statement per request, or per campaign page. Inserting into notifications is the idempotency
-- check: a repeated (producer, idem_key) inserts no row, so it gets no messages either. A message
-- is skipped when the user opted out of this category on that channel.
WITH a AS (
SELECT * FROM unnest($2::text[], $3::bigint[]) AS a (k, u)
), n AS (
INSERT INTO notifications (producer, idem_key, user_id, template, created_at)
SELECT $1, k, u, $4, $5 FROM a
ON CONFLICT (producer, idem_key) DO NOTHING
RETURNING id, user_id, idem_key
), ins AS (
INSERT INTO messages (notification_id, channel, priority, status, body, release_at)
SELECT n.id, c.channel, $6, c.status, c.body, c.release_at
FROM n JOIN unnest($7::text[], $8::text[], $9::text[], $10::text[], $11::timestamptz[])
AS c (k, channel, body, status, release_at) ON c.k = n.idem_key
WHERE NOT EXISTS (
SELECT 1 FROM opt_outs o
WHERE o.user_id = n.user_id AND o.category = $12 AND o.channel = c.channel
)
RETURNING id, notification_id, channel, status
)
SELECT n.id, n.user_id, coalesce(ins.id, 0), coalesce(ins.channel, ''), coalesce(ins.status, '')
FROM n LEFT JOIN ins ON ins.notification_id = n.id
ORDER BY n.id, ins.id;I stop repeats at the insert with a unique key. The one duplicate I cannot stop is a provider that accepted and then timed out, so I pass it the message ID.
send(msg):
IF first attempt AND NOT cap.allow(user, channel):1
mark capped; RETURN // never sent
FOR EACH provider IN failover order:
IF no room this tick OR breaker open2: NEXT
result = provider.send(msg, key = msg.id3)
breaker.record(result is not transient4)
IF ok: mark sent
ELSE IF permanent OR attempts = 6: mark dead; RPUSH dlq
ELSE: ZADD retry now + random(0, min(8 s, 250 ms x 2^n))5
RETURN
push msg back to the head of its queue6 // no provider had room- 1A sliding log in Redis: at most 3 SMS, 6 push and 4 emails per user per 60 s in the lab.
- 2Opens at 50% failures over 10 or more calls; probes after 5 s.
- 3Where the provider offers an idempotency key, a resend of one ID is not sent twice.
- 4A permanent error is the address's fault, not the provider's. It does not count against the breaker.
- 5Full jitter: retries from many dispatchers spread out instead of arriving together.
- 6No provider had room this tick. The message keeps its place.
Tested source Go: send
// send caps, routes and sends one message. It returns false when no provider had room, so the
// caller puts the message back at the head of its queue.
func (d *Dispatcher) send(ctx context.Context, m Msg, now time.Time, st *TickStats, out *outcome) (bool, error) {
ms := now.UnixMilli()
if m.Attempts == 0 { // a retry was admitted by the cap already
dec, err := d.Caps[m.Channel].Allow(ctx, d.S.Keys.Prefix+m.Channel+":"+strconv.FormatInt(m.User, 10), now)
if err != nil {
return false, fmt.Errorf("cap %s for user %d: %w", m.Channel, m.User, err)
}
if !dec.Allowed {
out.add(m, StatusCapped, "", 0)
st.Capped++
return true, nil
}
}
for _, r := range d.Routes[m.Channel] { // failover order
if r.Provider.Room(ms) <= 0 {
continue
}
ticket, err := r.Breaker.Allow(now)
if err != nil {
continue // breaker open: try the next provider
}
err = r.Provider.Send(m, ms)
st.Tried[r.Provider.Name]++
r.Breaker.Record(ticket, now, !errors.Is(err, ErrTransient))
attempts := m.Attempts + 1
switch {
case err == nil:
out.add(m, StatusSent, r.Provider.Name, attempts)
st.Sent[r.Provider.Name]++
if m.Priority == Transactional {
st.TxLatency = append(st.TxLatency, ms-m.Accepted)
}
case errors.Is(err, ErrPermanent) || attempts >= d.MaxAttempts:
out.add(m, StatusDead, r.Provider.Name, attempts)
st.Dead++
if err := d.S.RDB.RPush(ctx, d.S.Keys.Dead(m.Channel), m.Encode()).Err(); err != nil {
return false, fmt.Errorf("dead-letter %d: %w", m.ID, err)
}
default: // transient: retry later, with capped exponential backoff and full jitter
st.Failed++
m.Attempts = attempts
due := ms + max(d.Backoff.Delay(attempts, d.Rand).Milliseconds(), 1)
if err := d.S.RDB.ZAdd(ctx, d.S.Keys.Retry(), redis.Z{Score: float64(due), Member: m.Encode()}).Err(); err != nil {
return false, fmt.Errorf("schedule retry of %d: %w", m.ID, err)
}
out.add(m, StatusQueued, r.Provider.Name, attempts)
}
return true, nil
}
return false, nil
}
| result | action |
|---|---|
| 2xx accepted | Mark sent; wait for a receipt. |
| Timeout, 5xx, 429 | Retry with backoff and jitter. |
| Invalid number, hard bounce, expired token | Dead-letter now; flag the address. |
| 6 failed attempts | Dead-letter; alert on the rate. |
| Breaker open | Next provider in failover order. |
| Every breaker open | Stay queued; probes test recovery. |
| choice | status |
|---|---|
| Retry at once, no backoff | Not approved |
| Retry permanent errors | Not approved |
| Backoff with full jitter, capped | Approved |
| Failover on a breaker, not on one error | Approved |
| Fail over SMS codes on a timeout | A late code is useless anyway |
Lab: email-a failed every call from 10 s to 30 s. It saw 13 calls; email-b sent 1,870. 41 messages to bad addresses were dead-lettered, none from the outage.
I retry only transient errors, with jitter, 6 attempts at most. Permanent errors go to the dead-letter list at once. A breaker moves traffic to the second provider.
| rule | where it runs | lab result |
|---|---|---|
| Opt-out per category and channel | Accept, in the insert | No message row |
| Quiet hours for push and SMS | Accept: hold until the local end | 441 held, 0 sent early |
| Digest of social messages | Accept: buffer; dispatcher: fold | 1,064 likes in 183 pushes |
| Cap per user per channel | Dispatcher, first attempt | Flood user: 3 of 20 codes |
| Security messages | Skip quiet hours and digests; keep the cap | Codes at 23:00 local |
- Check the cap at send time, not at accept. A message that waited in a queue still counts when it reaches the user.
- A sliding log is exact and holds one entry per send; a sliding counter is cheaper and approximate (B3).
quiet(user, now):
local = now + user.tz
IF local in [quiet_start, quiet_end): // may wrap midnight1
RETURN true, quiet_end in UTC
can_wake(channel, category):
RETURN channel != email AND category != security2
flush(users whose window closed):
items = LRANGE dg:{user}; DEL dg:{user}
IF one item: queue it as it is3
ELSE: INSERT one digest "N new likes"; mark items digested4- 122:00 to 07:00 crosses midnight, so the test is start or end, not start and end.
- 2Only messages that ring wait. A sign-in code must arrive at 03:00.
- 3A digest of one reads worse than the original.
- 4Each like keeps a row that points at the digest, so status queries still answer.
Tested source Go: quiet hours · Go: digests
// QuietUntil reports whether now falls in the recipient's quiet hours, and when they end. The
// window is in the user's local time and may wrap midnight (22:00 to 07:00).
func QuietUntil(r Recipient, now time.Time) (bool, time.Time) {
if r.QuietStart < 0 || r.QuietEnd < 0 || r.QuietStart == r.QuietEnd {
return false, time.Time{}
}
local := now.Add(time.Duration(r.TZMinutes) * time.Minute)
minute := local.Hour()*60 + local.Minute()
in := minute >= r.QuietStart && minute < r.QuietEnd // same-day window
if r.QuietStart > r.QuietEnd {
in = minute >= r.QuietStart || minute < r.QuietEnd // wraps midnight
}
if !in {
return false, time.Time{}
}
midnight := time.Date(local.Year(), local.Month(), local.Day(), 0, 0, 0, 0, time.UTC)
end := midnight.Add(time.Duration(r.QuietEnd) * time.Minute)
if !end.After(local) {
end = end.AddDate(0, 0, 1)
}
return true, end.Add(-time.Duration(r.TZMinutes) * time.Minute)
}
// Interrupts reports whether a message on this channel can wake the user. Email waits in an inbox;
// security messages (sign-in codes, alerts) go out at any hour.
func Interrupts(channel, category string) bool {
return channel != "email" && category != "security"
}
// flushDigests closes every digest window that is due. One buffered message goes out as it is;
// two or more become one digest message, and the originals are marked as folded into it.
func (d *Dispatcher) flushDigests(ctx context.Context, now time.Time, st *TickStats, out *outcome) error {
ms := now.UnixMilli()
users, err := d.S.RDB.ZRangeArgsWithScores(ctx, redis.ZRangeArgs{Key: d.S.Keys.DigestDue(), Start: "-inf", Stop: ms, ByScore: true}).Result()
if err != nil {
return fmt.Errorf("read due digests: %w", err)
}
for _, z := range users {
user, err := strconv.ParseInt(z.Member.(string), 10, 64)
if err != nil {
return fmt.Errorf("digest user %v: %w", z.Member, err)
}
key := d.S.Keys.Digest(user)
pipe := d.S.RDB.TxPipeline()
items := pipe.LRange(ctx, key, 0, -1)
pipe.Del(ctx, key)
pipe.ZRem(ctx, d.S.Keys.DigestDue(), z.Member)
if _, err := pipe.Exec(ctx); err != nil {
return fmt.Errorf("take digest of %d: %w", user, err)
}
var msgs []Msg
var ids []int64
for _, s := range items.Val() {
m, err := Decode(s)
if err != nil {
return err
}
msgs, ids = append(msgs, m), append(ids, m.ID)
}
if len(msgs) == 1 {
out.add(msgs[0], StatusQueued, "", 0)
if err := d.enqueue(ctx, msgs[0]); err != nil {
return err
}
continue
}
window := strconv.FormatInt(user, 10) + ":" + strconv.FormatInt(int64(z.Score), 10)
body := fmt.Sprintf("%d new likes on your posts", len(msgs))
var id, folded int64
if err := d.S.DB.QueryRow(ctx, Q("digest"), window, user, now, body, ids).Scan(&id, &folded); err != nil {
return fmt.Errorf("fold digest of %d: %w", user, err)
}
st.Digests++
st.Folded += int(folded)
if err := d.enqueue(ctx, Msg{ID: id, User: user, Channel: "push", Priority: Social, Category: "social", Accepted: ms}); err != nil {
return err
}
}
return nil
}
Preferences and quiet hours decide before the queue; caps decide at send time; digests turn many low-value messages into one.
| event | result | why it is safe | saved by |
|---|---|---|---|
| A producer retries a request | The same key arrives again. | The insert finds the key and adds nothing; the API returns the first ID. | Unique key |
| The campaign job crashes mid-audience | It restarts from page 1. | Keys repeat, so already-stored users are skipped. | Unique key |
| The API crashes after commit, before RPUSH | A stored message is in no queue. | The sweeper finds queued rows older than a minute and pushes them. | Partial index |
| Redis loses its data | Queues and schedules are gone. | Every open message is a row in Postgres; rebuild queues and schedules from it. | Rebuild |
| A provider fails every call | Calls fail fast. | The breaker opens; the second provider takes the room; retries wait with jitter. | Breaker |
| A bug floods one user | Many distinct keys for one user. | The cap admits 3 SMS per window; the rest are capped and counted. | Sliding log |
| A campaign starts during peak | Bulk backlog grows. | Transactional is popped first; bulk keeps its share and finishes later. | Queue per priority |
| A receipt arrives twice, or never | Status is unclear. | The update runs once; missing receipts are counted per provider. | Conditional update |
| step | add | it handles | move up when you see |
|---|---|---|---|
| 1 | One Postgres: messages as a queue table, workers claim with SKIP LOCKED (B6). | Thousands a second; accept ran at about 9,600 requests a second in the lab. | Claims and status updates take most of the primary's writes. |
| 2 | Redis queues per channel and priority, caps as scripts. | About 6,000 messages a second per dispatcher; add dispatchers per channel. | The first provider outage, or one provider's throttle. |
| 3 | Breakers, backoff and a second provider per channel. | A provider outage costs a few failed calls, not a backlog. | Campaigns compete with daily traffic. |
| 4 | Paced campaigns: pages of 500, bulk share, separate provider accounts. | About 43,000 notifications a second into Postgres in pages. | One Postgres or one Redis passes its write rate. |
| 5 | Shard by user: Postgres partitions and Redis Cluster, one dispatcher group per shard (X2). | This prompt needs about 17,000 a second at peak and 6 TB for 30 days. | Top of the ladder. |
Demand from panel C. Capacity measured in the lab on one shared laptop: 8 clients for accept, 4 workers for pages, median of 3 runs of 2 s. One dispatcher makes one cap call per message. Read these as orders of magnitude.
I start with a Postgres table as the queue. I move queues to Redis when the dispatch rate needs it, and add a second provider before the first outage.
| question | answer | deeper |
|---|---|---|
| A provider limits you to 100 sends a second. How do you respect it? | Put a token bucket per provider account in front of its sends. The dispatcher's room per tick is the bucket's tokens. | C2 |
| Can you promise exactly once to the device? | No: a provider can accept and then time out. Send at least once with a stable ID and let the client drop repeats. | T9 |
| How do you send a campaign at 09:00 in each user's time zone? | Group the audience by offset and start one paced page job per group. Each job's pages carry the same campaign keys. | B6 |
| Users want an in-app inbox with unread counts. | Write an inbox row per user as another channel. The unread count is a counter per user, updated with the row. | D3 |
| The app is open. Can you skip the push? | Yes: check presence first and deliver over the open socket instead. | C6 |
| Marketing wants open and click rates. | Stream receipts, opens and clicks as events, and count them in windows per campaign. | B7 |
| How do you know the system is healthy? | Track queue age per priority, provider error rate, breaker state and dead-letter rate. Alert on the age of the oldest code. | O3 |
0 of 10 known
A campaign to every user starts while sign-in codes keep arriving. What do the codes wait behind with one queue per channel?
Strict priority can starve bulk. How do you keep a campaign moving during a busy hour?
A producer times out and sends the same request again. What stops a second message?
The campaign job crashes after 3 pages and restarts from page 1. What happens to the first 1,500 users?
Why does a cap check run only on the first attempt?
Which failures do you retry, and which go to the dead-letter list at once?
An email provider fails every call for 20 s. How many calls does it get, and where does email go?
Can failover deliver one message twice?
A user gets 40 likes in 10 s. What reaches their phone?
A user is asleep at 23:00 local. Which messages wake them?
- demand
- About 5,800 messages a second, 17,000 at peak.
- campaign
- 50 M in 4 h is about 3,500 a second.
- isolation
- Code p99 18.6 s with one queue; 200 ms with a queue per priority (lab).
- repeats
- 1,566 of 7,148 requests dropped by the key; 0 double deliveries.
- outage
- 13 calls to a provider down for 20 s, behind a breaker.
- queue
- 50.4 B of Redis per queued message.
- dispatch
- About 6,000 messages a second per dispatcher.
Postgres 16 and Redis 8 on an 8-core laptop shared with other runs. The run uses a virtual clock with 100 ms ticks, seed 7.