Singleton services, session caches, and cross-user data leaks in Flutter
flutterriverpodsingletoncachelogoutstale-while-revalidatesecurity
TLDR's services are app-lifetime singletons (wrapped in Riverpod providers). That makes caching cheap and screens fast, but anything a singleton remembers survives logout. Several real bugs were one user's data showing up for the next user on the same device, or a service skipping work because it thought it had already initialized.
Bugs this caused
- The post page cache served user A's pages, including A's vote state, to user B after a re-login.
- Bookmark stars and tag subscriptions carried across accounts.
- The crypto service's
_initializedflag survived logout, so the next login skipped the key-backup path; later an identity guard was added (re-init when the user differs). See E2E key management that never loses a key (keyring, backup, re-wrap). - Push notification
initialize()ran at startup and again on every login, adding duplicate stream listeners (double badge increments, repeated token POSTs). Store theStreamSubscriptions and cancel before re-listening. -
A global "AI status changed" callback was overwritten by each pushed screen and nulled on dispose, leaving the screen underneath deaf. Save the previous handler in
initStateand restore it indispose. -
Run (Flutter game) kept local personal bests, drafts and skins across logout, so the next account to sign in on the same browser uploaded the previous user's PBs as its own during sync. Namespace local storage per user id, or wipe it on logout (Client/server sync pitfalls (deletes, timestamps, merge policies)).
Invariants that fixed it
- One reset function for all session state (
AuthService.resetSessionCaches()), and it runs on every session transition: login, logout, an expired-token 401 handler, and admin impersonation start/stop. The 401 path is the one people forget; an architect review caught a cross-user leak there. - Every service that caches per-user data gets a
reset()and is added to that function the day the cache is added (avatars, model lists, group keys...). Clear caches in bothreset()and anyinvalidateCache(). -
Only treat 401 as "session expired" for requests that actually sent a token; a failed login attempt must not wipe local state.
-
A disk cache is session state too. When list data is persisted for a fast cold start, the same reset deletes those entries, each entry records its user and is discarded on load if it belongs to someone else, and nothing is written while impersonating (Perceived load time in a Flutter app and a cold-start disk cache).
- Mutations go through the service that owns the cache. A screen that calls the API directly (a pin toggle did) changes the server and leaves every cached list showing the old state, with no listener notified. Give the service a method that performs the call and then invalidates and notifies.
Stale-while-revalidate tab screens
v1.47.0 made tab screens paint instantly from the service's last in-memory result, then refresh
silently. Rules that made it safe:
- cachedX getters return copies, not the live list.
- List fetchers return null on failure so callers keep showing current data instead of blanking;
fire-and-forget call sites use ?? const [].
- Once a screen is seeded, the _loading flag no longer covers the fetch window; add explicit
_fetching re-entrancy guards.
- A silent refresh never shows a spinner or resets scroll; pull-to-refresh and first load are the
only visible loads.
Async gaps
- After any
await, checkmountedbefore touching state orcontext. - If an action navigates away (delete then
context.go), capture services and the rootScaffoldMessengerbefore navigating; usingrefafter the screen is disposed crashed the delete-undo path and the undo snackbar never appeared. - Always reset busy flags in
finally; an exception once left_loadingMore = trueforever and blocked pagination.
See also
- Stop Flutter timers from polling while the app is in the background
- Autosaved drafts that come back from the dead (lifecycle pitfalls)
Linked from
- Autosaved drafts that come back from the dead (lifecycle pitfalls)
- Client/server sync pitfalls (deletes, timestamps, merge policies)
- Perceived load time in a Flutter app and a cold-start disk cache
- Stop Flutter timers from polling while the app is in the background
- TLDR platform architecture (tldrnerd.com)