Sub topic 17
Monitoring and observability
This chapter assumes you have read the chapters on queues and workers, retries and backoff, and delivery tracking. You should be comfortable reading short Python snippets and know what a counter and a percentile are.
Why a notification system needs its own monitoring
A notification pipeline can fail without anyone noticing. If a web server crashes, users see an error. If a push provider rejects every token, the API still returns 202 Accepted, the queues drain, and workers look healthy. The only symptom is that people stop getting messages, and they may not complain for days.
Observability means you can answer new questions about the system's behavior from the data it emits. It rests on three kinds of data:
- Metrics are numbers aggregated over time, such as sends per minute. They are cheap to store and good for alerts and dashboards.
- Logs are records of individual events. They are good for explaining one failure.
- Traces follow one request across services. They show where time went.
For a notification system, metrics tell you that something is wrong, and logs and traces tell you why.
Following one notification through the pipeline
Each stage can lose, delay, or duplicate a message, so each stage needs its own signals.
Use one identifier, the event_id, in every log line and trace span along this path. That lets you answer "what happened to evt-1001?" with a single search.
The metrics that matter
Start with a small set and add more only when an incident shows a gap.
| Stage | Metric | Why it matters |
|---|---|---|
| Ingestion | Events accepted and rejected per minute, by reason | A drop in accepted events often means a producer broke. A rise in rejections means bad payloads. |
| Queue | Depth and age of the oldest message, per channel and priority | Depth alone misleads. A queue with 10,000 messages that drains in seconds is fine. A queue with 50 messages that are 20 minutes old is not. |
| Worker | Send attempts by channel and outcome (`success`, `transient_error`, `permanent_error`) | This gives you the success rate per channel. |
| Worker | Retries and dedup skips | Rising retries signal a struggling provider. A burst of dedup skips signals a producer or consumer replaying events. |
| Provider | Call latency (p50, p95, p99) and error codes | Isolates provider trouble from your own bugs. |
| Delivery | Time from event accepted to provider accepted, and to receipt | This is the end-to-end latency users feel. |
| Dead letter queue | Size and growth rate | Every message in it is a notification that failed for good. |
Queue age is usually the best single health signal, because it rises whether the cause is a slow provider, a stuck worker, or too little capacity.
Label carefully
A label (also called a dimension or tag) splits a metric into series, for example channel="push". Good labels have few distinct values: channel, priority, provider, outcome, and error class. Do not use user_id, event_id, or device tokens as metric labels. Every distinct value creates a new time series, and millions of series overload most metrics systems. This problem is called high cardinality. Put those identifiers in logs instead.
Instrumenting a worker
The following sketch uses only the standard library, so you can run it as shown. In production you would use a client library such as Prometheus or OpenTelemetry, but the shape is the same.
import json
import time
from collections import Counter
class Metrics:
def __init__(self):
self.counts = Counter()
def inc(self, name, **labels):
self.counts[(name, tuple(sorted(labels.items())))] += 1
def success_rate(self, channel):
ok = total = 0
for (name, labels), count in self.counts.items():
label_map = dict(labels)
if name == "send_attempts" and label_map.get("channel") == channel:
total += count
if label_map.get("outcome") == "success":
ok += count
return ok / total if total else None
metrics = Metrics()
def log_event(level, message, **fields):
record = {"ts": round(time.time(), 3), "level": level, "message": message}
record.update(fields)
print(json.dumps(record, sort_keys=True))
def record_attempt(event_id, channel, outcome, enqueued_at, error_code=None):
metrics.inc("send_attempts", channel=channel, outcome=outcome)
queue_wait = time.time() - enqueued_at
log_event(
"info" if outcome == "success" else "warning",
"send attempt",
event_id=event_id,
channel=channel,
outcome=outcome,
error_code=error_code,
queue_wait_seconds=round(queue_wait, 3),
)
now = time.time()
record_attempt("evt-1001", "push", "success", enqueued_at=now - 0.4)
record_attempt("evt-1002", "push", "transient_error", enqueued_at=now - 2.0, error_code="503")
record_attempt("evt-1003", "push", "success", enqueued_at=now - 0.2)
print("push success rate:", metrics.success_rate("push"))Three details are worth copying. The log line is JSON, so a log system can filter on channel or error_code without parsing text. The event_id appears in the log but not in the metric labels. Queue wait time is measured at the moment of the attempt, so it includes any time spent in retries.
The log carries no message body, phone number, email address, or device token. Logs are often kept longer and shared more widely than the primary database, so treat them as part of your privacy surface.
Alerting on symptoms
Alert on what users experience, and use cause-level metrics to diagnose. Good alerts for this system include:
- Oldest queue message age above a threshold for a channel and priority. Make the threshold much tighter for critical messages, such as one-time passcodes, than for marketing batches.
- Send success rate for a channel and provider below a baseline for several minutes.
- Dead letter queue growing faster than a set rate.
- Provider p99 latency above your worker timeout, which predicts a retry storm.
- A sudden drop in accepted events compared with the same hour last week. This catches a silent producer failure.
Require a condition to hold for a few minutes before paging. A single failed call is expected, because retries exist for that reason. Paging on every transient error teaches the team to ignore pages.
Distinguish failure classes
Split errors into at least three groups: transient (retry), permanent (for example an invalid or unregistered token), and rejected by policy (opt-out or quiet hours). A rise in permanent errors usually points to stale device tokens, not an outage. A rise in policy rejections may be a product change. If you combine these into one "failures" number, you cannot tell which kind of problem you have.
Beyond infrastructure health
Provider acceptance does not equal delivery. Track receipts, bounces, and unsubscribe events as described in the delivery tracking chapter. Watch the ratio of delivered to accepted per provider, and the share of notifications that never receive any receipt. A provider can return success for every call while its delivery rate falls.
Add a synthetic probe: a test account that receives a notification through each channel every few minutes, with a check that it arrives within a time limit. This tests the whole path, including the parts you do not control, and it catches failures that look healthy from inside.
Sample traces rather than collecting every one. Keep all traces for errors and slow requests, and a small fraction of the rest.
Common mistakes
- Watching only queue depth. Depth hides slow draining. Track the age of the oldest message.
- Averaging latency. Averages hide the slow tail. Use percentiles.
- No baseline. An alert for "fewer than 100 sends per minute" fires every night. Compare against the same time of day and week.
- Ignoring the dead letter queue. Without an alert and a review routine, it becomes a place where notifications are silently lost.
- Different identifiers in each service. If the API, worker, and receipt handler do not share
event_id, you cannot reconstruct one message's history.
Exercise
Your push queue holds only 40 messages, so the depth alert is quiet, but users report that order-shipped notifications arrive 15 minutes late. Which metric would have caught this, and what would you check next?
Show answer
The age of the oldest message in the push queue (or the queue wait time at the worker) would show the 15-minute delay even though depth is small. Next, compare worker send attempts and provider p95/p99 latency. Slow provider calls, a stuck or under-provisioned worker pool, or a rate limit that is throttling this channel would each explain old messages in a short queue. Then search logs by the event_id of an affected notification to see where the time was spent.