An OAuth 2.0 authorization server looks like a login screen with a “Allow this app to access your account?” button. It is not. It is a credential mint that third-party apps you have never audited use to act on your behalf, and the entire design lives or dies on one question: when a resource owner clicks “revoke access” for some sketchy app, how fast does every server in your fleet stop honoring the tokens that app is holding?

That question is harder than it sounds because of a direct contradiction baked into the requirements. You want access tokens to be self-contained - a signed JWT the resource server can verify with a public key, locally, in microseconds, with no call back to the authorization server - because at scale you cannot afford a database round trip on every single API request. But a self-contained token is valid until it expires by its own clock. Nobody is asking the authorization server whether it is still good. So the moment you make tokens verifiable offline, you lose the ability to revoke them. Offline verification and instant revocation are in direct opposition, and this whole post is about buying both: short-lived access tokens, a push-based revocation channel to the resource server fleet, and rotating refresh tokens with reuse detection as the long-lived credential you can strongly revoke.

This is not “design the consent screen.” This is “design the trust root that a thousand third-party apps and a fleet of stateless resource servers depend on, such that a stolen token has a blast radius measured in seconds.” Let me build it properly.

Functional Requirements (FR)

In scope:

  • Authorization Code flow with PKCE. The standard OAuth 2.0 dance: a third-party client redirects the resource owner to the authorization server, the owner authenticates and consents to a set of scopes, the server returns a short-lived authorization code, and the client exchanges that code server-side (with a PKCE verifier) for tokens. PKCE is mandatory for public clients (SPAs, mobile, native) that cannot hold a secret.
  • Token issuance. Mint a short-lived access token (presented to resource servers on every API call), a long-lived refresh token (used to get new access tokens without re-consent), and, for OIDC, an ID token (identifies the resource owner to the client).
  • Refresh token rotation. Every time a refresh token is used, invalidate it and issue a new one. Detect reuse of an already-rotated refresh token (the signal of a stolen token) and kill the whole token family.
  • Scopes and consent. Tokens carry scopes (read:contacts, write:calendar). The resource owner consents to exactly the scopes a client requested; resource servers enforce them.
  • Revocation. A resource owner can revoke a specific grant (one app’s access) at any time. A client can revoke its own tokens (RFC 7009). An admin can kill all tokens for a compromised user. Revocation must reach the resource server fleet fast.
  • Introspection and discovery. Expose a token introspection endpoint (RFC 7662) for opaque-token resource servers, a JWKS endpoint so resource servers can fetch signing keys, and an OIDC discovery document.
  • Client registration. Register third-party clients (client_id, client_secret or public, redirect URIs, allowed scopes, grant types).

Explicitly out of scope (name it so you own the scope):

  • The primary authentication of the human. Password hashing, MFA, passkeys, the login form - that is an authentication system I designed elsewhere. Here the authorization server has a way to authenticate a resource owner and produce a verified user_id; OAuth is what happens after that, turning an authenticated human into delegated tokens for a third-party app.
  • Fine-grained resource authorization. Scopes are coarse. What a user_id is actually allowed to touch inside the resource (row-level, tenant-level) is the resource server’s own authorization logic. We hand it identity plus scopes.
  • SAML. Enterprise federation via SAML is the same session model in XML with POST bindings. We design OAuth 2.0 / OIDC.
  • The resource servers’ business logic. We define how they verify tokens and learn about revocation; what they do with a valid request is theirs.

The one decision that drives everything: the authorization server issues self-describing, offline-verifiable access tokens, and backstops them with a fast revocation push channel plus aggressively short TTLs. Every hard problem - revocation latency, stolen tokens, logout - falls out of resolving “verify offline, no round trip” against “revoke in seconds.”

Non-Functional Requirements (NFR)

  • Scale: 500M registered resource owners, ~100M daily active. Tens of thousands of registered third-party clients. The read/write asymmetry is the whole story: token issuance (login, consent, refresh) is thousands to low tens of thousands per second; token validation by resource servers is five to six orders of magnitude higher - tens of millions per second across the fleet, because validation is on the hot path of every single API call.
  • Latency: token validation at the resource server must be effectively free - p99 under 1ms of local CPU, no network call on the common path. Token issuance (the authorization code exchange) can afford ~100-300ms; it is rare and interactive. Refresh p99 under 50ms.
  • Availability: 99.99%+ on issuance. Higher effective availability on validation, because validation is offline: the authorization server can be briefly down and resource servers keep accepting unexpired tokens. That decoupling is deliberate - the trust root being momentarily unavailable must not take down every API in the ecosystem.
  • Consistency: issuance is eventually consistent (a new grant visible on a replica a few ms late is fine). Revocation is the one place we pay for speed and strong intent - a revoked token that still validates is a live security hole. We target a bounded revocation propagation window (sub-second to a few seconds) rather than instant global consistency, and we make that bound explicit.
  • Durability: signing keys and the refresh-token store are sacred. Lose the signing key and the fleet trusts nothing you mint; leak it and an attacker mints valid tokens for any user - key material is the crown jewel, lives in an HSM/KMS, and never enters application memory in raw form. Refresh tokens are long-lived bearer credentials; losing the store logs everyone out, leaking it is a breach.
  • Security posture (the real NFR): an access token is a bearer credential - whoever holds it is the user, for its lifetime, with its scopes. So tokens are short-lived, narrowly scoped, sender-constrained where possible, and always revocable through the refresh path. Assume tokens get stolen; design so a stolen access token self-expires in minutes and a stolen refresh token is caught on first reuse.

Back-of-the-Envelope Estimation (BoE)

Real numbers with the arithmetic, because the read/write asymmetry sets the architecture.

Issuance QPS (the rare, interactive path):

500M users, ~100M daily active third-party-app sessions
Each active session: ~1 authorization-code grant + ~8 refreshes/day
  (access token TTL ~5 min; an app active for an hour refreshes ~12x,
   but most sessions are short, so average ~8)
Issuance events = 100M * 9 = 900M/day
  = 900,000,000 / 86,400
  ≈ 10,400 issuance events/sec average
Peak (~10x, morning login + app-open storm) ≈ 100,000/sec

Validation QPS (the real volume, the read path):

Each access token drives many API calls over its ~5 min life.
Say an active app makes ~10 API calls/min while in use.
100M active sessions, assume ~20% concurrently active at peak = 20M
  20M * 10 calls/min = 200M calls/min = ~3.3M validations/sec average
Peak bursts push this to ~30M validations/sec across the resource fleet.

30M validations/sec vs 100K issuance/sec  ->  ~300x asymmetry.

That asymmetry is the entire reason validation must be offline and local. If each of 30M validations/sec hit the authorization server’s introspection endpoint, that is a 30M-QPS self-inflicted DDoS on the one component whose outage breaks everything.

Storage - refresh tokens and grants:

Active grants (user x app with a live refresh token): ~500M
Per grant row: user_id, client_id, scopes, refresh_token_hash,
  family_id, rotation_counter, issued_at, status  ≈ ~300 bytes
500M * 300 bytes ≈ 150 GB of active grant state.
With rotation history + audit kept ~90 days: a few TB.
Comfortably a sharded SQL / KV footprint, not a "big data" problem.

Revocation event volume (the thing we must propagate):

Revocations are rare relative to issuance: password changes, "revoke app"
  clicks, admin kills, reuse-detection trips.
Order ~1,000-5,000 revocations/sec at peak across 500M users.
Each revocation must reach ~tens of thousands of resource-server nodes.
So the fan-out is large, but the event rate is tiny.
A revocation feed of ~5K events/sec fanned to 50K nodes is very tractable;
  this is a fan-out problem, not a throughput problem.

Revocation deny-list size (what each resource node must hold):

Only tokens revoked BEFORE their natural expiry matter. Access-token TTL
  is ~5 min, so a revoked access token is only interesting for < 5 min.
Revocations in a 5-min window at 5K/sec = 1.5M entries, worst case.
Each entry ~16-32 bytes (jti or user+client key) -> ~30-50 MB.
Fits in memory on every resource node trivially, and self-trims as
  entries pass their original expiry.

That last number is the key insight: because access tokens are short-lived, the deny-list a resource server must carry is bounded by TTL times revocation rate, not by total tokens ever issued. Short TTL is what makes the revocation set small enough to replicate everywhere.

High-Level Design (HLD)

The system splits into three planes: the authorization server (issues tokens, owns grants and keys - the rare write path), the resource servers (verify tokens on every API call - the hot read path, stateless), and a revocation propagation channel connecting them (pushes “this token/grant is dead” to the fleet). The central structural idea: the thing on the hot path (validation) must be dumb, local, and offline; the thing that changes state (issuance, revocation) can be slower and strongly consistent; and a cheap async channel bridges them.

 ┌──────────────┐   1. redirect to /authorize (+PKCE challenge, scopes)
 │  Resource    │ ───────────────────────────────────────────────┐
 │  Owner       │ <── consent screen ──┐                          │
 │ (browser)    │   2. approves         │                         ▼
 └──────┬───────┘                       │             ┌───────────────────────────┐
        │ 3. redirect back w/ CODE      │             │   AUTHORIZATION SERVER     │
        ▼                               │             │  ┌──────────────────────┐ │
 ┌──────────────┐  4. POST /token       └─────────────│  │ /authorize  /token   │ │
 │ Third-party  │     code + PKCE verifier ──────────>│  │ /introspect /revoke  │ │
 │ Client       │  5. {access_token (JWT, 5m),        │  │ /jwks  /.well-known  │ │
 │ (app backend)│      refresh_token (opaque, rotates)│  └──────────┬───────────┘ │
 └──────┬───────┘      id_token}  <───────────────────│             │             │
        │                                             │  ┌──────────▼───────────┐ │
        │ 6. API call w/ access_token (Bearer)        │  │ Grant + RefreshToken  │ │
        ▼                                             │  │ store (sharded SQL)   │ │
 ┌───────────────────────────────────────────┐       │  └──────────┬───────────┘ │
 │          RESOURCE SERVER FLEET             │       │  ┌──────────▼───────────┐ │
 │  (stateless, tens of thousands of nodes)   │       │  │ Signing keys (HSM/KMS)│ │
 │  per node, per request, NO round trip:     │       │  └──────────────────────┘ │
 │   - verify JWT signature w/ cached JWKS    │       └───────────┬───────────────┘
 │   - check exp / iss / aud / scope          │                   │ revocation event
 │   - check in-memory REVOCATION DENY-LIST   │                   │ (user/client/jti)
 │   allow -> serve ; denied -> 401           │                   ▼
 └──────────────────────┬─────────────────────┘       ┌───────────────────────────┐
                        │  subscribe / pull            │  REVOCATION CHANNEL        │
                        └─────────────────────────────>│  pub/sub bus + versioned   │
                           in-memory deny-list         │  snapshot (Redis/Kafka)    │
                           updated in < ~1s            │  fan-out to all RS nodes   │
                                                       └───────────────────────────┘

Request flow (two paths that matter):

Issuance (rare, interactive):

  1. The third-party client redirects the resource owner’s browser to /authorize with its client_id, requested scope, redirect_uri, state, and a PKCE code_challenge.
  2. The authorization server authenticates the owner (delegated to the auth system), shows a consent screen for the requested scopes, and on approval issues a one-time authorization code (short TTL, ~60s, single-use), bound to the PKCE challenge and the client.
  3. It redirects back to the client’s redirect_uri with the code.
  4. The client’s backend POSTs to /token with the code, its credentials, and the PKCE code_verifier.
  5. The server validates the code (unused, unexpired, matching client, SHA256(verifier) == challenge), then mints an access token (signed JWT, 5-min TTL), a refresh token (opaque, long-lived, rotating), and an ID token. It records the grant and the refresh-token family.
  6. The client stores the refresh token securely and uses the access token on API calls.

Validation (the hot path, ~30M/sec):

  1. The client calls a resource server with Authorization: Bearer <access_token>.
  2. The resource node, with no network call, verifies the JWT signature using the cached JWKS public key, checks exp, iss, aud, and that the token’s scope covers the operation, then checks the token’s jti/subject against its in-memory revocation deny-list. Pass all -> serve. Fail any -> 401/403.

The revocation channel (described in depth below) continuously pushes revocation events to every resource node so step 8’s deny-list is fresh within a bounded window.

Component Deep Dive

The three hard parts, each walked from naive to scalable: (1) the access-token format - the offline-verify vs revoke tension; (2) revocation propagation to the stateless resource fleet - the headline problem; and (3) refresh-token rotation with reuse detection.

1. Access Token Format: Offline Verification vs Revocability

The first fork in the road is what an access token is, and it determines everything downstream.

Approach A: Opaque token + introspection per request (the naive, revocable start)

The access token is a random 256-bit string. It carries no information; it is a lookup key. On every API call the resource server calls the authorization server’s /introspect endpoint, which checks the token store and returns {active: true, sub, scope, exp}.

Where it breaks: revocation is trivial (delete the row, next introspect says active: false) but validation now costs a network round trip to the authorization server on every one of 30M API calls/sec. That is a 30M-QPS load on the single most critical, hardest-to-scale component in the system - a self-inflicted DDoS on the trust root. Every API call across every third-party app now has the authorization server in its latency path and its failure path. Correct revocation, catastrophic scale.

Approach B: Self-contained JWT, no revocation story (the overcorrection)

Make the access token a signed JWT carrying sub, scope, client_id, iss, aud, exp, jti. The resource server verifies it with the authorization server’s public key (fetched once from JWKS, cached in memory, refreshed periodically). Verification is ~50-200 microseconds of local CPU - no network call, scales perfectly with the fleet, authorization server sees zero validation traffic.

Where it breaks: a signed JWT is valid until exp by its own arithmetic. There is no revocation. If a resource owner revokes an app, or a token is stolen, nothing stops that JWT from being accepted until it expires. With a 1-hour TTL, a stolen token works for an hour after revocation. Unacceptable for a credential that delegates access to strangers’ apps.

Approach C: Short-lived JWT + bounded-window revocation (the answer)

Keep the self-contained JWT for its offline-verify win, and attack the revocation gap on two fronts:

  • Short TTL. Set access-token TTL to ~5 minutes. Now the worst case if revocation propagation failed entirely is a 5-minute window, not an hour. Short TTL turns an unbounded problem into a bounded one, and - critically - it bounds the size of the revocation deny-list (only tokens revoked within the last 5 minutes can still be live), which is what makes propagation to every node feasible (the ~30-50 MB from the BoE).
  • Push-based revocation deny-list. When something is revoked, push the revocation to every resource node so step 8 can reject a still-unexpired token before its natural exp. This closes the window from 5 minutes to the propagation latency (sub-second to a few seconds). This is part 2 below.
Token:  signed JWT, exp = now + 5 min, carries jti + sub + client_id + scope
Verify: local signature check (cached JWKS) + exp/iss/aud/scope   -> microseconds
Revoke: push (jti | user_id | user_id+client_id) to deny-list on every RS node
Window: a revoked-but-unexpired token is honored only until the push arrives
        (bounded by propagation latency), and in absolute worst case until exp

The honest framing for an interviewer: a pure JWT trades revocability for scale; a pure opaque token trades scale for revocability. The production answer takes the JWT’s scale and buys back bounded revocation with short TTL plus a push channel - accepting a small, explicit staleness window rather than paying a round trip per request or waiting a full hour. We never introspect per request; the only thing that crosses the network on the hot path is the API call itself.

2. Revocation Propagation to the Stateless Resource Fleet (the core hard part)

This is the headline problem from the assignment: a resource owner revokes a grant, and tens of thousands of stateless resource-server nodes - each verifying tokens offline, each holding no per-token state - must stop accepting that grant’s access tokens quickly, without any of them doing a synchronous database round trip on every API call. We need the deny-list of step 8 to be both local (so validation stays sub-millisecond) and fresh (so a stolen token dies fast).

Naive: resource servers query a revocation table per request

Each resource node, on every API call, does SELECT 1 FROM revoked WHERE jti = ?. Where it breaks: this reintroduces exactly the round trip we eliminated in part 1 - 30M DB queries/sec against the revocation store, which is now a shared hot dependency on the hot path and a SPOF. We have paid the full cost of opaque tokens to add revocation to JWTs. Dead on arrival.

Better: periodic pull of the revocation list

Each node polls the authorization server every N seconds: “give me all revocations since my last cursor,” merges them into an in-memory set, and checks that set locally per request (no per-request network). Where it improves: validation is local again; the authorization server sees one poll per node per N seconds (50K nodes / 10s = 5K polls/sec), not 30M/sec. Where it is weak: revocation latency equals the poll interval. A 10-second poll means a stolen token can be used for up to 10 seconds after revocation. Shorten the interval and you trade freshness for load. Pull is simple and robust but its freshness floor is the interval.

Best: push-based pub/sub + versioned snapshot for correctness (the answer)

Combine a push bus for low latency with a pull-able snapshot for correctness and recovery - the classic “fast path + slow authoritative path.”

  • Push path (fast, best-effort). On revocation, the authorization server publishes a tiny event {type, key, revoked_at, not_after} to a pub/sub bus (Redis pub/sub, NATS, or a Kafka topic every node consumes). Every resource node subscribes and applies the event to its in-memory deny-list on arrival - propagation in tens to a few hundred milliseconds. key is one of: a specific jti (one token), a user_id+client_id pair (revoke this app’s grant for this user - the “revoke access” click), or a user_id (kill everything for a compromised user). not_after is the original token/grant expiry so the entry can self-trim.
  • Snapshot path (slow, authoritative). The push bus is best-effort - a node that was restarting, newly autoscaled, or briefly partitioned can miss events. So each node, on startup and then every ~10-30s, pulls a versioned snapshot (or delta since its last version) of the current revocation set from a durable store. This is the safety net: push gives you speed, the periodic snapshot guarantees eventual correctness and bounds how long a missed event can matter.
Revocation happens (user clicks "revoke app X"):
  AuthZ server:
    1. write revocation row (durable, versioned, monotonically increasing seq)
    2. PUBLISH {user_id, client_id, revoked_at, not_after} to the bus
                        │                         └── authoritative, pull-able
                        ▼  (fast, best-effort fan-out)
  Every RS node:  receives event in <~300ms, adds (user_id+client_id) to
                  in-memory deny-list.  Next API call with a matching token -> 401.

  Independently, every ~15s each RS node:
    GET /revocations?since=<my_version>  -> merge any events it missed,
    advance its version.  (covers restarts, new nodes, dropped messages)

Deny-list membership check on the hot path. The deny-list is small (bounded by TTL x revocation rate, ~30-50 MB) and held in memory. The common case is “not revoked,” so front the exact set with a bloom filter: a bloom hit is ~nanoseconds and, for the >99.99% of tokens that are not revoked, answers “definitely not revoked” with zero further work. Only a bloom positive (rare - a real revocation or a false positive) falls through to the exact hash-set check. So the per-request cost of revocation checking is a bloom lookup, not a DB query.

What key do you revoke by? Three granularities, all supported:

Revocation typeKey pushedTriggered by
Single tokenjticlient calls /revoke on one token
One app’s grantuser_id + client_idresource owner clicks “revoke this app”
All of a user’s tokensuser_id + min_issued_atpassword change, account compromise

For the user_id case we push a not_before timestamp: reject every token for that user issued_at < not_before. This revokes all existing tokens without having to enumerate their jtis, and tokens minted after the password change (which carry a newer issued_at) are unaffected. This is the cheapest way to express “kill everything issued so far for this user.”

Bounding the window explicitly (the interview payoff). The absolute worst-case staleness is min(access_token_TTL, snapshot_interval + push_failure). In normal operation it is push latency (~100-300ms). If the push bus is fully down, it degrades to the snapshot interval (~15s). If everything breaks, it degrades to the access-token TTL (5 min) because the token simply expires. There is no scenario where a revoked token lives longer than its TTL, and in the common case it dies in a fraction of a second - all without a per-request round trip. That layered bound (push -> snapshot -> TTL) is the design: speed from push, correctness from snapshot, and a hard ceiling from TTL.

The refresh path is the real kill switch. The access token’s short TTL means the durable enforcement point is refresh: even if a resource node somehow missed a revocation, the stolen access token expires in 5 minutes, and the attacker cannot get a new one because the refresh token is revoked and the refresh call hits the authorization server’s strongly consistent grant store directly (one DB read, on the rare refresh path, not the hot path). So revocation is enforced strongly at refresh (synchronous DB check, every ~5 min) and quickly but with bounded staleness at validation (pushed deny-list, every request). That split - strong-but-rare at refresh, fast-but-eventually-consistent at validation - is the heart of the design.

3. Refresh Token Rotation with Reuse Detection

Refresh tokens are long-lived bearer credentials; if one leaks, an attacker can mint access tokens indefinitely. Rotation plus reuse detection turns a stolen refresh token into a detectable, self-defeating event.

Approach A: Static long-lived refresh token (the naive start)

Issue one refresh token that lives for 30 days; the client uses it repeatedly to get access tokens. Where it breaks: if it leaks, the attacker and the legitimate client both use the same token happily, forever, and you have no way to tell a theft occurred. The breach is silent until someone notices anomalous activity. A long-lived static bearer credential with no detection is the worst-case blast radius.

Approach B: Rotation on every use (better, but needs the detection piece)

Every time a refresh token is redeemed at /token, invalidate it and issue a brand-new refresh token in the response. The old one is now dead. Where this helps: the window any single refresh token is valid shrinks to one use. The crucial addition - reuse detection: tie every refresh token to a token family (family_id). When a refresh token is redeemed, you record it as “rotated” (consumed). If you ever see a consumed refresh token presented again, that is the signal: either the attacker stole it and used it (and the legit client later rotates the now-dead one), or the legit client used it and the attacker replays it. Either way, both the thief and the victim cannot hold the current token simultaneously after a rotation - so a replay of an old one means compromise. On reuse detection, revoke the entire family - every token descended from that grant - and force re-authentication.

Grant created -> family F, refresh token R0 (rotation_counter=0, status=active)
Client refreshes with R0:
   R0 -> status=rotated(consumed);  issue R1 (counter=1, active);  new access token
Client refreshes with R1:
   R1 -> rotated;  issue R2 (active);  ...

ATTACKER stole R1 and uses it AFTER the client already rotated R1 -> R2:
   server sees R1 presented but R1.status == rotated  ->  REUSE DETECTED
   -> revoke the whole family F (R0..R2 all dead), publish revocation,
      force re-auth.  The thief's access is cut and the owner is alerted.

