System Design

C7

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.

Not startedSaved in this browser only.
  1. 1Store each request once under its idempotency key, in the same statement that creates its messages. Producer retries and job restarts then add nothing.
  2. 2Give each channel a queue per priority. A campaign then waits behind sign-in codes, not the other way round.
  3. 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.
  4. 4Respect the user: preferences, quiet hours and digests decide what is sent before any queue sees it.
C7
    A

    The prompt

    as the interviewer says it
    "Design a system that sends push, SMS and email to users from many producing services, with rate caps and retries."
    questionanswer 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.

    B

    Requirements

    as numbers
    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-functionaltarget
    Transactional, accept to providerp99 < 1 s
    Accept API availability99.95%
    Delivery from our sideAt most once per notification and channel
    Accepted messages lost0
    Campaign of 50 M< 4 h

    The hard requirement is isolation: a campaign of 50 million must not delay one sign-in code.

    C

    Estimates

    the arithmetic, on the board
    quantityarithmeticresult
    Messages500 M a day ÷ 86,400≈ 5,800/s; 3× peak ≈ 17,000/s
    Campaign50 M users ÷ (4 h × 3,600)≈ 3,500/s on top
    SMS0.5% × 500 M2.5 M a day ≈ 29/s
    Message rows500 M × 400 B200 GB a day; 30 days ≈ 6 TB
    A whole campaign queued at once50 M × 50.4 B (measured)≈ 2.5 GB, so feed it in pages
    Receiptsone webhook per sent message≈ 5,800/s inbound
    Dispatchers at peak17,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.

    D

    API

    endpoints, status codes, retries
    callforretry safe bysuccesserrors
    POST /v1/notifications {user_id, template, data} + Idempotency-Keysend onethe key, unique per producer202 + id; 200 + first id on a repeat400, 404 template, 422
    POST /v1/campaigns {template, audience, start_at, rate}send to manythe campaign id in each key202 + campaign_id400, 409 running
    GET /v1/notifications/{id}status per channela read200404
    PUT /v1/users/{id}/preferencesopt-outs, quiet hoursPUT is idempotent204400
    POST /v1/providers/{name}/receiptsdelivery receiptsa conditional update204401 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.

    E

    Data model

    Postgres is the truth, Redis moves the work
    the truth: five tables in Postgres1 : n1 : n1 : nrendersrecipientsPKuser_idemailphonepush_tokentz_minutesquiet_startlocalquiet_endlocalopt_outsPK FKuser_idPKcategoryPKchannela row = no messages herenotificationsPKidUQproducerUQidem_keyFKuser_idtemplateUNIQUE (producer, idem_key)templatesPKnamePKchannelcategoryprioritybody{{vars}}messagesPKidFKnotification_idchannelprioritystatusproviderattemptsFKdigest_idrelease_atquietUNIQUE (notification_id, channel)
    Redis keyholds
    q:{channel}:{priority}List of message payloads, oldest first. Nine queues.
    retrySorted set, scored by the time a retry is due.
    deferredSorted set, scored by the end of the user's quiet hours.
    dg:{user}, dg:dueThe user's buffered likes, and when each window closes.
    rl:{channel:user}:logSend times in the last window: the cap.
    dlq:{channel}Dead letters for review and replay.
    recipients, opt-outs, templates, notifications, messagessql
    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;
    1. 1Quiet hours in the user's local time. The offset turns them into UTC at send time.
    2. 2The idempotency check. Two producers may use the same key without a clash.
    3. 3At most one message per channel per notification.
    4. 4A folded like points at the digest message that carried it.
    5. 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.

    F

    The architecture

    click a step; its path lights up
    Producers50 servicesCampaign jobpages of 500Notification APIaccept, routeReceipt webhookfrom providersRedisqueues, schedules, capsDispatchersone loop per channelPostgresnotifications, messagesProviderspush, SMS, email

    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.

    G

    Capabilities used

    what each tool gives you
    toolcapabilitywhat it gives this designalso used for
    PostgresUNIQUE key with INSERT ... ON CONFLICT DO NOTHINGIdempotency in the insert itself. No read-then-write race.Payments, any API with keys
    PostgresData-modifying CTEs: INSERT ... RETURNING feeds the next INSERTNotification and messages in one statement. A repeat inserts neither.Outbox rows with their change
    PostgresUPDATE ... FROM unnest(arrays)Every status change of a tick in one statement.Bulk updates from a batch job
    PostgresConditional UPDATE (WHERE status = 'sent')Repeated receipts change nothing.State machines
    PostgresPartial index; partitions by dayThe sweeper reads open rows only; old days drop as whole partitions.Job tables, logs
    RedisLists: RPUSH, LPOP with a countA queue per channel and priority; one round trip pops a batch.Work queues (B6)
    RedisSorted sets scored by time; ZRANGE BYSCORERetries, quiet-hours holds and digest windows, all released by time.Delay queues, schedulers
    RedisLua script: sliding logAn exact cap per user and channel, checked and counted in one call.API rate limits (B3)
    ServiceCircuit breaker; backoff with full jitterA failing provider gets probes, not traffic; retries spread out.Any remote call (O2)
    ProvidersTwo per channel; an idempotency key where offeredFailover; 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.

    H

    Deep dive: queues and priority

    who waits behind whom
    designduring a campaignstatus
    One FIFO queue per channelCodes wait behind the campaign: p99 18.6 s in the lab.Not approved
    A queue per priority, strict orderCodes first. A long busy hour can stall bulk.Low transactional load
    A queue per priority, bulk keeps a shareCodes p99 200 ms; campaign done at 28.7 s, not 26.0 s.Approved
    Separate dispatchers and provider accounts for bulkFull isolation, also of provider throttles.At large scale
    Enqueue the whole audience at once2.5 GB of Redis for 50 M users.Not approved
    Page the audience at the send rateThe 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).
    pop one tick of workpseudo code
    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
    1. 1A tick is 100 ms in the lab. Room per tick is what the providers accept in that time.
    2. 2Bulk always moves while it waits, so a campaign finishes even in a busy hour.
    3. 3Highest first. Codes never wait behind likes or campaigns.
    4. 4LPOP with a count: one round trip pops a batch from one list.
    Tested source Go: take
    Go: takego
    
    // 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.

    I

    See it: a campaign, an outage, a flood

    recorded: 3,000 users, 60 s on a virtual clock, real Postgres and Redis
    email-a downmessages waiting in Redis queues (log)1101001k10ktransactional p99, accept to provider (log)100 ms1 s10 starget 1 semail sends a second, by provider0100200breaker0 s10 s20 s30 s40 s50 s60 s
    transactional waitingbulk waiting (dashed) p99 within 1 s p99 above 1 s, or breaker openemail-a solid, email-b dashed
    second 12 to 13value
    Waiting: transactional / social / bulk43 / 0 / 1,306
    Transactional sent; p9910; < 0.1 s
    Sent: push / sms-a / sms-b15 / 5 / 0
    Sent: email-a / email-b0 / 99
    email-a breakeropen
    Failed calls, scheduled for retry0
    Capped / dead letters / folded into digests0 / 1 / 25
    1. Campaign job starts: 3,000 users, 500 a page.
    2. Campaign job crashes after 3 pages and restarts from page 1.
    3. The idempotency key drops 1,500 repeated campaign requests.
    4. Provider email-a starts to fail every call.
    5. The email-a breaker opens. Email fails over to email-b.
    6. A probe call fails. The email-a breaker stays open 5 s more.
    7. Order burst: 100 orders in 1 s.
    8. A probe call fails. The email-a breaker stays open 5 s more.
    9. A probe call fails. The email-a breaker stays open 5 s more.
    10. The campaign queues are empty.
    11. One producer sends 20 codes to one user in 2 s. The cap lets 3 through.
    12. Provider email-a recovers.
    13. 3 probe calls succeed. The email-a breaker closes.
    whole run, both designsOne queue per channelA 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 at26.0 s28.7 s
    Messages delivered twice00
    Most sends to one user in 60 s: push / sms / email6 / 3 / 4 (caps 6 / 3 / 4)6 / 3 / 4 (caps 6 / 3 / 4)
    Interrupting messages in quiet hours0 (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.

    J

    Deep dive: duplicates

    where a second copy comes from
    a repeat comes fromwhat stops itlab
    A producer retries after a timeoutUNIQUE (producer, idem_key)66 dropped
    The campaign job restarts from page 1Key = campaign:user1,500 dropped
    A dispatcher crashes after poppingStatus stays queued; the sweeper pushes it again oncenot run
    A provider sends a receipt twiceUPDATE ... WHERE status = 'sent'364 ignored
    A provider accepts, then times out; failover sends againMessage ID as the provider's key; the client drops a seen IDnot 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 one requestpseudo code
    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
    1. 1The insert is the check. Two concurrent repeats race on the unique index, and one wins.
    2. 2Opt-outs are a NOT EXISTS in the same statement, per category and channel.
    3. 3Push and SMS, except security messages. Email waits in an inbox.
    4. 4A data-modifying CTE. A repeated key inserts no notification, so it inserts no messages.
    5. 5Redis sees only what Postgres stored. A crash before the push leaves a queued row for the sweeper.
    Tested source Go: accept · SQL: accept
    Go: acceptgo
    
    // 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
    }
    
    SQL: acceptsql
    -- 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.

    K

    Deep dive: providers, retries, failover

    each error class has one action
    send one messagepseudo code
    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
    1. 1A sliding log in Redis: at most 3 SMS, 6 push and 4 emails per user per 60 s in the lab.
    2. 2Opens at 50% failures over 10 or more calls; probes after 5 s.
    3. 3Where the provider offers an idempotency key, a resend of one ID is not sent twice.
    4. 4A permanent error is the address's fault, not the provider's. It does not count against the breaker.
    5. 5Full jitter: retries from many dispatchers spread out instead of arriving together.
    6. 6No provider had room this tick. The message keeps its place.
    Tested source Go: send
    Go: sendgo
    
    // 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
    }
    
    resultaction
    2xx acceptedMark sent; wait for a receipt.
    Timeout, 5xx, 429Retry with backoff and jitter.
    Invalid number, hard bounce, expired tokenDead-letter now; flag the address.
    6 failed attemptsDead-letter; alert on the rate.
    Breaker openNext provider in failover order.
    Every breaker openStay queued; probes test recovery.
    choicestatus
    Retry at once, no backoffNot approved
    Retry permanent errorsNot approved
    Backoff with full jitter, cappedApproved
    Failover on a breaker, not on one errorApproved
    Fail over SMS codes on a timeoutA 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.

    L

    Deep dive: caps, quiet hours, digests

    what the user agreed to receive
    rulewhere it runslab result
    Opt-out per category and channelAccept, in the insertNo message row
    Quiet hours for push and SMSAccept: hold until the local end441 held, 0 sent early
    Digest of social messagesAccept: buffer; dispatcher: fold1,064 likes in 183 pushes
    Cap per user per channelDispatcher, first attemptFlood user: 3 of 20 codes
    Security messagesSkip quiet hours and digests; keep the capCodes 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 hours and digestspseudo code
    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
    1. 122:00 to 07:00 crosses midnight, so the test is start or end, not start and end.
    2. 2Only messages that ring wait. A sign-in code must arrive at 03:00.
    3. 3A digest of one reads worse than the original.
    4. 4Each like keeps a row that points at the digest, so status queries still answer.
    Tested source Go: quiet hours · Go: digests
    Go: quiet hoursgo
    
    // 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"
    }
    
    Go: digestsgo
    
    // 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.

    M

    Failure cases

    what breaks, and why no user hears twice
    eventresultwhy it is safesaved by
    A producer retries a requestThe 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-audienceIt restarts from page 1.Keys repeat, so already-stored users are skipped.Unique key
    The API crashes after commit, before RPUSHA stored message is in no queue.The sweeper finds queued rows older than a minute and pushes them.Partial index
    Redis loses its dataQueues and schedules are gone.Every open message is a row in Postgres; rebuild queues and schedules from it.Rebuild
    A provider fails every callCalls fail fast.The breaker opens; the second provider takes the room; retries wait with jitter.Breaker
    A bug floods one userMany distinct keys for one user.The cap admits 3 SMS per window; the rest are capped and counted.Sliding log
    A campaign starts during peakBulk backlog grows.Transactional is popped first; bulk keeps its share and finishes later.Queue per priority
    A receipt arrives twice, or neverStatus is unclear.The update runs once; missing receipts are counted per provider.Conditional update
    N

    Scale ladder

    start simple; climb only on a signal
    Each step adds one component1Postgres table queue2+ Redis queues, caps3+ breakers, 2nd provider4+ paced campaigns5+ shards by usermore load →
    Capacity against this prompt's demand1k10k100k1MDemand: average: 5,787 messages or requests per secondDemand: average5,787Demand: peak: 17,361 messages or requests per secondDemand: peak17,361Postgres: accept one: 9,624 messages or requests per secondPostgres: accept one9,624Postgres: campaign pages: 42,779 messages or requests per secondPostgres: campaign pages42,779Service: one dispatcher: 5,965 messages or requests per secondService: one dispatcher5,965Redis: list push, 100 (B6): 324,969 messages or requests per secondRedis: list push, 100 (B6)324,969messages or requests per second, log scale
    stepaddit handlesmove up when you see
    1One 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.
    2Redis 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.
    3Breakers, backoff and a second provider per channel.A provider outage costs a few failed calls, not a backlog.Campaigns compete with daily traffic.
    4Paced 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.
    5Shard 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.

    O

    Follow-ups

    what the interviewer asks next
    questionanswerdeeper
    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
    P

    Drill

    predict, then reveal

    0 of 10 known

    1. A campaign to every user starts while sign-in codes keep arriving. What do the codes wait behind with one queue per channel?

    2. Strict priority can starve bulk. How do you keep a campaign moving during a busy hour?

    3. A producer times out and sends the same request again. What stops a second message?

    4. The campaign job crashes after 3 pages and restarts from page 1. What happens to the first 1,500 users?

    5. Why does a cap check run only on the first attempt?

    6. Which failures do you retry, and which go to the dead-letter list at once?

    7. An email provider fails every call for 20 s. How many calls does it get, and where does email go?

    8. Can failover deliver one message twice?

    9. A user gets 40 likes in 10 s. What reaches their phone?

    10. A user is asleep at 23:00 local. Which messages wake them?

    Q

    Numbers to say

    measured, derived or recorded
    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.