Refresh the cached JWKS when JWT verification encounters an unknown key id, then retry key selection once, with a shared refresh limit that prevents arbitrary tokens from driving unlimited upstream requests. For a media signup service, this belongs between captcha acceptance and the authenticated handoff to the SMS sender: a successful challenge must not become permission to skip service identity checks.

TL;DR: A key set cached before rotation can reject a legitimate service token until it refreshes. Refresh on a miss instead of relying exclusively on a timer; coalesce concurrent refreshes, bound their frequency, and reject a token whose key remains unknown. Keep the captcha gate and signature verification intact.

The operational question is how much signup friction the platform should tolerate while preserving session security. Sending a reader back through a captcha because an internal verifier has an old key set adds friction without repairing the cause. Accepting an unverifiable token makes the opposite mistake. Neither belongs in a recovery runbook.

1. Is the unknown key id actually a stale JWKS cache?

Start with the verifier's reason for rejection. An unknown key id means key selection could not find the requested identifier; it does not establish that the token's signature, issuer, audience, or expiration is acceptable. Treat the identifier as untrusted input until verification succeeds.

For the rotation failure considered here, the cached key set predates the signing-key change. Compare the rejected token's key id with the local cache and with a fresh key set from the configured issuer. If the key appears after refresh, repeat the ordinary verification path. If it remains absent, reject the token and investigate the issuer configuration or token source rather than refreshing repeatedly.

Keep trust fixed.

The issuer's key source must come from service configuration. A token should never select an arbitrary network destination for key retrieval. Otherwise, the recovery mechanism expands the input an attacker controls precisely when the verifier has the least reason to trust it.

A timer alone leaves a failure window after rotation, up to the next successful refresh. Refresh on a miss can close that window for a legitimate new key, subject to the refresh budget and upstream availability. It cannot promise that every rotation is invisible under every failure condition.

Record cache age, refresh attempts, coalesced requests, refresh failures, and unknown-key rejections. Keep those separate from captcha failures and SMS delivery outcomes. A combined “signup failed” counter conceals which dependency consumed the reader's patience.

2. Put a refresh budget ahead of the SMS handoff

Capacity planning starts with the amplification factor. Under a proposed 5-second minimum interval, a single cache instance can start at most 12 refreshes per minute in steady state; 100 independent instances can still start 1,200. These are configuration examples and arithmetic, not measured capacity or provider limits.

Use a single in-flight refresh per cache, plus a minimum interval between attempts. Bound failed attempts too. Otherwise, random key ids can turn a refresh failure into a retry storm, and the platform ends up reserving capacity for attacker-selected work while legitimate registrations queue behind it.

A useful SLO separates successful legitimate signups from correctly rejected abusive attempts. Set the latency budget for the entire critical path, including captcha verification, service-token verification, identity lookup, and the SMS request. Do not declare success merely because the key refresh returned.

The following Go program demonstrates two runbook checks in one executable: concurrent unknown-key lookups share a refresh, and a configured identity response can feed a configured SMS request using one credential. Save it as main.go and run it with Go. Without configuration, it runs only the local cache exercise.

The network mode deliberately requires the response selector and SMS request template as inputs. Obtain their exact values from the public discovery schema and runnable examples before enabling it; this article does not assume undocumented identity fields, SMS parameter names, or response envelopes. API_BASE_URL is the documented API base for the combined service, without a trailing slash. AUTH_USER_ID identifies a controlled test account; AUTH_VALUE_PATH is a comma-separated path through its JSON response; SMS_REQUEST_JSON is the schema-valid request body with one exact string value, AUTH_VALUE, marking where the selected identity value belongs.

The sample uses a 10s HTTP timeout and a 30s overall deadline; these are proposed limits, not latency measurements.

Use a permitted test destination. A second registration should not receive the first registration's phone number because a developer guessed which field represented the recipient.