The elegant property: rotation makes the refresh token a single-use credential whose reuse is a bright-line theft signal. You do not need to detect anomalous behavior; you detect a protocol violation (presenting a consumed token), which is unambiguous.

Approach C: Hardening the rotation details (the production nuance)

Two real-world wrinkles to name:

  • Benign reuse from network retries. A client sends R1, the server rotates to R2 and responds, but the response is lost to a network blip; the client retries with R1 and now trips reuse detection on an innocent retry. Mitigation: a small grace window - accept the immediately-previous token for a few seconds and return the same R2 (idempotent refresh) rather than treating it as theft, or detect that the presenter is the same client/device fingerprint. Tune the grace so retries survive but real replays (which come later, from elsewhere) still trip.
  • Sender-constrained tokens (DPoP / mTLS). Rotation limits a stolen refresh token to one use; binding it to the client’s key (DPoP proof-of-possession or mTLS client cert) means a stolen token is useless to anyone who does not also hold the private key. This is defense in depth on top of rotation - rotation catches theft after the fact, sender-constraint prevents it from being usable at all. For high-value clients, require both.

Refresh is also where strong revocation is enforced cheaply: the refresh call is rare (~every 5 min per session) and already a synchronous call to the authorization server, so it reads the grant store directly - a revoked grant means the refresh is rejected outright, no new access token, done. The hot validation path stays offline; the rare refresh path carries the authoritative consistency.

API Design & Data Schema

Endpoints

# Authorization (browser redirect, starts the flow)
GET /authorize
  ?response_type=code
  &client_id=app_123
  &redirect_uri=https://app.example/cb
  &scope=read:contacts%20write:calendar
  &state=<csrf-opaque>
  &code_challenge=<base64url(SHA256(verifier))>
  &code_challenge_method=S256
  -> 302 redirect to redirect_uri?code=<authz_code>&state=<state>

# Token exchange (client backend, code -> tokens)
POST /token
  grant_type=authorization_code
  &code=<authz_code>
  &redirect_uri=https://app.example/cb
  &client_id=app_123 &client_secret=<secret>   # or client assertion / PKCE for public
  &code_verifier=<pkce-verifier>
  -> 200 {
       "access_token": "<signed JWT>",
       "token_type": "Bearer",
       "expires_in": 300,                        # 5 minutes
       "refresh_token": "<opaque, rotating>",
       "id_token": "<signed JWT, OIDC>",
       "scope": "read:contacts write:calendar"
     }

# Refresh (client backend, rotate)
POST /token
  grant_type=refresh_token &refresh_token=<opaque> &client_id=app_123
  -> 200 { "access_token": "...", "refresh_token": "<NEW rotated>", "expires_in": 300 }
  -> 400 invalid_grant   (revoked family, reuse detected, or expired)

# Revocation (RFC 7009 - client or owner kills a token/grant)
POST /revoke
  token=<access_or_refresh_token> &token_type_hint=refresh_token
  -> 200 {}   (also publishes to the revocation channel)

# Introspection (RFC 7662 - for opaque-token resource servers only)
POST /introspect
  token=<token>
  -> 200 { "active": true, "sub": "u_42", "scope": "...", "client_id": "app_123", "exp": ... }

# Discovery + keys
GET /.well-known/oauth-authorization-server   -> endpoints, supported grants/scopes
GET /.well-known/openid-configuration         -> OIDC discovery
GET /jwks.json                                -> current public signing keys (verify JWTs)

# Internal: revocation feed consumed by resource servers
GET /revocations?since=<version>   -> { "version": N, "events": [ {key, not_after}, ... ] }
SUBSCRIBE revocations.bus          -> live push stream of revocation events

Data stores and schema

The authorization server owns durable, relational-ish state with strong consistency needs (grants, rotation, consent) - SQL, sharded. The resource fleet holds only ephemeral in-memory deny-lists fed by the push channel - no durable store on the hot path. Keys live in HSM/KMS.

Grants and refresh tokens - sharded SQL (Postgres/Spanner-style), shard key = user_id

grant
  grant_id        UUID        PK
  user_id         BIGINT      -- resource owner (SHARD KEY)
  client_id       STRING      -- third-party app
  scopes          STRING[]    -- consented scopes
  status          ENUM        -- active | revoked
  created_at      TIMESTAMP
  revoked_at      TIMESTAMP   NULL
  INDEX (user_id, client_id)          -- "revoke this app for this user"
  INDEX (user_id, status)             -- list a user's active grants

