Anh Tran dev notes

Production bugs from mobile and backend work, written up with the fix and how it was checked.

Note 22 / Flutter / Auth / Mobile

Push tokens and several accounts on one phone: why dedupe by token alone lost notifications

A guest upgraded to a real account and stopped getting push. Then a signed-out phone kept getting the old user's. Dedupe by token and owner, and one ordered logout path.

By
Trần Thế Anh, Software Engineer
Published
Work done
October 2026, AI Note Taker (Flutter, NestJS)
Stack
Flutter, APNs direct from the backend, NestJS, Prisma, Postgres, RevenueCat SDK
Reading
7 min, 1,534 words

Two reports about AI Note Taker’s sign-in flows, both logged on 5 October 2026. When a guest signed in to an account they already had, that account received no push notification on that phone. Separately, a phone that had been signed out still received notifications addressed to the previous user, and RevenueCat still believed the old user was holding the purchase SDK. I first thought these were two bugs. They share one idea: a push token belongs to a device, but I had written the app as if it belonged to an account.

Who owns a token

The app registers its device token with a single PUT to the backend. On the server side, the device table has a unique column on the token, and the register call is an upsert keyed by that token. If the same token arrives from a different user, the row changes owner. A comment I wrote there says why: otherwise the previous user’s notifications keep landing on the new user’s phone. That part was right, and I kept it.

A guest is a real user row created by the guest login, so a guest has a device row too. When a guest signs in to an existing account, the backend merges the guest into that account. In the merge transaction it revokes the guest’s sessions and deletes the guest’s device rows. The comment next to that delete explains the intent: the app registers again right after sign-in, and keeping the row would only send notifications to a user nobody uses.

The app did not register again. The client kept the last registered token in memory and skipped registration when the new token was equal to it:

// before
if (token == _registered) return;
await api.registerDevice(token);
_registered = token;

My own comment on that line says the skip is there on purpose: iOS hands back the same token on every launch, and re-sending an identical request is wasted traffic. I did not check Apple’s documentation for how often the token changes, so I treat that as my observation, not a guarantee. What I can say is that the token is the same across the sign-in, so the guard saw “already registered” and returned. Meanwhile the backend had just deleted the only row for that token. The new account had no device row at all, and nothing in the app would ever create one until the process restarted.

The fix: dedupe by the pair

The client now remembers two values, the token and the user id of the session it was registered for, and skips only when both match:

Future<void> _sync(String token) async {
  final owner = session.current?.userId;
  if (owner == null) return;                       // no session, nobody to attach to
  if (token == _registered && owner != 0 && owner == _registeredFor) return;
  await api.registerDevice(token, locale: AppLocale.tag);
  _registered = token;
  _registeredFor = owner;
}

Two small choices are in there. If there is no session, the app does not register at all, because the backend has nobody to attach the device to. If an older session was saved without a user id, the id reads as 0 and the app registers every time, since an unknown owner can never be proven equal to the last one.

The test I wrote for it drives the same sequence I saw: sign in as a guest, start push, switch the session to the other account without any logout, start push again, then start it a third time for the same account. The expectation is exactly two PUT requests, the first with the guest’s bearer token and the second with the new account’s, and none for the third call. The push service only runs on iOS, so the test sets debugDefaultTargetPlatformOverride for the duration and resets it in a finally; I wrote about why that matters in Flutter Platform.isIOS tests pass locally and fail on CI. I made the test fail first by restoring the old comparison, then pass with the fix.

The person who checked the report reproduced the same sequence independently and it matched mine. Beyond that, my evidence is the test above, which runs against a fake backend, not a real device with a real APNs token.

The other half: logout did almost nothing

The second report was about what logout left behind. When I read the code the cause was plain. logout posted to the backend inside a try/finally, so a network error propagated instead of finishing the sign-out. The method that removes the device registration had no caller. Nothing called the purchase SDK’s log-out either. In the profile screen, deleting the account also called the logout endpoint after the deletion command, with a token that might already be invalid.

All of those fixes live in one method now, because order matters. The doc comment on it spells out why:

Future<void> logout() async {
  await _attempt(push.unregister,   'logout:push-unregister');
  await _attempt(revokeOnServer,    'logout:revoke');
  await _attempt(releasePurchases,  'logout:purchases');
  await session.end(SessionEnd.signedOut);
}

Unregistering push comes first because the backend only removes a device for the owner of the access token, and once the session is gone there is nothing left to prove who is asking. Revoking comes second, because a live refresh token on the server can still mint access tokens after the phone claims to be signed out. The purchase SDK goes back to anonymous third, and the local session is cleared last.

_attempt wraps each helper step in a timeout and records a non-fatal event if it fails, then moves on. A user who taps “sign out” has to get out even with no network, so none of the helper steps may block the final one. Account deletion uses the same order with one difference: if the deletion command itself fails, the method rethrows and re-attaches the device that step one detached, because the account still exists and should keep receiving notifications. An expired session, where the backend already rejected the refresh, cannot unregister anything on the server. That path only forgets the token locally, so the next sign-in registers for the new person.

The purchase SDK and the anonymous id

RevenueCat’s documentation says logOut generates a new anonymous App User ID for the logged-out state, and that when you switch accounts you can call logIn directly without logging out first. The page does not say what happens if you call logOut while already anonymous. My code treats the SDK’s “already anonymous” error as an expected result and swallows it with a log line; that comes from my own handling of the error, and I did not find it described on the page.

After logOut the helper also resets a field that remembers which user the SDK was last configured for. Without that reset, signing back in as the same person looks like “same user” and skips logIn, so a purchase made afterwards belongs to the anonymous id and the webhook cannot match it to anyone. The account-bound side of this is covered in RevenueCat restore behavior and account-bound subscriptions.

A third bug in the same request: the wrong language

While I was in the register-device call I fixed one more thing that the same request carried. It sent the phone’s system locale. The backend’s upsert writes that value into the user’s locale, and push text and error messages read it. A user with a Vietnamese phone who chose English in the app got Vietnamese notifications, and the user’s locale reset to Vietnamese on every launch. The request now sends the language selected inside the app, and when that is unknown it sends no locale at all, so the backend keeps what it has. The test has two cases: a Traditional Chinese selection sends zh-TW, and an unset selection leaves the key out. Mutating the code to send the device language, and to send a fixed fallback, both turned the test red.

Scanning the class, and what is still open

The scans were greps. For the registration state, every place that writes or clears the token also writes or clears the owner. For logout, every route that unregisters push, logs out of the purchase SDK, requests deletion or calls the logout endpoint goes through the repository, and a search for the system locale in the app code finds nothing today. While scanning I also found that the guest login sent only the language code without the region, so a Traditional Chinese user became plain Chinese. I handed it over as a separate item; in the current code that call sends the full language tag.

What I can claim is limited. The fixes are covered by unit tests against a fake backend and a mocked platform channel, with the red-then-green runs described above. I did not run any of this on production, or on a real phone with live push from APNs. Push exists only on iOS in this app; Android has no push service yet, so the Android path for these bugs is not applicable, not tested. The backend’s merge logic is read from code, not exercised by me in this pass.

Sources