Why Push Notifications Pass Every Test and Still Fail in Production
Lessons from shipping push notifications in a React Native app with FCM and direct APNs: real devices, sandbox vs production tokens, dead token cleanup, shared phones, and pushes that should expire.
Push notifications look like the easiest feature in a mobile app. Get a token, send a message, done.
Then you ship, and the bug reports are strange. "I never got the invite." "I got a call notification an hour after the call ended." "I'm getting someone else's notifications." Every test passed, and nothing in the logs looks wrong.
I recently built push notifications for a social app I'm working on for a client. Users like each other, chat, call, send gifts and invite each other to games and coffee dates, and each of those needs a push when the app is closed. Android goes through Firebase Cloud Messaging (FCM). iOS goes straight to Apple's APNs with a .p8 key, with no Firebase on iOS at all.
Sending a push was the easy part. Almost every real problem lived around it: tokens, environments, phones and time. Here is what I learned.
The Setup in One Picture
React Native app (expo-notifications)
│ getDevicePushTokenAsync() → native token (FCM on Android, APNs on iOS)
▼
registerPushDevice(token, platform) ──► FastAPI + Postgres (push_devices)
│
something happens (like, invite, call)
│
┌───────────────────────┴───────────────────────┐
▼ ▼
FCM HTTP v1 (Android) APNs HTTP/2 (iOS)
│ │
└──────── dead token? delete it ◄───────────────┘Each token goes to the service that issued it. Every push also writes a row to an in-app notification list (the bell icon), so a lost push never means a lost event.
Lesson 1: Simulators Lie, So Test on Real Phones
The iOS simulator can't receive remote pushes. An Android build without google-services.json never gets a token. Everything can look fine in development while the feature has never actually worked.
So the rule became simple: pushes are only "done" when they arrive on a real device, from a real build. On iOS that is a development build first, and TestFlight later, because they behave differently (see the next lesson).
It sounds obvious. It's also the step most teams skip when the deadline is close.
Lesson 2: Sandbox and Production Tokens Look the Same
On iOS, a development build gets a sandbox token. A TestFlight or App Store build gets a production token. The token itself doesn't tell you which one it is, and each one only works on its own APNs host.
That's the classic "works for the team, fails for users" bug. Developers test on development builds, everything arrives, and the first TestFlight build gets nothing.
Instead of tracking the build type, the backend tries production first and falls back to the sandbox when Apple says the token isn't one of its:
async def send(token: str, push: Push) -> Result:
async with _client() as client:
reason = await _post(client, PRODUCTION_HOST, token, push)
if reason == "BadDeviceToken":
reason = await _post(client, SANDBOX_HOST, token, push)
...One code path, and both kinds of builds just work.
Lesson 3: Send the Native Token, Not a Wrapper Token
There were three ways to get a token in React Native: Expo push tokens, @react-native-firebase/messaging, or the raw device token.
I went with expo-notifications and getDevicePushTokenAsync(), which returns the native token: an FCM token on Android and an APNs token on iOS. Two reasons:
- No middleman. The backend talks to FCM and APNs directly, so there's one less service that can fail or rate-limit.
- No native build risk. The newest React Native Firebase version wanted a different iOS build setup, and the app already had a video/chat SDK with a delicate native linking fix. Adding Firebase on iOS just to get a token wasn't worth breaking calls.
The same native token is also handed to the chat SDK, so chat message pushes and our own pushes use one token per phone.
Lesson 4: Dead Tokens Pile Up Quietly
Tokens die all the time. Users uninstall the app, restore a phone, or the OS rotates the token. If you keep sending to dead tokens, you waste requests, and you lose track of who can actually be reached.
The trick is telling a dead token apart from a bad moment. A network timeout or a 500 from Apple doesn't mean the token is bad. So the senders return one of three results:
class Result(enum.StrEnum):
SENT = "sent"
INVALID_TOKEN = "invalid_token" # never send to this token again
FAILED = "failed" # the service or network failed; keep the tokenOnly these count as dead:
- FCM:
UNREGISTERED,SENDER_ID_MISMATCH(the token belongs to another Firebase project), or a 400 about a malformed registration token. - APNs:
BadDeviceToken(after the sandbox retry),Unregistered,DeviceTokenNotForTopic.
After every send, dead tokens are deleted in one go. Everything else is logged and kept.
A nice side effect: SENDER_ID_MISMATCH makes moving to the client's own Firebase project painless later. Old tokens from our project get rejected once and clean themselves up.
Lesson 5: One Phone, Two Accounts
This is the bug that worries me most in a social app: someone getting another person's notifications.
It happens on shared phones. User A logs out, user B logs in on the same phone, and the token is still linked to A. Now B's phone shows A's likes and messages.
Two rules fix it:
- A token belongs to the last user who registered it. Registering a token that already exists moves it to the new user instead of adding a second row.
- Logout unregisters the token first, before the session is cleared.
device = await session.scalar(select(PushDevice).where(PushDevice.token == token))
if device is None:
session.add(PushDevice(user_id=user_id, token=token, platform=platform))
else:
device.user_id = user_id # same phone, new account: move itThe app registers after login, on every app start, and whenever the OS rotates the token. A user can still have several phones. Deleting the account removes all of them.
Lesson 6: Some Pushes Should Expire
A phone that has been offline will get every queued push once it comes back. For a "Sara liked your profile" push, that's fine. For "Sara is calling you", it's wrong. The call ended long ago, and now the user taps a notification for a call that doesn't exist.
So incoming call pushes get a time-to-live equal to the ring time (30 seconds). If it can't be delivered by then, FCM and APNs drop it:
# APNs
headers["apns-expiration"] = str(int(time.time()) + push.ttl_seconds)
# FCM
android["ttl"] = f"{push.ttl_seconds}s"If nobody answers, a separate "You missed a call" push follows. That one doesn't expire, because it's still true an hour later.
Lesson 7: The Small Things That Hide Pushes
None of these throw an error. They just make pushes quietly not show up:
- Android channels. If the notification channel isn't high importance, the push lands silently in the tray with no banner. The app creates the channel, and every push uses it with high priority.
- Auth tokens for the push services. Apple accepts a provider token for an hour and refuses new ones made more often than every 20 minutes, so we keep one for 50 minutes. The FCM access token is renewed 5 minutes before it expires. Both are thrown away on an auth error so the next push makes a fresh one.
- Keys in
.env. A private key stored on one line with\nneeds real line breaks before signing. That one cost me more time than I'd like to admit. - Foreground. When the app is open and already shows its own popup (an incoming call, a game invite), showing a system banner too is just noise. Those kinds skip the banner, and every push still refreshes the bell count.
What I'd Add Next
Shipping honestly means naming the gaps:
- Delivery tracking. Today, refused pushes are logged. Next is tracking sent, delivered and opened per kind, so a silent failure shows up on a dashboard before a user complains.
- A real ringing screen for calls. Right now an incoming call is a normal notification with one sound. A proper ringing call needs CallKit and VoIP pushes on iOS and a full-screen intent on Android.
- More Android device testing. iOS is verified end to end on a real iPhone. Android needs the same pass across older devices, which is where the weird bugs live.
Key Takeaways
- A push isn't done until it arrives on a real device from a real build.
- On iOS, try production first, then sandbox, so dev and TestFlight builds both work.
- Separate dead tokens from temporary failures, and only delete the dead ones.
- A token belongs to the last user who registered it, and logout unregisters it.
- Time-sensitive pushes like calls need a TTL.
- Keep an in-app notification list, so a lost push never means a lost event.
Building a mobile app where notifications, calls or real-time features have to work for real users? Let's connect and we can talk it through.
Building a mobile app or web platform?
I take products from concept to a production release in 4–6 weeks. Let's talk through your goals.