Skip to content

    System Design

    Case Study: Notification Service

    Design a notification service end to end: requirements, estimates, API, data model, lanes, campaign fan-out, token hygiene, receipts and failure drills.

    By Published 22 min read

    Share

    Case studyintermediateBackend System Design

    Before this: Case Studies: The Hard Problems Map and the Template, Notification Systems

    What you'll learn: By the end of this lesson you will be able to run a notification-service design round from requirements to failure drills: size the traffic, define the API and data model, choose lanes and a campaign fan-out, make intake safe against duplicates, keep device tokens and addresses clean, and say how the service behaves when a provider, a queue or a deploy goes wrong.

    Picture the mailroom of a large office. Parcels arrive from every department, some "urgent", some "newsletter for everyone". The clerk checks the person still wants the item, picks a courier and files the receipt. When a newsletter run jams the sorting table, urgent parcels must still leave on time.

    A notification service is that mailroom for software, and the interview question "design a notification system" is a request to design the mailroom. This is an educational reference design, not the verified internal architecture of any company, and it names no company. It is a case study: it applies the theory taught in Notification systems: lanes, channels, retries and receipts and does not repeat it. It assumes lanes, expiry, collapse keys and bounces, and spends its words on requirements, numbers, interfaces, storage and failure drills. The running example is the ShopStream grocery marketplace, whose notification stage is in ShopStream: search, notifications and media.

    Verified on 2026-12-02 against RFC 8030, RFC 8058 and the Firebase Cloud Messaging, Amazon SES, Amazon SNS and Apache Kafka documentation. All traffic numbers are illustrative assumptions; the arithmetic was checked with Node on the same date.

    The core idea

    A notification service is a policy engine in front of a delivery pipeline. Other teams say "tell this person this thing". The service decides whether to, when, on which channel and how urgently, then drives providers and learns from what they report. A push is one HTTPS request; the difficulty is the surrounding promises: never send the same message twice, never send after an opt-out, never let a campaign delay a security code, never keep retrying a dead address. A good answer has four layers: a small API, a decision layer that holds the rules, lanes and workers that move messages at controlled rates, and a feedback loop from providers back into the rules. Three illustrations run through the lesson:

    • Minimal example: one order event becomes one push, with every table row it touches.
    • Realistic example: the ShopStream daily campaign running next to live order updates.
    • Failure example: a restarted campaign job that sends the same promotion twice.

    Requirements and scope

    Functional

    • Producers (order service, auth service, marketing tool) request a notification by type and recipient; the service renders and sends it.
    • Channels: mobile push, email, SMS. In-app inbox is out of scope except as a history list.
    • Users and operators control preferences per category and channel, including quiet hours and unsubscribe.
    • Scheduled and bulk sends: a campaign to a segment inside a send window, pausable.
    • Status: a producer or support agent can ask what happened to a notification, and why a user did not get one.

    Out of scope: composing campaign content, segment computation (the service receives a segment id), provider selection beyond one provider per channel, and the in-app real-time feed (see WebSockets, SSE and long polling).

    Non-functional (assumptions, illustrative)

    Requirement Target
    Critical lane (security codes, courier at the door) Handed to the provider within 5 seconds at p99
    Standard lane (order progress, receipts) Within 60 seconds at p99
    Bulk lane (campaigns) Within the campaign's window, which the sender chooses
    Duplicates Producer retries never create a second notification; a user sees at most one copy in normal operation
    Opt-out A change to preferences applies to every message not yet handed to a provider
    Availability Intake accepts requests even when every provider is down; delivery degrades, intake does not
    Honesty The service records "handed to provider" and "reported delivered" as different facts

    The last row is a design principle, not a measurement. It follows from the channel semantics in the theory lesson: for example, RFC 8030 says a 201 for a push request "does not indicate that the message was delivered to the user agent" (section 5).

    Back-of-envelope estimate

    All inputs are illustrative assumptions, taken from ShopStream's shared figures where they exist (2,000,000 daily active users, 500,000 orders per day).

    Quantity Assumption Result
    Order messages per order 6 (placed, confirmed, picked, out for delivery, delivered, receipt) 500,000 x 6 = 3,000,000 per day
    Average transactional rate 3,000,000 / 86,400 about 35 per second
    Peak transactional rate 10 times average, like checkouts about 347 per second
    Security codes 100,000 per day about 1 per second
    Marketing one campaign a day to every daily user 2,000,000 per day
    Total 3,000,000 + 100,000 + 2,000,000 5,100,000 messages per day, about 59 per second on average
    Channel mix of order messages 70% push, 25% email, 5% SMS 2,100,000 push, 750,000 email, 150,000 SMS
    Campaign drain at 2,000 per second 2,000,000 / 2,000 1,000 seconds, about 17 minutes
    Same campaign spread over 60 minutes 2,000,000 / 3,600 about 556 per second
    Status rows 1.3 rows per message x 200 bytes about 1.3 GB per day, about 40 GB for 30 days
    Dedup keys kept 48 hours 5,100,000 x 2 x 100 bytes about 1 GB
    Device tokens 2,000,000 users x 1.5 devices x 200 bytes about 600 MB

    Two things follow. The steady rate is tiny, so the system is sized by bursts: the campaign is 2,000,000 messages in one job, two thirds of a normal day's order traffic. And the scarce resource is outside the system: provider rate limits and fees. The lever is how fast we ask providers to go, not how fast our servers can go.

    API design

    Producers call a thin HTTP API. They send identifiers and data, never finished text, so rendering stays in one place.

    POST /v1/notifications
    Idempotency-Key: order-9917-out-for-delivery
    { "type": "order_out_for_delivery", "userId": "u_31",
      "data": { "orderId": "9917", "etaMinutes": 10 } }
    -> 202 { "notificationId": "n_7f3a", "status": "queued" }
    
    GET  /v1/notifications/n_7f3a
    -> 200 { "status": "accepted", "attempts": [ ... ], "reason": null }
    
    POST /v1/campaigns        { "segmentId": "s_44", "type": "weekly_offer",
                                "window": { "from": "...", "to": "..." }, "ratePerSecond": 600 }
    POST /v1/campaigns/c_12/pause     -> 204
    PUT  /v1/users/u_31/preferences   { "category": "marketing", "channel": "email", "enabled": false }
    POST /v1/devices                  { "userId": "u_31", "token": "...", "platform": "android" }
    POST /v1/unsubscribe/{opaqueToken}   -> 200   (no login, no redirect)
    POST /v1/provider-events/{provider}  -> 204   (receipts and bounces, signature checked)

    Design points worth saying aloud:

    • 202 Accepted, not 200. The call means "durably recorded, will be processed". It does not mean sent. Returning before provider calls is what lets intake stay up while providers are down.
    • The idempotency key is the dedup key. Producers choose a key that names the real-world event, such as the order id plus the step, never a random value generated per attempt. A producer's retry then returns the original notificationId. See idempotency keys and safe retries.
    • The unsubscribe endpoint obeys RFC 8058. One-click unsubscribe works by the mail client sending an HTTPS POST to the URI in the List-Unsubscribe header, with a List-Unsubscribe-Post header whose value is exactly List-Unsubscribe=One-Click (sections 3.1 and 3.2). The POST must not carry cookies or authorization, the server must not answer with a redirect, and both headers must be covered by a valid DKIM signature. So the URI carries an opaque, signed token that identifies user and list, and the handler works without a session.
    • Provider events are authenticated. They change suppression state, so they are verified, never trusted by URL alone.

    Data model

    Rules live in data, so changing "how long is a courier ETA valid" is a configuration change, not a deploy.

    erDiagram accTitle: Notification service data model accDescr: A notification type defines lane, expiry and channels. A notification belongs to a user and has many attempts, one per channel try. Users have device tokens and preferences. A campaign creates notifications. A suppression entry blocks an address on a channel. NOTIFICATION_TYPE ||--o{ NOTIFICATION : defines CAMPAIGN ||--o{ NOTIFICATION : creates NOTIFICATION ||--o{ ATTEMPT : has USER ||--o{ NOTIFICATION : receives USER ||--o{ DEVICE_TOKEN : owns USER ||--o{ PREFERENCE : sets SUPPRESSION }o--|| USER : blocks NOTIFICATION_TYPE { string type PK string category string lane int expiry_seconds string collapse_key_template string channels } NOTIFICATION { string id PK string dedup_key UK string type FK string user_id FK string status datetime expires_at } ATTEMPT { string notification_id FK string channel string state string provider_ref string error_class } DEVICE_TOKEN { string token PK string user_id FK string platform datetime last_seen string state }

    Figure 1. The tables behind the service. How to read this: NOTIFICATION_TYPE is the rules table (lane, expiry, collapse key, allowed channels). NOTIFICATION has one row per logical message and a unique dedup_key. ATTEMPT has one row per channel try, so "why did I not get it" is a query.

    • notification, sharded by user_id so one user's history is one shard (see hot partitions and resharding for the skew you will meet). The unique dedup_key index is the intake guard.
    • attempt, keyed by (notification_id, channel, attempt_no), append-only. It holds the provider reference that receipts later refer to.
    • device_token with last_seen and a state (active, stale, invalid). Tokens are keyed by token, with the user as an attribute, because one phone can be re-assigned to another account after a log-out.
    • preference holds per category and channel consent, plus the user's time zone and quiet hours. Consent changes are recorded with a timestamp; for marketing that history is the evidence of consent (see compliance and privacy).
    • suppression lists addresses and tokens never to send to, with a reason (hard bounce, complaint, unsubscribe, invalid token). It is checked in the decision step.
    • Dedup and expiry. Keep dedup keys for longer than the longest retry window plus the longest expiry. The estimate above kept them for 48 hours, which is a choice, not a rule.

    Minimal example (illustrative). Order 9917 goes out for delivery. Intake inserts notification n_7f3a with dedup_key = order-9917-out-for-delivery, type order_out_for_delivery (lane standard, expiry 20 minutes, collapse key order-9917-eta), and writes an outbox row in the same transaction. Decide finds a push-enabled preference and two active tokens. Two attempt rows appear, accepted a second later, and a receipt webhook later moves one to delivered.

    High-level design

    Notification service: components and data flowProducers to Intake API; Intake API to Notification store (row and outbox); Notification store to Outbox relay; Outbox relay to Decision workers; Decision workers to Lane queues (render, enqueue); Lane queues to Channel workers; Channel workers to Providers (send); Campaign job to Decision workers (page by page); Providers to Receipt handler (receipts); Receipt handler to Notification store (state, suppression)Producers: orders, auth, marketingProducersorders, auth,marketingIntake API: idempotent, 202Intake APIidempotent, 202Notification store: rows plus outboxNotificationstorerows plus outboxOutbox relayOutbox relayDecision workers: rules, limitsDecisionworkersrules, limitsLane queues: critical, standard, bulkLane queuescritical,standard, bulkChannel workers: push, email, SMSChannelworkerspush, email, SMSProviders: outside our controlProvidersoutside ourcontrolCampaign job: paged fan-outCampaign jobpaged fan-outReceipt handler: bounces, tokensReceipthandlerbounces, tokensrow and outboxrender, enqueuesendpage by pagereceiptsstate, suppression

    Figure 2. The reference design. How to read this: the top row is the send path; the campaign job feeds the same decision workers as ordinary traffic, so every rule applies to bulk sends too. Providers are drawn muted because the service cannot control them. The bottom arrow is the feedback loop that writes suppression and token state back to the store.

    The path of one request: the intake API writes the notification and an outbox row in one database transaction, so a crash can never leave a recorded request that is never published (the pattern is in the transactional outbox). A relay publishes the outbox rows to the decision queue. Decision workers check consent, suppression, expiry and limits, render the template as late as possible, and enqueue onto a lane. Channel workers call the provider and record an attempt. Receipts arrive by webhook and update the same rows.

    sequenceDiagram accTitle: Life of one notification request accDescr: A producer posts a request with an idempotency key. Intake inserts the notification and an outbox row in one transaction and answers 202. The relay publishes to the decision workers, which check preferences and suppression, render, and enqueue on a lane. A channel worker sends to the provider, records the attempt, and a later webhook records the receipt. participant P as Producer participant I as Intake API participant S as Store participant D as Decision worker participant W as Channel worker participant V as Provider P->>I: POST notification, Idempotency-Key I->>S: insert notification and outbox row (one transaction) I-->>P: 202 queued S-->>D: relay publishes D->>D: consent, suppression, expiry, limits D->>W: render and enqueue on lane W->>V: send V-->>W: accepted W->>S: record attempt accepted V-->>I: receipt webhook later I->>S: record delivered or failed

    Figure 3. One request from producer to receipt. How to read this: the producer is released at the 202, before any provider is called. Everything below that line is retryable background work, which is why intake stays up when a provider is down.

    Deep dive 1: making intake safe

    Duplicates come from three places

    1. Producer retries. A caller times out and calls again. The unique dedup_key rejects the second insert and intake returns the first notification's id.
    2. Queue redelivery. Queues deliver at least once. Amazon SES's documentation says this of its own message copies and tells applications to be idempotent about it. Decision workers therefore claim a notification with a conditional update from queued to deciding, and a second worker that loses the race stops.
    3. Crash between provider call and record. A channel worker calls the provider, then dies before writing the attempt row. On redelivery it cannot know whether the provider received the request. No design makes this impossible, so the service reduces the visible damage: it sends with a collapse key where the provider supports one. RFC 8030 says a push with a topic "replaces any outstanding push message with an identical topic" (section 5.4), and Firebase's collapse key discards an older undelivered message with the same key and token. Both end with one message at the device. Email has no such guard, which is why email workers write the attempt row before the call in state sending and treat a stale sending row as "unknown", not "retry".

    This is the honest framing for an interview: the service gives at-least-once handoff and engineers duplicates toward harmless. For the general theory see delivery guarantees and idempotent consumers and deduplication.

    Choosing the dedup key per type

    Message Dedup key Why
    Order step order id plus step name "Out for delivery" is once per order
    Security code user id plus a login-attempt id A second attempt is a new message
    Campaign campaign id, user id, channel A restarted campaign must not repeat
    Receipt email order id plus "receipt" A replayed event must not mail it again

    A key that includes a timestamp or a random value is a key that never deduplicates anything.

    The decision step, in a fixed order

    Check cheap, high-rejection rules first and expensive lookups last. Each rejection records a reason, so support can answer "why".

    flowchart TD accTitle: Decision step order accDescr: Check that the notification has not expired, then that the user consented to this category and channel, then that the address or token is not suppressed, then quiet hours for marketing, then per-user frequency limits. A pass renders and enqueues on a lane. Any failure records a reason. Quiet hours reschedule instead of dropping. A["Dequeued"] --> B{"Expired?"} B -->|yes| X["Record: expired"] B -->|no| C{"Consent for category
    and channel?"} C -->|no| X2["Record: no consent"] C -->|yes| D{"Address or token
    suppressed?"} D -->|yes| X3["Record: suppressed"] D -->|no| E{"Marketing inside
    quiet hours?"} E -->|yes| H["Reschedule for window"] E -->|no| F{"Under frequency cap?"} F -->|no| X4["Record: capped"] F -->|yes| G["Render and enqueue on lane"]

    Figure 4. The decision order. How to read this: each diamond removes messages before they cost rendering or provider calls. Quiet hours are the only branch that reschedules instead of dropping, and it applies to marketing only; a security code ignores quiet hours but never ignores consent to the channel.

    What happens when the preference store is down? State the policy per category, because there is no single right answer: fail closed for marketing (hold or drop, because sending without consent is the costly error) and fail open for security codes (send, because the user is waiting and the message is requested by the user). Writing that table down is the senior signal.

    Deep dive 2: lanes and the campaign fan-out

    The theory lesson explains lanes and head-of-line blocking; here is how to size and run them. With the estimate above: the critical lane carries about 1 message per second plus bursts, so a small reserved pool of workers is enough, and its value is isolation rather than throughput. The standard lane carries up to about 350 per second at peak. The bulk lane has a rate budget set by the provider's limits and by what the business allows, for example 600 per second, which drains 2,000,000 messages in about an hour.

    A campaign is a job, not 2,000,000 messages

    The campaign job stores a cursor over the segment and pages through it:

    1. Read a page of 1,000 recipient ids after the cursor.
    2. For each, create the notification with dedup key (campaign, user, channel) in a batch; a unique violation means "already done" and is skipped.
    3. Hand the page to the decision workers at the lane's rate.
    4. Persist the new cursor, then loop.

    Because the cursor is stored and each recipient has a dedup key, a restart resumes instead of repeating, and an operator can pause between pages. The rate is a token bucket per lane in front of the provider calls (see rate limiting), so the number of workers does not decide the speed; the budget does.

    Firebase's guidance on scaling sends says the same from the provider's side: ramp traffic up gradually, avoid strategies that immediately exhaust the send quota, and avoid sending within a two-minute window around the :00, :15, :30 and :45 marks. A campaign that starts "at 09:00 sharp" for two million people is exactly that spike, so the job adds a random offset per recipient inside its window.

    Overload policy is part of the design: when the bulk lane is behind, expire its messages at the end of the sale rather than sending them late, and never borrow capacity from the critical lane.

    Deep dive 3: channels, tokens and the feedback loop

    Push token hygiene

    A token is a perishable address. Firebase's token guidance says a registration is considered stale by default if its app instance has not connected for a month, Android registrations inactive for 270 days expire and are garbage collected, and the recommended refresh is about once a month. Its documentation also says a response of UNREGISTERED (HTTP 404) means it is safe to delete the registration record, but cautions that INVALID_ARGUMENT can also mean a problem in the message payload, so it is not by itself proof the token is bad. Two rules follow:

    • Prune by two signals: the provider's "gone" response, and the service's own last_seen age. Run a daily job that marks tokens past the staleness window stale and stops sending to them.
    • Never delete on an ambiguous error. Classify errors so a bad template cannot wipe your device table: only the specific "unregistered" outcome removes a token, and a payload error pages a human.

    RFC 8030 gives the web-push equivalent: a push service must answer 404 when an application server sends to an expired subscription (section 7.3).

    Receipts and unknowns

    Treat the provider webhook as an event stream. For web push, RFC 8030 describes receipts: when the user agent acknowledges a message, the push service returns 204, which "confirms that the message was delivered and acknowledged" (section 6.3), and if it stops retrying before expiry it returns 410 (section 6.2). Most channels give less. So the status model has accepted as a normal resting state and a sweeper that moves accepted rows past their type's expiry to expired ("no receipt, assume unknown"). The support tool shows exactly those words.

    Retries by error class

    The retry rules from the theory lesson become a small table in the channel worker:

    Outcome Class Action
    Timeout, 5xx, 429 Transient Retry with backoff and jitter; honour Retry-After; stop at the message's expiry
    Hard bounce, unregistered token Permanent, address Suppress the address or token; no retry
    Bad credentials, malformed payload Permanent, ours Stop, page a human, do not delete anything
    Complaint Permanent, consent Suppress marketing to that address

    The sources agree on the shape. Amazon SNS treats all 5xx and 429 responses as retryable and every other error as permanent (for HTTP/S endpoints), and for SMTP, SMS and mobile push its fixed default is 50 attempts over six hours, after which a message is discarded unless a dead-letter queue is attached. Firebase advises exponential backoff with jitter, waiting at least 10 seconds before retrying, and honouring retry-after on a 429. RFC 8030 says a push service may return 429 and should include Retry-After (section 8.4). The design takes the structure and replaces the numbers: a courier ETA's retry window is minutes, not six hours, because its expiry is minutes. Failures that should be inspected go to a dead-letter queue; the backoff mechanics are in timeouts, retries, backoff and jitter.

    Email reputation is a shared resource

    Amazon SES's documentation defines a hard bounce as a persistent failure, which SES does not retry and which you should not retry either, and a soft bounce as a temporary failure that SES retries and then abandons. It says only hard bounces count toward the bounce rate, that excessive bounces and complaints can lead SES to reduce sending quotas or terminate an account, and that it keeps a global suppression list of recently hard-bounced addresses for up to 14 days. The consequence for the design: one sender identity per category. If marketing and order receipts share an identity, a bad campaign list damages the delivery of receipts. The service therefore maps category to a sending identity in the type table, and a bounce-rate guard pauses the bulk lane (not the transactional ones) when the rate crosses a threshold.

    Ordering and per-user fairness

    Per-order ordering matters ("delivered" must not be followed by "out for delivery"); global ordering does not. Partition the standard lane by user_id: Kafka documents that events with the same key go to the same partition and that a consumer reads a partition's events in the order written. Also carry a source version and drop an update older than the newest already handed over for that order and channel. A per-user frequency cap stops an upstream bug from sending one person a hundred messages.

    Bottlenecks and scaling

    • Decision workers read preferences and suppression on every message. Cache both in memory with a short time to live and invalidate on write events; a stale consent cache is a correctness risk, so keep marketing TTLs short and let opt-out writes publish an invalidation. The theory is in cache strategies.
    • The notification store is write-heavy and append-mostly. Shard by user_id, partition by day, and drop partitions older than the retention window instead of deleting rows.
    • Provider rate limits are the real ceiling. Keep one token bucket per provider credential, and split credentials between lanes if the provider allows it.
    • Receipt webhooks can flood in after an outage: give them their own queue and bounded consumers.

    Failure drills

    A senior answer rehearses failures out loud. Each row is a drill the team can run in staging.

    Failure What users see Design response
    One provider down Delayed pushes or emails Circuit breaker per provider, retries within expiry, then expired; fail over email to a second provider only where consent covers it
    Queue backlog on the bulk lane Late campaigns Slow or pause the job, expire at the window's end; critical lane unaffected
    Preference service down Possibly wrong sends Fail closed for marketing, open for security codes
    Bad template deploy "Hello null" messages Render in staging against sample data, canary the template by lane, kill switch per type
    Campaign job restarted Possible duplicate promotion Stored cursor plus per-recipient dedup key
    Mass token invalidation Sudden drop in push success Alert on "unregistered" ratio; confirm the app identifier and credentials before pruning
    Bounce spike on marketing email Receipts start landing in spam Pause bulk email, separate sender identities, clean the list
    Clock or time-zone bug Marketing at 03:00 local Quiet hours evaluated with the user's stored zone; a "send hour" histogram alert

    Drills must end with a statement of the blast radius: which category, how many users, for how long. A design that cannot say "only marketing, only email" for a bounce spike has shared a fate it did not need to.

    Trade-offs worth stating

    Decision Option A Option B How to choose
    Intake style Synchronous send in the request Durable record, 202, async send Async, because intake must survive provider outages
    Dedup Unique key in the store Cache-only check Unique key; a cache entry can be lost before the send
    Campaign release All at once Paged, rate-limited, random offsets Paged; it is pausable and provider-friendly
    Provider failure Retry until success Retry until the message's expiry Expiry; late messages are worse than none
    Consent store outage Fail open Fail closed By category: closed for marketing, open for security codes

    Interview cheat sheet

    Step What to say Key numbers (illustrative)
    Requirements At most one useful message per channel, with consent and expiry Lane targets 5 s, 60 s, window
    Estimate Steady load is small; the campaign burst sizes the system 59 per second average, 347 peak, 2,000,000 campaign
    API and data 202 plus idempotency key; type rules, notification, attempt, token, preference, suppression About 40 GB status rows for 30 days
    Design Outbox, decision workers, three lanes, channel workers, receipt handler Page of 1,000, cursor stored
    Failures Provider down, restart mid-campaign, bounce spike, bad template Blast radius per category

    Build it

    There is no lab for this case study. The lessons that give you a runnable piece are the ones it builds on: practise the retry rules in timeouts, retries, backoff and jitter and the intake pattern in the transactional outbox. Nothing on this page was run beyond the estimate arithmetic.

    In practice: running the service day to day

    This is an educational scenario on ShopStream with illustrative numbers.

    This is a realistic scenario, not a case history.

    The situation

    ShopStream's notification service has been live for a month. The marketing team schedules the daily offer for 09:00. On a Thursday, order "out for delivery" pushes arrive up to 12 minutes late between 09:00 and 09:20, and 41,000 shoppers receive the offer twice.

    Starting architecture

    Figure 2, with two flaws found later: the campaign job keeps its cursor in memory, and the bulk and critical lanes share one provider credential and one token bucket.

    Options considered

    Option Gain Cost Wrong when
    A. Lower the campaign rate globally Less pressure on the provider Campaigns take longer; the shared bucket flaw remains Throttling comes from the shared credential, not the rate
    B. Persist the cursor, keep per-recipient dedup keys, split the token bucket per lane Restarts resume; urgent traffic keeps its own budget Two buckets to size and monitor The provider offers only one credential and one limit

    The decision

    Option B. The cursor moves into the store, each page commits its cursor and its notifications together, and the dedup key (campaign, user, channel) rejects a repeat. The provider's budget is split so the critical lane has a protected share, and the bulk job adds a random offset per recipient across a 30-minute window instead of starting everyone at 09:00.

    Rollout and verification

    Replay the previous Thursday's order stream against a staging copy with a synthetic campaign and watch critical-lane queue age and duplicate rows per campaign. Then run one real campaign to 5 percent of users, then 25, then all. Dashboards: queue age per lane, handed-to-provider rate per provider, accepted rows older than expiry, tokens marked invalid per hour, bounce and complaint rates per sender identity, and campaign duplicates (rows sharing a campaign and user).

    The 2 a.m. failure

    The campaign job's host is replaced during the 09:00 run in the original design; the replacement starts at page one.

    sequenceDiagram accTitle: Campaign restart without a stored cursor accDescr: A campaign worker sends pages one to forty and then is replaced. The new worker has no cursor and starts at page one. Without per-recipient dedup keys, recipients in pages one to forty receive the offer again. With the new design, the stored cursor resumes at page forty-one and any repeated recipient is rejected by the unique key. participant J as Campaign worker participant S as Store participant L as Bulk lane J->>S: create page 1..40 notifications S-->>L: queued and sent Note over J: host replaced mid-run J->>S: start again at page 1 (old design) S-->>J: no dedup key, inserts succeed S-->>L: second copy queued J->>S: read stored cursor (new design) S-->>J: resume at page 41 J->>S: create page 41 onward S-->>J: repeated recipient rejected by unique key

    First checks: campaign id, count of notifications per (campaign, user), and the cursor position. Mitigation: pause the job, drop the queued second copies whose dedup row shows an earlier send, and post a short in-app apology only if the offer was materially affected. Follow-up: add a test that kills the job host mid-run and asserts zero duplicates.

    Architect's notes

    • Write the expiry and fail-open table first. Those two tables answer most of the arguments.
    • Make the status API the first consumer. If support cannot explain a missing message from your own data, the data model is wrong.
    • Keep campaigns on the same rules path as everything else. A side door for marketing is where consent bugs hide.
    • Budget providers, not workers. Provider limits and reputation are the scarce resources.
    • Never build a retry you cannot stop. Every loop needs an expiry, a limit and an off switch.

    Common mistakes

    • Sending in the request path, so a provider outage becomes an outage of the order service.
    • A per-attempt random dedup key, which deduplicates nothing.
    • A campaign without a stored cursor, which repeats on restart.
    • Deleting a device token on INVALID_ARGUMENT, when the payload was at fault.
    • One sender identity for receipts and promotions, which shares their reputation.
    • Retrying until success, instead of until expiry.
    • Failing open on marketing consent when the preference store is down.

    Key takeaways

    • A notification service is a policy engine in front of a pipeline; the API stays small and the rules live in data.
    • Size it by bursts and provider limits, not by the steady rate.
    • Intake records durably, answers 202, and uses an idempotency key as the unique dedup key.
    • At-least-once handoff is the honest guarantee; collapse keys and topics make duplicates harmless on devices.
    • A campaign is a paged job with a stored cursor, a rate budget and a pause button.
    • Tokens and addresses are perishable: prune on the provider's "gone" signal and on age, and never on an ambiguous error.
    • Fail closed for marketing and open for security codes, and say so by category.

    Practice exercises

    Exercise 1 (30 min). Using the estimate table, recompute the campaign drain time if the segment doubles to 4,000,000 and the bulk budget stays at 600 per second. Decide whether to lengthen the window or raise the budget, and what each choice costs.

    Exercise 2 (1 hour). Write the notification_type rows for ten ShopStream messages: lane, category, expiry, collapse key and channels. Mark which ones fail open and which fail closed when the preference store is down.

    Exercise 3 (2 hours). Design the sweeper for accepted rows: its query, its batch size, its per-shard schedule, and what each final state triggers (token cleanup, support visibility, a metric).

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments