📚 Encyclopedia

Flutter & Mobile · updated 2026-11-30

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

Invariants that fixed it

  1. 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.
  2. 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 both reset() and any invalidateCache().
  3. Only treat 401 as "session expired" for requests that actually sent a token; a failed login attempt must not wipe local state.

  4. 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).

  5. 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

See also

Linked from

Sources: tldr memory (release-v1.47.x, release-v1.31.0-audit, release-v1.50.0, feature-ai-model-discovery, completed-work), tldr memory (bug-pin-stale-lists, perf-post-load), 2026-11-29