Skip to content

stack-auth: refresh a token in the background before it expires, with backoff after a failure #1962

In review

Description

@coderdan

Background

Every SDK gets its access token for ZeroKMS (the key service) from CTS (the CipherStash Token Service) through the stack-auth Rust crate. A token lasts 900 seconds by default. stack-auth refreshes it when a call asks for a token within 90 seconds of its expiry (EXPIRY_LEEWAY_SECS, packages/stack-auth/src/token.rs).

Problem

Nothing refreshes a token before a call needs it, in any SDK:

  1. The call that starts a refresh waits for it, although its token is still valid (refresh_non_blocking in packages/stack-auth/src/auto_refresh.rs). Natively, other callers do not wait; in the Go SDK they do, which is Go SDK: a user request waits for each token refresh, and every other call in the process queues behind it #1958.
  2. If no call arrives in the last 90 seconds, the token expires. The next call then refreshes with no token to fall back on, and every caller waits for it.
  3. After a refresh fails while the token is still valid, every later call inside the 90 seconds starts a new refresh at once. There is no backoff, so a CTS outage gets a request from every call.

So a user request pays for an exchange with CTS (a new connection, and sometimes about a second at CTS) about once per token lifetime, per process.

Proposal

  1. The rule lives in stack-auth, once: when the next refresh is due, with jitter; and the backoff after a failure. It refreshes ahead only for a strategy used since its last refresh, so an idle process does not call CTS forever.
  2. Natively, stack-auth runs it on a background task. Rust and the TypeScript SDK on Node get it without other changes.
  3. A WebAssembly host runs it: the guest exposes "when is the next refresh due" and "refresh now", and the host keeps the timer. In Go, a goroutine per Strategy, stopped by Close.
  4. What a normal call does:
    • The token is still valid: it gets that token, and never waits for or starts a refresh.
    • The token has expired and refreshes are failing: it fails at once with the last refresh error, and does not start an exchange of its own while the background refresh backs off.
    • There is no token yet (startup): it does the exchange, as today.
    • CTS refused the account: unchanged; stack-auth already stops asking.

Relationship to other work

Activity

  1. added
    enhancement
    Golang
    Rust
    on Nov 27, 2026
  2. self-assigned this
    on Nov 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

GolangRustSDKenhancement

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions