Sub topic 9
Managing device tokens
This chapter assumes you have read the chapters on provider integration and retries. You should know that a worker calls a push provider such as APNs (Apple) or FCM (Firebase Cloud Messaging) and that some failures are transient. You should also be comfortable reading short Python snippets and thinking about key-value or relational storage.
What a device token is
A device token is an opaque string issued by a push provider. It identifies one app installation on one device. You send a push by giving the provider the token and a payload. The provider routes the message to that installation.
Three properties shape the design:
- The token is not a user id. One user can have a phone, a tablet and a web browser, and each has its own token.
- The token can change. The provider may rotate it. Reinstalling the app, restoring a backup, or clearing app data can also produce a new one.
- The token can die. After an uninstall, the provider eventually reports the token as invalid. Sending to it wastes capacity and can hurt your standing with the provider.
Your system therefore needs a registry that stays accurate as devices come and go.
The data model
Store one row per token, not a list of tokens on the user record. A per-token row lets you look up a token directly when the provider reports it dead.
| Field | Purpose |
|---|---|
| token | Unique key. The value the provider gave the app. |
| user_id | The user who currently owns the token. Indexed for fan-out. |
| platform | ios, android or web. Selects the provider and payload format. |
| app_version | Helps you avoid sending payloads an old client cannot render. |
| active | False after a permanent failure or logout. |
| last_seen | Updated on every registration call. Used for pruning. |
Make token unique across the whole table, not just per user. This matters on shared devices. If user A logs out and user B logs in on the same phone, the app registers the same token for user B. Without a global uniqueness rule, user A's notifications would still reach that phone, which is a privacy bug.
The token lifecycle
Tokens move through a small set of states. The diagram shows the transitions your registry must support.
Registration
The client should send its token to your API on every app launch, not only the first one. This call is cheap. It keeps last_seen fresh and picks up rotated tokens without special logic. Handle it as an upsert keyed on the token. If the token already exists, update user_id, app_version and last_seen, and set active to true.
Authenticate the call. An unauthenticated endpoint would let anyone attach a token to an arbitrary user.
Logout and account switching
When a user logs out, the client should call an unregister endpoint, and the server should mark the token inactive. Do not rely on the client alone, because the app may be killed before the call completes. The upsert-by-token rule above is the safety net. The next login on that device moves the token to the new user.
Provider feedback
The provider is the final authority on whether a token works. Your worker must classify each response and act on it.
| Outcome | Examples | Action |
|---|---|---|
| Success | HTTP 200 from APNs, a message id from FCM | Record as sent. |
| Token permanently invalid | APNs 410 `Unregistered`, FCM `UNREGISTERED` | Deactivate the token. Do not retry. |
| Token malformed or wrong environment | APNs 400 `BadDeviceToken`, FCM `INVALID_ARGUMENT` | Deactivate and log. Check for a sandbox/production mix-up. |
| Transient | Timeout, 5xx, provider throttling | Retry with backoff and jitter. |
Check the current provider documentation for exact codes, since they change over time. The key rule is that permanent token errors must not enter the retry path. Retrying a dead token never succeeds, and it consumes your rate budget.
Pruning stale tokens
Many dead tokens never produce an error, because the device is simply gone. A periodic job should deactivate tokens whose last_seen is older than a threshold, then delete inactive rows after a retention window. FCM's documentation treats tokens unused for about 270 days as expired. Many teams prune sooner, such as at 60 to 90 days, depending on how often users open the app.
A working registry
This sketch keeps the registry in memory so you can run it. A real system would use a database with a unique index on token and an index on user_id.
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
@dataclass
class DeviceToken:
token: str
user_id: str
platform: str
active: bool
last_seen: datetime
class TokenRegistry:
def __init__(self):
self._by_token = {}
def register(self, token, user_id, platform, now=None):
"""Upsert by token. A token always belongs to exactly one user."""
now = now or datetime.now(timezone.utc)
self._by_token[token] = DeviceToken(token, user_id, platform, True, now)
def deactivate(self, token):
record = self._by_token.get(token)
if record:
record.active = False
def active_tokens(self, user_id):
return [
t for t in self._by_token.values()
if t.user_id == user_id and t.active
]
def prune(self, max_age_days=60, now=None):
"""Deactivate tokens not seen recently. Returns how many changed."""
now = now or datetime.now(timezone.utc)
cutoff = now - timedelta(days=max_age_days)
count = 0
for record in self._by_token.values():
if record.active and record.last_seen < cutoff:
record.active = False
count += 1
return count
PERMANENT_TOKEN_ERRORS = {"Unregistered", "BadDeviceToken", "UNREGISTERED"}
def handle_result(registry, token, error_reason):
"""Return 'ok', 'retry' or 'dropped' for one send attempt."""
if error_reason is None:
return "ok"
if error_reason in PERMANENT_TOKEN_ERRORS:
registry.deactivate(token)
return "dropped"
return "retry"
registry = TokenRegistry()
registry.register("tok-phone", "user-42", "ios")
registry.register("tok-tablet", "user-42", "android")
print(len(registry.active_tokens("user-42"))) # 2
print(handle_result(registry, "tok-tablet", "Unregistered")) # dropped
print(len(registry.active_tokens("user-42"))) # 1
registry.register("tok-phone", "user-77", "ios") # same phone, new login
print(len(registry.active_tokens("user-42"))) # 0The last three lines show the shared-device case. Registering tok-phone for user-77 removes it from user-42 without any extra cleanup.
Fan-out to several devices
An event targets a user, but the push worker sends to tokens. Resolve the user's active tokens at send time, not at enqueue time. A token deactivated a minute ago should not receive a message queued an hour ago.
Each token is a separate delivery attempt with its own outcome. One device may succeed while another fails with Unregistered. Track them separately. Build the deduplication key from the previous chapter to include the token, such as evt-1001:user-42:tok-phone, so a retry for one device does not resend to the others.
If the user's token list is empty, the push channel cannot deliver. Fall back to another enabled channel if your preferences and priority rules allow it. Otherwise record the event as undeliverable on push.
Common errors
- Storing tokens as a list on the user. You then cannot find the owner of a dead token without scanning every user.
- Registering only at first launch. Rotated tokens go unnoticed, and
last_seengoes stale for active users. - Retrying permanent failures. This wastes rate budget and delays real messages.
- Mixing sandbox and production tokens. APNs sandbox tokens fail against the production endpoint. Store the environment with the token or keep separate registries.
- Logging full tokens. A token is a credential for reaching a device. Log a short prefix or a hash.
- Skipping logout cleanup. The previous user keeps receiving notifications on a shared device.
Exercise
A user logs out on a shared tablet, but the app is killed before it can call your unregister endpoint. A different user then logs in on the same tablet. Which design rule makes sure the first user stops receiving pushes on that tablet, and what happens at registration?
Show answer
Token uniqueness across the whole table, with registration as an upsert keyed on the token. When the second user's app registers, the tablet's token already exists, so the row is updated with the new user_id and marked active. The first user no longer has that token among their active tokens, so no pushes reach the tablet for them.
Exercise
Your push worker receives APNs 410 Unregistered for one of a user's three tokens, and a timeout for another. What should the worker do for each?
Show answer
For the 410 response, deactivate the token and do not retry, because the failure is permanent. For the timeout, treat it as transient and retry that token with exponential backoff and jitter. The third token is unaffected, since each token is its own delivery attempt with its own deduplication key.