Sub topic 12
Notifying offline users
This chapter assumes you have read the chapters on the one-to-one message flow, acknowledgements and idempotency, and presence with heartbeats. You should know that a message is persisted with a per-chat sequence number before delivery is attempted, and that presence is derived from heartbeats with a time-to-live.
What a push notification is for
A user whose app is closed has no WebSocket connection, so the connection server cannot deliver to them. A push notification is a message sent through the phone vendor's service: Apple Push Notification service (APNs) for iOS, and Firebase Cloud Messaging (FCM) for Android. The vendor keeps its own always-on connection to the device, so it can reach a device your servers cannot.
A push is a hint, not a delivery channel. It tells the device that something is waiting. The message itself is already in the chat log, and the app fetches it when it opens or reconnects. This keeps the delivery guarantee in one place. Push can be late, dropped, or collapsed by the vendor, and the user still loses nothing.
Where push fits in the flow
The decision to push happens after the message is stored. The chat server looks up where each recipient device is connected, using the routing table from the architecture chapter. Any device with no live connection becomes a candidate for a push.
Two design choices in this flow matter.
- The sender's ack does not wait for the push. The ack means the message is durably stored. Push is slow and can fail, so it runs asynchronously through a queue.
- The queue decouples the chat server from vendor calls. If APNs is slow, jobs wait in the queue and chat delivery for online users is unaffected.
Deciding who gets a push
Presence alone is a weak signal. A heartbeat TTL of 30 seconds means a user who just lost signal still looks online for up to 30 seconds. If you skip the push because of presence, that user gets nothing. Use the actual delivery result as well.
| Situation | Action |
|---|---|
| Device has a live connection and acks the message | No push |
| Device has a live connection but no ack within a timeout | Push, and keep retrying over the socket |
| Device has no connection | Push |
| User is online on a laptop, phone app is closed | Push to the phone only if your product wants it, or wait a grace period |
| Chat is muted and the message has no mention | No push |
| User is in do-not-disturb hours | Defer or drop, per user settings |
The grace period is a short delay, often a few seconds. Before sending, the worker rechecks whether any device has acked or read the message. This avoids a buzzing phone when the user has already seen the message on another device.
The device token registry
The vendor identifies a device by a token. You store tokens per device, not per user, because one user can have several devices.
| Column | Purpose |
|---|---|
| user_id | Partition key for lookup by recipient |
| device_id | Stable identifier generated by the app |
| platform | `ios` or `android`, selects the vendor |
| token | Vendor token used as the push address |
| updated_at | Lets you expire stale tokens |
Tokens change. The app must send its current token on every launch, and the server upserts it by device_id. When a vendor reports a token as invalid (APNs answers 410 Unregistered, FCM answers UNREGISTERED), the worker deletes that token. If it doesn't, your queue spends effort on dead addresses forever.
A worker sketch
This runnable sketch separates the decision, the payload, and the cleanup of dead tokens. The vendor call is passed in as a function, so it can be replaced with a real APNs or FCM client.
from dataclasses import dataclass
class TokenGone(Exception):
"""Raised when the push vendor says a token is no longer valid."""
@dataclass
class Device:
device_id: str
platform: str
token: str
connected: bool
def devices_to_notify(devices, muted, mentioned):
if muted and not mentioned:
return []
return [d for d in devices if not d.connected]
def build_payload(chat_id, seq, unread):
# No message text: the app fetches it from the chat log.
return {"chat_id": chat_id, "seq": seq, "badge": unread}
def notify(devices, payload, send, registry):
sent = []
for d in devices:
try:
send(d.token, payload)
sent.append(d.device_id)
except TokenGone:
registry.pop(d.device_id, None)
return sent
registry = {
"phone": Device("phone", "ios", "tok-1", connected=False),
"old": Device("old", "android", "tok-dead", connected=False),
"laptop": Device("laptop", "web", "tok-3", connected=True),
}
def fake_send(token, payload):
if token == "tok-dead":
raise TokenGone(token)
targets = devices_to_notify(list(registry.values()), muted=False, mentioned=False)
sent = notify(targets, build_payload("c1", 42, 3), fake_send, registry)
assert sent == ["phone"]
assert "old" not in registry
assert devices_to_notify(list(registry.values()), muted=True, mentioned=False) == []Payload design
Vendors cap payload size at about 4 KB, so a push cannot carry long messages or attachments anyway. There are also privacy reasons to keep it small.
- Push vendors are third parties. Putting message text in the payload exposes it to them.
- With end-to-end encryption the server cannot read the text at all. It can send only an opaque "new message" signal, or ciphertext that a notification extension on the device decrypts.
- Include
chat_idandseq. The app usesseqto fetch exactly the messages after its last known sequence number.
Some platforms let the app run a short background task on receipt of a data push. The task can fetch and decrypt the message, then show a notification with real text. Treat this as an optimization. Vendors throttle background pushes, and the OS may not run the task.
Retries, collapsing, and rate limits
Push workers need the same discipline as any other at-least-once consumer.
- Retry transient errors. Retry on timeouts and 5xx responses with exponential backoff and jitter. Do not retry on invalid-token errors.
- Make jobs idempotent. A job keyed by
(user_id, chat_id, seq)can be redelivered by the queue. A duplicate push is annoying but harmless, and a collapse key can hide it. - Collapse bursts. If 30 messages arrive in a minute, send one notification per chat with the latest
seqand an unread count. APNs supportsapns-collapse-idand FCM supportscollapse_key, so the vendor replaces older pending pushes. - Respect vendor limits. Both vendors throttle senders. Keep a per-vendor rate limiter in the worker pool.
Group chats
In a group of 500 members, one message can create hundreds of push jobs. Apply these rules while fanning out.
- Skip members who muted the group, unless they were mentioned.
- Skip members who are connected and acking.
- For very large groups, default to notifying only on mentions or replies.
- Enqueue jobs in batches, one per recipient, so a slow vendor call for one user does not block others.
Common failure modes
- Skipping the push because presence says online. The user dropped off 10 seconds ago and gets nothing until they open the app. Base the decision on acks.
- Never deleting dead tokens. The registry grows, the queue wastes work, and some vendors penalize senders with many invalid tokens.
- Pushing before the message is stored. The user taps the notification and the app syncs an empty log. Always persist first.
- Sending message text in the clear. This leaks content to a third party and breaks end-to-end encryption.
- Blocking the send path on the vendor. A vendor outage then stops chat for everyone. Keep push behind a queue.
Exercise
A user's phone loses signal. Their last heartbeat was 10 seconds ago, and the presence TTL is 30 seconds. A friend sends them a message. Why can a push policy that checks only presence fail here, and what should the system check instead?
Show answer
Presence still reports the user as online for up to 20 more seconds, so a presence-only policy would skip the push, and the user would not be notified until they reopen the app. The system should check whether the message was actually acked over a live connection. If no ack arrives within a timeout, it should send the push. The message stays in the chat log either way, so the client also syncs from its last sequence number on reconnect.
Exercise
Your push worker receives an UNREGISTERED error from FCM for a token. What should it do, and why should it not retry the request?
Show answer
It should delete that token from the device registry. UNREGISTERED means the token is permanently invalid, for example because the app was uninstalled. Retrying cannot succeed and only wastes queue capacity and vendor rate limit. Transient errors such as timeouts or 5xx responses are the ones to retry with backoff.