Auth Tokens & Idempotency
DATA › Networking
The full token lifecycle, single-flight refresh under concurrency, idempotency, and its security implications.
A favourite fintech live-coding exercise is a token manager: cache an access token, refresh it when it expires, and stay correct when twenty coroutines ask at once. It compresses idempotency (many calls, one refresh, one result), state consistency under concurrency, and cancellation handling into one small class. Expect follow-ups on the full token lifecycle, why the refresh must be idempotent, and the security side: rotation, reuse detection, and where tokens may and may never live.
What this covers
- Full token lifecycle: authenticate to obtain access + refresh tokens, cache, attach to requests, expiry, refresh, rotation/revocation, and cleanup on logout
- Idempotency: repeating an operation yields the same result as doing it once; retries after timeouts are only safe when the operation is idempotent (idempotency keys for payments/POSTs)
- Single-flight refresh: concurrent callers must share ONE in-flight refresh (Mutex plus re-check, or a shared Deferred), never fire N refreshes
- Re-check after acquiring the lock: another caller may have refreshed while you waited; validate the condition again before acting (the same check-then-act discipline as any race)
- State consistency: keep token + expiry in one immutable value swapped atomically from a single source of truth; a failed refresh must fail cleanly, not corrupt cached state
- Cancellation: one caller being cancelled must not abort the shared refresh other callers await, and must never leave a Mutex held
- Security implications: refresh-token rotation with reuse detection, Keystore-backed encrypted storage (never plaintext prefs or logs), and OkHttp's Authenticator for reacting to 401s
Study this topic
- Auth Tokens & Idempotency explained: the guided lesson
- 14 practice quiz questions
- 9 revision flashcards
- Auth Tokens & Idempotency interview questions and answers