refresh_token
  token_id        UUID        PK
  family_id       UUID        -- all tokens descended from one grant
  grant_id        UUID        FK -> grant
  user_id         BIGINT      -- (SHARD KEY, colocated with its grant)
  token_hash      BYTEA       -- SHA-256 of the opaque token; never store raw
  rotation_counter INT
  status          ENUM        -- active | rotated | revoked
  issued_at       TIMESTAMP
  expires_at      TIMESTAMP
  UNIQUE (token_hash)
  INDEX (family_id, status)           -- revoke a whole family fast
  INDEX (user_id, status)

authorization_code            -- short-lived, single-use; TTL ~60s
  code_hash       BYTEA       PK   -- store the hash, not the code
  client_id       STRING
  user_id         BIGINT
  scopes          STRING[]
  code_challenge  STRING      -- PKCE S256 challenge
  redirect_uri    STRING
  consumed        BOOL
  expires_at      TIMESTAMP

client                        -- registered third-party apps
  client_id       STRING      PK
  client_secret_hash BYTEA    NULL   -- NULL for public (PKCE) clients
  type            ENUM        -- confidential | public
  redirect_uris   STRING[]
  allowed_scopes  STRING[]
  grant_types     STRING[]

Why SQL: grants, families, rotation, and consent are relational, require transactional integrity (rotating a token and marking the old one consumed must be atomic, or you get the lost-update races that break reuse detection), and are read on the rare path (issuance/refresh), not the hot path - so SQL’s per-op cost is fine. Sharding by user_id colocates a user’s grants, refresh tokens, and codes on one shard, so every revocation and refresh for a user is a single-shard transaction, and “revoke all for this user” touches exactly one shard. user_id is high-cardinality and uniformly distributed, so no hot shard.

Revocation set - durable versioned log + in-memory deny-list

revocation (authoritative, durable, monotonic version)
  seq         BIGSERIAL   PK   -- monotonically increasing version cursor
  key_type    ENUM             -- jti | user_client | user
  key         STRING           -- jti value, "user:client", or "user"
  not_before  TIMESTAMP   NULL -- for user-level: reject tokens issued before this
  not_after   TIMESTAMP        -- original expiry; entry can be dropped after this
  created_at  TIMESTAMP

# Resource-server in-memory structure (per node, rebuilt from snapshot + push):
#   bloom_filter  over revoked keys  (fast "definitely not revoked")
#   hash_set      exact revoked keys (confirm on bloom positive)
#   version       last applied seq   (for GET /revocations?since=version)
#   entries self-evict once now > not_after

The authoritative revocation log is durable and versioned (the seq is the cursor resource nodes pull against); the per-node bloom+hashset is the ephemeral, fast, hot-path copy. This is NoSQL/in-memory on the read path, SQL on the write path - the same strong-write / fast-read split as the tokens themselves.

Signing keys - HSM/KMS, never in app memory as raw private key

Signing happens via KMS: the authorization server calls KMS to sign token
  payloads; the private key never leaves the HSM. Public keys are published
  at /jwks.json with a `kid` (key id) so resource servers pick the right one.
Key rotation: publish the new public key in JWKS first (resource servers now
  trust both old and new), then start signing with the new key, then retire the
  old key after > max-token-TTL so no in-flight token is orphaned.

Bottlenecks & Scaling

Where it breaks first, in order, and the fix for each.

1. Introspection on the hot path (breaks first if you let it). Any design where resource servers call the authorization server per request caps the whole ecosystem at the authorization server’s QPS and makes its outage a total outage. Fix: self-contained JWTs verified locally with cached JWKS; the authorization server sees issuance and refresh traffic (~100K/sec), never the ~30M/sec validation traffic. Only opaque-token resource servers introspect, and they cache results by token hash with a short TTL.

2. Revocation propagation lag / missed events. A pure push bus can drop messages to a restarting or newly autoscaled node, leaving it honoring revoked tokens. Fix: the layered model - fast push for latency, periodic versioned snapshot pull for correctness, short access-token TTL as the hard ceiling. Worst case staleness is bounded by min(TTL, snapshot_interval), and a new node pulls a full snapshot before it serves traffic.

3. Revocation fan-out to tens of thousands of nodes. One revocation must reach every resource node. Fix: it is a fan-out, not a throughput, problem - revocation events are only ~thousands/sec. Use a pub/sub topic every node subscribes to (Kafka consumer group per node, or Redis/NATS fan-out), and keep the per-event payload tiny (a key + two timestamps). Tens of thousands of subscribers on a few thousand small events/sec is well within one Kafka/NATS cluster. If subscriber count grows huge, add a fan-out tier (regional relays that each re-broadcast to local nodes).

