Stateless at Scale: Mobile Authentication Done Right

Why mobile auth is different
Web sessions benefit from cookies, same-site policies and relatively stable connections. Mobile apps live in a harsher world: aeroplane mode, OS background limits, shared devices and users who expect to stay logged in for months. Document rotation, expiry and failure behaviour where on-call engineers look during incidents, not buried wikis. Mobile refresh flows should degrade gracefully offline; forced re-login during travel erodes perceived reliability quickly.
Authentication architecture must handle token refresh gracefully, recover from expired credentials without forcing unnecessary re-login and fail safely when tokens are stolen or replayed. Load-test hot paths at peak multiples; margins reveal authentication and logging surprises before launch day traffic. Separate authentication services from business APIs so scaling and deployment cadences do not entangle unnecessarily.
The goal is not statelessness for its own sake. It is reducing coupling between client longevity and server-side session storage while keeping enough control to revoke access when people leave or devices are lost. Prefer boring standards over bespoke crypto; differentiation should not live in hand-rolled token parsing logic. Monitor clock skew and certificate expiry proactively; both cause authentication outages that look like application bugs.
Design logout and revocation to propagate within minutes when users report device theft or departure.
Access tokens and refresh tokens
Access tokens should be short-lived — often fifteen minutes to an hour depending on risk. They authorise API requests and carry claims about identity and permissions. Keep payloads lean; every byte ships on every call. Treat audit queries as features with SLAs when compliance teams depend on them during weekly investigations. Avoid logging raw tokens; structured correlation ids debug incidents without creating new secret leakage paths.
Refresh tokens live longer — days or weeks — and are used only against a dedicated token endpoint to obtain new access tokens. Never send refresh tokens to general business APIs. Keep write paths idempotent; retries are inevitable from mobile networks and asynchronous workers alike. Test backward compatibility when tightening validation rules — old mobile builds linger in stores for months.
Rotate refresh tokens on each use: issue a new refresh token and invalidate the previous one. Detect reuse of an old refresh token as a potential theft signal and revoke the entire token family. Expose metrics for token errors, issuance rate and latency so regressions surface in dashboards before user complaints. Use rate limits on token endpoints to reduce brute force and buggy client retry storms during partial outages.
Prefer standard claims and well-named roles over ad hoc JWT fields that each service interprets differently.
JWT done responsibly
JSON Web Tokens are convenient carriers for signed claims, but they are not a substitute for thoughtful authorisation. Sign with strong algorithms, validate issuer and audience on every request and reject expired tokens without exception. Version architecture decisions with dates and owners so future teams inherit context instead of repeating debates. Audit mobile key storage during security reviews; platform secure enclaves are baseline, not optional extras.
Avoid putting sensitive personal data in JWT payloads. They are encoded, not encrypted, and may appear in logs. Include subject identifier, issued-at, expiry and permission references — not entire user profiles. Prefer explicit tenant scoping in tokens and queries over implicit conventions new services may forget to enforce. Plan key rotation without global logout where possible — overlapping signing keys smooth operational transitions.
Plan for revocation. Short access token lifetimes limit exposure, but maintain a revocation list or session registry for refresh tokens and high-risk events such as password change or reported device theft. Cap session counts per device where fraud teams see credential stuffing; convenience trades against detectability. Document break-glass access separately from routine roles; infrequent use should still leave clear audit trails.
Align session duration with risk — consumer apps differ from financial products with stricter expectations.
Secure storage on the client
Where tokens live on the device matters enormously. Platform secure storage — iOS Keychain, Android Keystore — is the baseline. Plain text in preferences or async storage is an avoidable breach waiting to happen. Consider step-up authentication for sensitive actions even when sessions remain valid for routine browsing.
Biometric unlock can guard access to stored credentials without re-prompting passwords on every app open. Balance convenience with policy: financial and health apps often require stricter re-authentication intervals. Review third-party identity integrations whenever vendors change token formats or deprecate grant types.
Assume rooted or jailbroken devices exist in your user base. Client-side security raises the bar; server-side validation and anomaly detection provide the real enforcement layer. Immutable logs complement monitoring; alerts on anomalous write patterns catch tampering attempts early.
Read models for audit UI can denormalise safely when sourced from immutable events rather than mutable tables.
Login, logout and session hygiene
Logout must invalidate refresh tokens server-side, not just delete local copies. Users expect "sign out everywhere" to work when they report a lost phone. Correlate mobile client version in auth logs to spot outdated builds hitting deprecated endpoints after changes.
Offer device management: list active sessions, last used timestamps and the ability to revoke individual devices. This transparency builds trust and reduces support load. Prefer centralized session revocation registries over hoping short TTLs alone cover every theft scenario.
Password reset and role change should cascade to token invalidation immediately. Do not wait for natural expiry when trust in the credential has clearly ended. Challenge assumptions during design reviews — stateless patterns still need operational hooks for fraud teams.
Invest in developer experience for auth libraries; inconsistent implementations across services create holes quickly.
Authorisation is a separate layer
Authentication proves who the user is. Authorisation decides what they can do. Mixing the two in token claims without a clear model leads to bloated JWTs and painful permission updates. Audit mobile key storage choices during security reviews; platform secure enclaves are baseline, not optional extras. Mobile refresh flows should degrade gracefully offline; forced re-login during travel erodes perceived reliability quickly.
Prefer referencing roles or permissions by identifier and resolving fine-grained access server-side against current policy. Tokens prove identity; your API enforces entitlements on each request. Separate authentication services from business APIs so scaling and deployment cadences do not entangle unnecessarily.
For multi-tenant systems, always validate tenant context explicitly. A valid token for tenant A must never mutate data in tenant B because of a missing check in one handler. Monitor clock skew and certificate expiry proactively; both cause authentication outages that look like application bugs.
Operational concerns at scale
Token endpoints become hot paths. Rate limit them, monitor failure rates and alert on refresh storms that may indicate credential stuffing or a buggy client release. Avoid logging raw tokens; structured correlation ids debug incidents without creating new secret leakage paths.
Clock skew breaks expiry validation. Allow small leeway and ensure NTP discipline on servers. Mobile devices with wrong clocks are more common than teams expect. Review third-party identity integrations whenever vendors change token formats or deprecate grant types unexpectedly. Test backward compatibility when tightening validation rules — old mobile builds linger in stores for months.
Document key rotation for signing keys. Support overlapping valid keys during rotation so you can replace material without forcing global logout. Use rate limits on token endpoints to reduce brute force and buggy client retry storms during partial outages.
Getting the trade-offs right
Pure stateless JWT APIs without refresh rotation simplify early development and complicate incident response. Pure server sessions simplify revocation and resist horizontal scaling. Correlate mobile client version in auth logs to spot outdated builds hitting deprecated endpoints after server changes. Audit mobile key storage during security reviews; platform secure enclaves are baseline, not optional extras.
The hybrid model — short JWT access tokens, rotated refresh tokens, central revocation registry — is the pragmatic default for consumer and B2B mobile products at scale. Prefer centralized session revocation registries over hoping short TTLs alone cover every theft scenario adequately. Plan key rotation without global logout where possible — overlapping signing keys smooth operational transitions.
Invest in the boring parts: secure storage, token rotation, session lists and clear logout. Users notice seamless sign-in; security teams notice when those foundations are missing. Challenge assumptions during design reviews — stateless patterns still need operational hooks for fraud and abuse teams. Document break-glass access separately from routine roles; infrequent use should still leave clear audit trails.
Evolving the pattern over time
Document why you chose this architecture, what alternatives you rejected and when you would revisit the decision. Future teams inherit context, not guesswork. Invest in developer experience for auth libraries; inconsistent implementations across services create security holes quickly. Consider step-up authentication for sensitive actions even when sessions remain valid for routine browsing.
Validate assumptions with load tests and failure injection before marketing campaigns or customer launches spike traffic in ways lab environments never replicated. Treat authentication migrations as product projects with comms, support scripts and phased rollout plans prepared early. Review third-party identity integrations whenever vendors change token formats or deprecate grant types.
Tie onboarding for new engineers to decision records linked to real migrations and incidents — the fastest way to prevent accidental reintroduction of solved problems. Document rotation, expiry and failure behaviour where on-call engineers look during incidents, not buried wikis. Immutable logs complement monitoring; alerts on anomalous write patterns catch tampering attempts early.
At a glance
Stateful server sessions work until they do not — especially for mobile clients that reconnect constantly and expect to stay signed in for weeks.
A well-designed JWT and refresh token model gives you horizontal scale and clear revocation paths without sacrificing security hygiene.
Use short-lived access tokens and long-lived refresh tokens with rotation
Store refresh tokens securely — platform keychain, not local storage
Bind tokens to device identity where risk warrants it
Revoke sessions centrally without waiting for tokens to expire
Separate authentication concerns from authorisation and business logic
