Notes from a hundred million notifications

Sending a message is easy. Sending the right one, once, at a sensible hour, a hundred million times a month — that's the system. What I learned building notifications at Compass.

A stream of dots fanning out into three channels

At Compass I spent a good part of two years on the system that told real-estate agents and their clients that something had happened. A showing was booked. An offer came in. A listing they were watching dropped its price. Across push, email and SMS it added up to around a hundred million messages a month.

Nobody joins a company to work on notifications. They look like plumbing: an event happens, you call a provider, a phone buzzes. Then you run one at scale and discover it's one of the few systems every single user has an opinion about. People don't notice when search is 40ms slower. They absolutely notice when their phone buzzes eleven times at 3am about a house they looked at once.

This is a long write-up of what I'd tell myself on day one.

The naive version, and why it breaks

The first version of almost every notification system looks like this: a service that cares about an event calls a helper, the helper looks up the user's device tokens or email address, and it sends. Every team owns its own little send_notification call.

It works for a long time, which is the dangerous part. The failure modes only show up at volume, and they all have the same root cause: the decision about whether a human should hear about this is spread across dozens of call sites. Each one makes a locally reasonable choice. Together they make a phone that won't stop buzzing.

Here is what we were actually seeing before the rework:

  • the same event delivered two, three, sometimes five times, because upstream services retried and each retry looked like a new message
  • pushes at night for things that could easily have waited until morning
  • ten updates to one listing in a minute turning into ten separate notifications
  • support tickets asking "did my client get the offer alert?" that took an engineer twenty minutes and three log queries to answer
  • SMS bills that went up faster than SMS volume, because retries were paying for the same message twice

None of these are hard problems on their own. The hard part is that you can't fix them one call site at a time.

One place for the rules

The single most important change was architectural, and it's boring: producers stop sending notifications. They emit events. One dispatcher owns every decision after that.

The notification pipeline: producers emit events, the dispatcher applies dedupe, preferences, quiet hours and collapsing, then routes to channelsProducers only describe what happened. Whether, when and where a person hears about it is decided in exactly one place.

That sounds like a small thing. It changes everything about how the system evolves. When product wants quiet hours, there's one place to add them. When legal asks for an audit of what was sent to whom, there's one table to query. When a new team ships a feature, they don't need to know how APNs token expiry works. They need to know how to describe an event.

The event contract was deliberately small:

events/offer_received.json
json
{
  "type": "offer.received",
  "event_id": "evt_01HZX4K8Q2M7",
  "occurred_at": "2022-03-14T18:22:05Z",
  "subject": { "kind": "listing", "id": "lst_88214" },
  "audience": [
    { "user_id": "usr_1021", "role": "listing_agent" },
    { "user_id": "usr_7733", "role": "seller" }
  ],
  "payload": { "amount": 812000, "currency": "USD" },
  "urgency": "high"
}

Two fields in there did most of the work. event_id is the producer's promise that retries carry the same identity. urgency is the producer's opinion about how much this matters, and the dispatcher is free to overrule it.

Deduplicate at the edge

Upstream services will send the same event twice. Sometimes five times. Message buses deliver at least once, HTTP clients retry on timeouts, and a deploy that restarts a consumer mid-batch replays whatever wasn't acknowledged. You will not fix this upstream. Accept it and deduplicate at the door.

Every notification gets a deterministic key built from things that define "the same message to the same person", not from anything that changes between retries:

dispatcher/dedupe.py
python
import hashlib
 
DEDUPE_WINDOW_S = 6 * 60 * 60  # six hours
 
 
def dedupe_key(event: dict, user_id: str, template: str) -> str:
    raw = f"{event['event_id']}:{user_id}:{template}"
    return hashlib.sha256(raw.encode()).hexdigest()[:32]
 
 
def accept(redis, event: dict, user_id: str, template: str) -> bool:
    """True if this is the first time we've seen this message in the window."""
    key = "ntf:seen:" + dedupe_key(event, user_id, template)
    return bool(redis.set(key, 1, nx=True, ex=DEDUPE_WINDOW_S))

SET NX with an expiry is one round trip and atomic. Two workers racing on the same retry can't both win. We sized the window at six hours because that comfortably covered the worst replay we'd ever seen, and Redis memory for six hours of keys was cheap.

The subtle bit is choosing what goes into the key. Early on we included the rendered message text, which meant a template change during a deploy produced "new" messages for events already sent. The key should describe intent, not output.

Respect the clock

A push at 3am about a price drop is a great way to get your app deleted. Quiet hours sound simple and have three traps.

Time zones belong to people, not servers. We stored a time zone per user, defaulted from their market, and let them change it. Agents travel; their clients often live somewhere else entirely.

Not everything can wait. An offer with a deadline in two hours is not the same as a price drop on a saved search. Urgency from the producer decides whether a message can break quiet hours, and only a short allowlist of event types could.

Deferred is not dropped. Messages held overnight go into a schedule and are released in the morning, collapsed with anything else that arrived in the meantime. One "while you were asleep" summary beats eight separate buzzes at 8:00:01.

dispatcher/quiet_hours.py
python
from datetime import datetime, time, timedelta
from zoneinfo import ZoneInfo
 
QUIET_START, QUIET_END = time(21, 0), time(8, 0)
BREAKS_QUIET = {"offer.received", "offer.deadline", "showing.cancelled"}
 
 
def release_at(event_type: str, tz: str, now_utc: datetime) -> datetime:
    """When this message may be delivered. now_utc if it can go immediately."""
    if event_type in BREAKS_QUIET:
        return now_utc
    local = now_utc.astimezone(ZoneInfo(tz))
    t = local.time()
    if QUIET_END <= t < QUIET_START:
        return now_utc
    morning = local.replace(hour=8, minute=0, second=0, microsecond=0)
    if t >= QUIET_START:
        morning += timedelta(days=1)
    return morning.astimezone(ZoneInfo("UTC"))