4. Grant store as bottleneck / SPOF. 500M grants and all refresh/revoke writes hit one database. Fix: shard by user_id. A user’s grants, refresh tokens, codes, and “revoke all” operations are then single-shard transactions. Read replicas per shard absorb the read-heavy introspection/consent-listing. Shard key is user_id because every operation (refresh, revoke-app, revoke-all, consent list) is scoped to one user; sharding by client_id would be wrong - a few popular apps would create hot shards holding millions of users’ grants.

5. Hot key - a wildly popular third-party client. One mega-app (millions of users) concentrates issuance and refresh load. Fix: sharding by user_id already spreads that app’s grants across all shards (each user on their own shard), so there is no single hot row; the client row itself is read-mostly config, cached in memory on the authorization-server nodes. Refresh-token rotation writes are spread by user, not clumped by client.

6. Reuse-detection races / benign retries. Concurrent refreshes or a lost response can trip false reuse detection or allow a lost-update. Fix: make rotation an atomic transaction (UPDATE refresh_token SET status='rotated' WHERE token_hash=? AND status='active' - if it updates zero rows, the token was already consumed -> reuse path). Add a short idempotency grace window returning the same rotated token on an immediate retry. The atomic conditional update is what makes reuse detection correct under concurrency.

7. Signing-key compromise or loss (the catastrophic one). A leaked private key lets anyone mint valid tokens for any user; a lost key makes the fleet trust nothing. Fix: keys live in HSM/KMS and never enter app memory raw; sign via KMS calls. Rotate keys regularly with overlapping validity (publish new public key in JWKS before signing with it; retire old key after max token TTL). On suspected compromise, rotate immediately and bump the kid so old-key-signed tokens are rejected fleet-wide - a global revocation via key rotation.

8. Authorization server availability vs validation availability. If issuance is down, no new tokens; if validation depended on it, everything is down. Fix: the offline-validation design means the authorization server can be briefly down and resource servers keep accepting unexpired tokens (effective validation availability exceeds issuance availability). Run the authorization server multi-AZ, stateless app tier in front of the sharded store, with the JWKS and discovery docs served from a CDN so even key fetches survive an authorization-server blip.

9. Clock skew across resource nodes. exp/not_before/issued_at checks depend on time; skewed node clocks over- or under-accept tokens. Fix: keep nodes NTP-synced; allow a small leeway (~30-60s) on exp/nbf to tolerate bounded skew; carry absolute timestamps (not relative) in tokens and revocation events so every node evaluates against the same wall-clock reference.

Wrap-Up

The trade-offs that define this design:

  • Self-contained short-lived JWT over opaque-token introspection. Resource servers verify access tokens locally with cached public keys - sub-millisecond, no round trip, the authorization server never sees the ~30M/sec validation flood. The cost is that a JWT is not natively revocable, which we buy back with a 5-minute TTL (bounding the worst case and the deny-list size) plus a push channel.
  • Layered revocation: push for speed, snapshot for correctness, TTL for the ceiling. This is the core hard part. A pub/sub bus fans tiny revocation events to every resource node in ~hundreds of milliseconds; a periodic versioned snapshot pull guarantees nodes that missed events (restart, autoscale, partition) still converge; and the short access-token TTL caps worst-case staleness regardless. No synchronous database round trip ever sits on the per-request validation path - revocation is checked against an in-memory bloom+hashset. Strong revocation is enforced on the rare refresh path (one synchronous grant-store read every ~5 min), where it is cheap.
  • Refresh-token rotation with reuse detection over static long-lived tokens. Every refresh rotates the token and consumes the old one inside an atomic transaction; presenting a consumed token is an unambiguous theft signal that revokes the whole family. A stolen refresh token is caught on first reuse rather than exploited silently for weeks, and sender-constraining (DPoP/mTLS) makes it useless to a thief who lacks the key.
  • SQL (sharded by user_id) for grants and rotation, in-memory on the resource fleet. The write path needs transactional integrity for rotation and family revocation and runs on the rare path, so it pays for SQL; the hot path holds only an ephemeral, self-trimming deny-list. The same strong-write / fast-read split appears in both the token format and the revocation set.

One-line summary: an OAuth 2.0 authorization server is a sharded, strongly consistent grant mint that issues short-lived locally-verifiable JWTs and rotating reuse-detecting refresh tokens, with revocation propagated to a stateless resource fleet through a fast best-effort push bus backstopped by a versioned snapshot and a 5-minute TTL - trading a sub-second-to-a-few-seconds revocation window and a small bounded staleness for offline, round-trip-free validation at tens of millions of requests per second.