Sub topic 9
Managing device tokens
This chapter assumes you have read the chapters on provider integration and retries. It also assumes you can read short Python snippets.
What a device token is
A device token is an identifier that a push provider issues for one app installation on one device. Apple Push Notification service (APNs) issues device tokens. Firebase Cloud Messaging (FCM) issues registration tokens. Your system can't push to a user directly. It can only push to a token, so the token store decides whether push delivery works at all.
Tokens change. A token can be replaced after a reinstall, a restore from backup, or an OS or provider refresh. It can also expire when the app is unused for a long time. A stored token is therefore a guess about where the user can be reached, not a fact.
Storing tokens
One user usually has several devices, so tokens are a one-to-many relation from user to token. Store at least these fields:
token, which is unique across all usersuser_idplatform(ios,android, orweb)last_seen, updated each time the app registersstatus(activeorinvalid)
The app should send its token on every launch. The upsert below handles new tokens, refreshed timestamps, and shared devices.
import time
class TokenRegistry:
def __init__(self):
self._tokens = {} # token -> record
def register(self, user_id, token, platform):
# The same token under a new user means someone else logged in
# on this device, so ownership moves to the new user.
self._tokens[token] = {
"user_id": user_id,
"platform": platform,
"last_seen": time.time(),
"status": "active",
}
def active_tokens(self, user_id):
return [
t for t, r in self._tokens.items()
if r["user_id"] == user_id and r["status"] == "active"
]
def mark_invalid(self, token):
if token in self._tokens:
self._tokens[token]["status"] = "invalid"
def unregister(self, token):
self._tokens.pop(token, None)
registry = TokenRegistry()
registry.register("user-42", "tok-a", "ios")
registry.register("user-42", "tok-b", "android")
print(registry.active_tokens("user-42")) # ['tok-a', 'tok-b']Token lifecycle
Cleaning up
Clean up tokens in three ways:
- React to provider feedback. When a send fails permanently, call
mark_invalid. APNs returns HTTP 410 for an unregistered token. FCM returnsUNREGISTERED. Do not retry these. They are permanent failures, unlike the timeouts and 5xx errors that the backoff logic handles. - Remove on logout. The app should call an unregister endpoint before the session ends. Otherwise the next person to log in on that device may receive the previous user's notifications.
- Expire stale tokens. A scheduled job deletes tokens whose
last_seenis older than your threshold, such as 60 days.
Common errors
- Keeping
user_idas the key, so a second device overwrites the first. - Not making
tokenunique, which causes duplicate pushes to one device. - Skipping the logout cleanup, which sends private content to the wrong person.
- Removing a token on any failure, including temporary ones.
Exercise
A user logs out on a shared tablet, and a different user logs in on it. The app registers the same token for the new user. What should the registry do, and why?
Show answer
Treat the token as unique and reassign it to the new user, as the register upsert does. Otherwise the old user would keep receiving notifications on a device they no longer use, and the new user's notifications could be delivered twice. The app should also call unregister at logout.