The code is short. Getting product, sales and a few very vocal agents to agree on the allowlist took three weeks. That's normal, and it's the right place to spend the time.

Collapse, don't spam

Some events come in bursts. An agent edits a listing: price, photos, description, open-house times, all in ninety seconds. Each save fires an event. To a watcher of that listing, it is one piece of news: "this listing changed".

We added a short collapse window per user and subject. The first event opens the window; anything for the same subject in the next couple of minutes joins it; when the window closes, one notification goes out with a summary. "Price reduced to $812k, and 4 more updates."

The window length is a trade-off between latency and noise. Two minutes felt slow to engineers and right to users. We let urgent events skip the window entirely, for the same reason they could skip quiet hours.

Channels fail differently

The second-biggest mistake in the old system was a single retry policy for every channel. Push, email and SMS fail in completely different ways, and one policy is wrong for all three.

pushemailsms
typical failurestale or unregistered tokenbounce, spam foldercarrier rejection, invalid number
how you find outimmediately, from the provider responseminutes to days later, via webhookseconds to minutes, via status callback
retry?no — remove the tokensoft bounce yes, hard bounce nevera couple of times with backoff
cost per attempteffectively freevery lowreal money
what to fall back toemail, if urgentnothing, it's the fallbackpush, if they have the app

The SMS row is the one that hurts if you get it wrong. A blind "retry three times" policy on a message the carrier already rejected for a bad number pays three times for zero deliveries. We moved to retrying only on errors the provider marked as transient, with a per-message budget.

The Twilio side became a small internal platform of its own: number pools per market, sender reputation, opt-out keywords handled before anything reached product code. Other teams used it to send messages directly, and it was where most of the improvement in agent response times came from.

Make it observable per message

"Did this person get told?" is a support question you will hear every day. If answering it requires an engineer, you've built the wrong system.

We modelled every notification as a small state machine and wrote every transition to a status store with a reason.

The states a notification moves through, from accepted to delivered, dropped, scheduled or failedEvery arrow is a row in the status store. Support reads the reasons; engineers read the counts.

Once that existed, a support tool was a single page: search by user, see every message for the last thirty days, and for each one the path it took. "Dropped: duplicate." "Scheduled: quiet hours until 08:00 America/New_York." "Failed: push token unregistered, fell back to email, delivered." Most tickets closed without an engineer.

The same table gave us the metrics that mattered. Not "messages sent", which only ever goes up, but:

  • drop rate by reason, broken down by producer
  • median and p99 time from event to delivery, per channel
  • the share of messages deferred by quiet hours, and how many of those were later opened
  • cost per delivered SMS, not per attempted SMS
analytics/drops_by_producer.sql
sql
select
  producer,
  reason,
  count(*)                                   as dropped,
  round(100.0 * count(*) / sum(count(*)) over (partition by producer), 1) as pct
from notification_transitions
where to_state = 'dropped'
  and created_at >= now() - interval '7 days'
group by producer, reason
order by dropped desc
limit 20;

That one query found more bugs than any test suite we had. A producer with a 40% duplicate drop rate is a producer with a retry bug, and now we could tell its team which one.

Volume, roughly

Monthly volume by channelPush grew fastest; SMS stayed small but expensive. Illustrative numbers.

Volume grew every quarter, but not evenly. Push grew fastest as more agents and clients installed the app. Email stayed the dependable baseline. SMS stayed the smallest by far and was still a meaningful line in the budget, which is exactly why it got the most careful routing.

The dispatcher itself was not the bottleneck at a hundred million a month. That works out to roughly forty messages a second on average, with peaks several times higher on Monday mornings and around big listing days. The pressure points were always the edges: provider rate limits, Redis memory for dedupe keys during replays, and the status store's write volume. We partitioned the status table by day and kept thirty days hot.

Things that went wrong

A few failures I still think about.

The replay storm. A consumer deploy went out with a bug that skipped acknowledgements. When it was rolled back, the bus redelivered about four hours of events at once. Dedupe caught the vast majority, but our collapse window code had a bug with late-arriving events and produced a burst of "and 37 more updates" summaries. Users were confused rather than annoyed, which counts as a near miss. We added a rule: events older than the collapse window go straight to the digest path, never to a live push.

The time zone default. For a while, users without a stored time zone defaulted to the server's, which was UTC. Every one of them on the US west coast got quiet hours that ended at midnight. The fix was trivial. Finding it took a week, because nobody complains about a notification at 1am in a structured way.

The silent token rot. Push providers tell you when a token is unregistered, but only when you try to send to it. Users who reinstalled the app had a dead token and a live one, and we sent to both. Delivery looked fine; the error rate looked noisy. Pruning tokens on the first hard failure cut push errors by more than half overnight.

What I'd do differently

Start with the status store. We built the dispatcher first and the per-message history later. It should be the other way round. Visibility is what makes every other change safe, and it's what turns support from a cost into a feedback loop.

Make preferences a product, not a settings page. Most users never opened notification settings. What worked was inline control: "Too many of these? Mute this listing." One tap, right where the annoyance happens.

Give notifications an owner. For a long time they were a side effect of every other feature, so nobody owned the overall experience. The moment one team owned the dispatcher end to end — the rules, the budget, the complaints — the complaints dropped and the volume kept climbing.

Budget, don't just rate-limit. A per-user daily budget across all producers would have prevented most of the "too many" complaints before they happened. Rate limits protect providers. Budgets protect people.

None of this is clever. It's a handful of plain ideas applied in one place, consistently. That's most of what scale turned out to be.