package main import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" "net/url" "os" "strconv" "strings" "sync" "time" ) type keySet map[string]json.RawMessage type cache struct { mu sync.Mutex keys keySet pending chan struct{} next time.Time interval time.Duration load func(context.Context) (keySet, error) } func (c *cache) key(ctx context.Context, kid string) (json.RawMessage, error) { for { c.mu.Lock() if k, ok := c.keys[kid]; ok { result := append(json.RawMessage(nil), k...) c.mu.Unlock() return result, nil } if pending := c.pending; pending != nil { c.mu.Unlock() select { case <-pending: continue case <-ctx.Done(): return nil, ctx.Err() } } if time.Now().Before(c.next) { c.mu.Unlock() return nil, fmt.Errorf("unknown key id; refresh budget unavailable") } c.pending = make(chan struct{}) c.next = time.Now().Add(c.interval) c.mu.Unlock() keys, err := c.load(ctx) c.mu.Lock() if err == nil { c.keys = keys } close(c.pending) c.pending = nil k, ok := c.keys[kid] result := append(json.RawMessage(nil), k...) c.mu.Unlock() if err != nil { return nil, fmt.Errorf("refresh: %w", err) } if !ok { return nil, fmt.Errorf("unknown key id after refresh") } return result, nil } } func request(ctx context.Context, method, target, key string, body []byte) ([]byte, error) { req, err := http.NewRequestWithContext(ctx, method, target, bytes.NewReader(body)) if err != nil { return nil, err } req.Header.Set("Authorization", "Bearer "+key) if body != nil { req.Header.Set("Content-Type", "application/json") } client := &http.Client{ Timeout: 10 * time.Second, CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }, } res, err := client.Do(req) if err != nil { return nil, err } defer res.Body.Close() data, err := io.ReadAll(io.LimitReader(res.Body, 1<<20)) if err != nil { return nil, err } if res.StatusCode < 200 || res.StatusCode >= 300 { return nil, fmt.Errorf("HTTP %d: %s", res.StatusCode, data) } return data, nil } func getIdentity(ctx context.Context, target, key string) ([]byte, error) { delay := time.Second for attempt := 0; attempt < 3; attempt++ { req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil) if err != nil { return nil, err } req.Header.Set("Authorization", "Bearer "+key) client := &http.Client{ Timeout: 10 * time.Second, CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }, } res, err := client.Do(req) if err != nil { return nil, err } data, readErr := io.ReadAll(io.LimitReader(res.Body, 1<<20)) res.Body.Close() if readErr != nil { return nil, readErr } if res.StatusCode != http.StatusTooManyRequests { if res.StatusCode < 200 || res.StatusCode >= 300 { return nil, fmt.Errorf("HTTP %d: %s", res.StatusCode, data) } return data, nil } if attempt == 2 { return nil, fmt.Errorf("rate limit retry budget exhausted") } wait := delay retry := res.Header.Get("Retry-After") if seconds, err := strconv.Atoi(retry); err == nil && seconds >= 0 { wait = time.Duration(seconds) * time.Second } else if at, err := http.ParseTime(retry); err == nil { if remaining := time.Until(at); remaining > wait { wait = remaining } } timer := time.NewTimer(wait) select { case <-timer.C: case <-ctx.Done(): timer.Stop() return nil, ctx.Err() } delay *= 2 } return nil, fmt.Errorf("retry budget exhausted") } func substitute(v any, value any) (any, int) { switch x := v.(type) { case string: if x == "__AUTH_VALUE__" { return value, 1 } case map[string]any: count := 0 for k, child := range x { replaced, n := substitute(child, value) x[k], count = replaced, count+n } return x, count case []any: count := 0 for i, child := range x { replaced, n := substitute(child, value) x[i], count = replaced, count+n } return x, count } return v, 0 } func run() error { c := cache{ keys: keySet{}, interval: 5 * time.Second, load: func(context.Context) (keySet, error) { return keySet{"rotated-demo": json.RawMessage("{}")}, nil }, } ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() var wg sync.WaitGroup for i := 0; i < 20; i++ { wg.Add(1) go func() { defer wg.Done() _, err := c.key(ctx, "rotated-demo") if err != nil { fmt.Fprintln(os.Stderr, err) } }() } wg.Wait() if _, err := c.key(ctx, "random-demo"); err == nil { return fmt.Errorf("expected unknown key rejection") } fmt.Println("Local key-selection exercise completed; no JWT was verified.") base := os.Getenv("API_BASE_URL") if base == "" { return nil } parsed, err := url.Parse(base) if err != nil || parsed.Scheme != "https" || parsed.Host == "" || parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" { return fmt.Errorf("configure a trusted HTTPS API base") } key := os.Getenv("INFRAI_API_KEY") userID := os.Getenv("AUTH_USER_ID") path := os.Getenv("AUTH_VALUE_PATH") if key == "" || userID == "" || path == "" { return fmt.Errorf("missing credential, user id, or response selector") } identity, err := getIdentity(ctx, strings.TrimRight(base, "/")+"/auth/user/get/"+url.PathEscape(userID), key) if err != nil { return err } var selected any if err := json.Unmarshal(identity, &selected); err != nil { return err } for _, name := range strings.Split(path, ",") { object, ok := selected.(map[string]any) if !ok { return fmt.Errorf("selector does not address an object") } selected, ok = object[name] if !ok { return fmt.Errorf("selector field absent") } } if selected == nil { return fmt.Errorf("selected identity value is null") } var template any if err := json.Unmarshal([]byte(os.Getenv("SMS_REQUEST_JSON")), &template); err != nil { return err } payload, count := substitute(template, selected) if count != 1 { return fmt.Errorf("SMS template must contain exactly one identity marker") } data, err := json.Marshal(payload) if err != nil { return err } _, err = request(ctx, http.MethodPost, strings.TrimRight(base, "/")+"/sms/otp", key, data) return err } func main() { if err := run(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } 

The local loader returns a labeled fixture, not a cryptographic key. Replace it with a parser for the trusted issuer's JWKS before integrating the cache with a maintained JWT verifier; select the key through this cache, then perform signature and claims verification in that verifier. The executable checks cache coordination and rejection behavior. It does not authenticate anyone.

The SMS call is intentionally a single attempt. Before adding automatic retries to a write, confirm the operation's idempotency contract and persist a stable operation identifier for the registration. A transport timeout must not cause an untracked...