Refresh token rotation makes every refresh token single-use: each refresh returns a new one, and a token that comes back a second time is treated as stolen. That rule assumes a client that never uses the same token twice. Real clients have dozens of threads, several browser tabs, and network calls that time out after the server has already answered. Each of those can send the same refresh token twice, and strict rotation then signs the user out, or worse, revokes the session as a theft.
This article makes rotation thread-safe from both ends. On the client: a token source that any number of threads can share, which refreshes exactly once when the token expires. On the server: an idempotent refresh, where every request that presents the same token at the same moment, on any server instance, gets the same new token. Everything was tested: the client in Go (with the race detector) and Java (with 10,000 virtual threads), the server as three separate instances on PostgreSQL 18. It builds on our articles on access and refresh tokens and refresh token rotation by RFC 9700.
The short answer#
Where the races come from#
| Source | What happens with strict rotation | Who can fix it |
|---|---|---|
| Threads or goroutines in one app, all finding the token expired | Each refreshes; all but one get an error | The client |
| Several browser tabs, or several worker processes sharing a token store | Same, across processes | The client, with a lock shared by the processes |
| Several instances of a backend that holds the session (a BFF) | Two instances refresh the same session at once | The server, or a lock shared by the instances |
| A response lost on the network; the client retries | The retry presents a spent token | Only the server |
The client can remove the first three, and should, because they waste refreshes even when the server forgives them. The last one it can't: the client never saw the new token, so the only token it has is the old one. That case has to be solved on the server.
The client: refresh once#
The pattern is double-checked locking around the refresh. Reading a fresh token takes no lock at all, which matters because every API call asks for one. When the token is about to expire, the first thread to notice takes the lock and refreshes; the others wait for the lock, then check again, find a fresh token, and use it:
// tokens.go: a token source that any number of goroutines can share. Fresh tokens are read without locking;
// when a refresh is needed, one goroutine does it and the others wait for its result.
package tokens
import (
"context"
"sync"
"sync/atomic"
"time"
)
type Tokens struct {
Access, Refresh string
Expiry time.Time
}
type Source struct {
current atomic.Pointer[Tokens]
mu sync.Mutex // held while refreshing
Refresh func(ctx context.Context, refreshToken string) (Tokens, error)
Save func(Tokens) error // persist the new refresh token before anything uses it
}
func NewSource(t Tokens) *Source {
s := &Source{}
s.current.Store(&t)
return s
}
const margin = 30 * time.Second // refresh a little early, before requests start failing
func (s *Source) Token(ctx context.Context) (string, error) {
if t := s.current.Load(); time.Until(t.Expiry) > margin {
return t.Access, nil // the fast path: no lock
}
s.mu.Lock()
defer s.mu.Unlock()
t := s.current.Load() // check again: another goroutine may have refreshed while we waited
if time.Until(t.Expiry) > margin {
return t.Access, nil
}
next, err := s.Refresh(ctx, t.Refresh)
if err != nil {
return "", err
}
if err := s.Save(next); err != nil {
return "", err
}
s.current.Store(&next)
return next.Access, nil
}
// Rejected reports that the API refused an access token (401), so the next Token call refreshes,
// unless another goroutine has already replaced that token.
func (s *Source) Rejected(access string) {
s.mu.Lock()
defer s.mu.Unlock()
if t := s.current.Load(); t.Access == access {
expired := *t
expired.Expiry = time.Time{}
s.current.Store(&expired)
}
}Three details make it correct:
- The second check, inside the lock. Without it, every waiting goroutine would refresh again in turn, each with the token the previous one just spent.
- Save before publish. If the process dies after the refresh but before the new refresh token is stored, the next start has only the spent token, and the session is gone. Persist it first.
Rejectedcompares before it invalidates. When an API returns 401, the caller reports the access token it used. If another goroutine has already refreshed, the token no longer matches and nothing happens, so 1,000 failed requests cause one refresh, not 1,000.
We tested it against a fake token endpoint that rotates strictly, takes 20 ms per call, and rejects any refresh token used twice. With 1,000 goroutines asking for a token at the moment it expired, there was exactly one refresh call and one save, and every goroutine got the new access token. With 1,000 goroutines all reporting a rejected access token and retrying, there was again exactly one more refresh. Go's race detector found nothing, and the lock-free fast path took about 1 nanosecond per call with 32 goroutines reading at once.
Then we removed the lock and the second check. The same 1,000 goroutines made 1,000 refresh calls: one succeeded, 999 got invalid_grant, and the race detector reported a data race on the token. Against a server with reuse detection, the second refresh with the same token would also have revoked the session.
The same pattern in Java#
// TokenSource.java: the same pattern in Java. Safe for platform and virtual threads alike.
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.function.Function;
public final class TokenSource {
public record Tokens(String access, String refresh, Instant expiry) {
boolean fresh() { return Instant.now().plus(Duration.ofSeconds(30)).isBefore(expiry); }
}
private final AtomicReference<Tokens> current;
private final ReentrantLock lock = new ReentrantLock();
private final Function<String, Tokens> refresh; // calls the token endpoint
private final Consumer<Tokens> save; // persists the new refresh token
public TokenSource(Tokens initial, Function<String, Tokens> refresh, Consumer<Tokens> save) {
this.current = new AtomicReference<>(initial);
this.refresh = refresh;
this.save = save;
}
public String token() {
Tokens t = current.get();
if (t.fresh()) return t.access(); // no lock while the token is good
lock.lock();
try {
t = current.get(); // someone may have refreshed while we waited for the lock
if (t.fresh()) return t.access();
Tokens next = refresh.apply(t.refresh());
save.accept(next);
current.set(next);
return next.access();
} finally {
lock.unlock();
}
}
}In our test, 10,000 virtual threads called token() with an expired token: one refresh, one save, no errors, and all 10,000 got the same new access token. ReentrantLock is a good fit for virtual threads; since Java 24, synchronized no longer pins them to a carrier thread either, so both work. In C#, the same shape uses SemaphoreSlim(1, 1) with await WaitAsync(), because a plain lock can't contain an await.
Beyond one process#
A lock in memory only covers one process. When several processes share one refresh token, the lock has to be shared too:
- Browser tabs share cookies and storage. The Web Locks API (
navigator.locks.request) gives them a lock with the same double-check inside: re-read the stored token after getting the lock. Better still, keep tokens out of the browser in a backend-for-frontend, as our access and refresh tokens article recommends. - Workers or CLI processes that share a token file can use a file lock, or a row lock if the token lives in a database.
- Several BFF instances serving one user's session can lock the session's row. Or they can simply rely on an idempotent token endpoint, which makes concurrent refreshes harmless.
The server: the same successor for everyone#
On the server, the usual answers to a spent token seen again within seconds are to reject it (safe, but a lost response signs the user out) or to issue another new token (forgiving, but it creates a second, independent branch of the session that reuse detection never sees). Our RFC 9700 article tested both. There is a third answer: give the request the same successor the first request got.
The problem is that the server mustn't keep refresh tokens in a readable form; it only stores their hashes. The solution is to store the successor encrypted, with a key derived from the token it replaces. Only someone who presents the old token can derive the key, and that someone was going to receive the successor anyway:
-- schema.sql: grants and their refresh tokens (stored as hashes). next_sealed holds the successor, encrypted so
-- that only someone who presents the old token can read it.
CREATE TABLE grants (
id uuid PRIMARY KEY DEFAULT uuidv7(),
user_id bigint NOT NULL,
expires_at timestamptz NOT NULL,
revoked_at timestamptz,
revoked_why text
);
CREATE TABLE refresh_tokens (
hash bytea PRIMARY KEY, -- SHA-256 of the token
grant_id uuid NOT NULL REFERENCES grants ON DELETE CASCADE,
idle_expires_at timestamptz NOT NULL,
rotated_at timestamptz, -- set once, by the first refresh
next_sealed bytea -- the successor, AES-GCM with a key derived from this token
);
CREATE INDEX ON refresh_tokens (grant_id);// rotate.mjs: idempotent refresh token rotation. Every request that presents the same token within the window
// gets the same successor, on any server instance; a token that comes back later, or after its successor was
// used, revokes the grant.
import { createCipheriv, createDecipheriv, createHash, hkdfSync, randomBytes } from "node:crypto";
const WINDOW = "30 seconds";
const IDLE = "14 days";
const sha256 = (t) => createHash("sha256").update(t).digest();
const newToken = () => randomBytes(32).toString("base64url");
// The successor is encrypted with a key derived from the token it replaces. The database only has that token's
// hash, so a copy of the database can't open it; whoever presents the token can.
const keyFor = (token) => Buffer.from(hkdfSync("sha256", token, "", "refresh-token successor", 32));
function seal(token, next) {
const iv = randomBytes(12);
const c = createCipheriv("aes-256-gcm", keyFor(token), iv);
return Buffer.concat([iv, c.update(next, "utf8"), c.final(), c.getAuthTag()]);
}
function open(token, sealed) {
const d = createDecipheriv("aes-256-gcm", keyFor(token), sealed.subarray(0, 12));
d.setAuthTag(sealed.subarray(-16));
return Buffer.concat([d.update(sealed.subarray(12, -16)), d.final()]).toString("utf8");
}
export async function refresh(db, token) {
const c = await db.connect();
try {
await c.query("BEGIN");
// The row lock serializes every refresh of this token, across connections and server instances.
const { rows: [t] } = await c.query(
`SELECT t.grant_id, g.user_id, t.next_sealed,
t.rotated_at IS NOT NULL AS spent,
t.rotated_at > now() - $2::interval AS in_window,
t.idle_expires_at > now() AS fresh,
g.expires_at > now() AND g.revoked_at IS NULL AS live
FROM refresh_tokens t JOIN grants g ON g.id = t.grant_id
WHERE t.hash = $1
FOR UPDATE OF t`,
[sha256(token), WINDOW],
);
if (!t || !t.live) return null;
if (!t.spent) {
if (!t.fresh) return null;
const next = newToken();
await c.query("INSERT INTO refresh_tokens (hash, grant_id, idle_expires_at) VALUES ($1, $2, now() + $3::interval)",
[sha256(next), t.grant_id, IDLE]);
await c.query("UPDATE refresh_tokens SET rotated_at = now(), next_sealed = $2 WHERE hash = $1",
[sha256(token), seal(token, next)]);
await c.query("COMMIT");
return { userId: t.user_id, grantId: t.grant_id, refreshToken: next };
}
// Spent. Within the window, and while its successor is still unused, this is a retry or a race:
// answer with the same successor. Anything else is a replay of a stolen token.
if (t.in_window) {
const next = open(token, t.next_sealed);
const { rows: [s] } = await c.query("SELECT rotated_at IS NULL AS unused FROM refresh_tokens WHERE hash = $1", [sha256(next)]);
if (s?.unused) {
await c.query("COMMIT");
return { userId: t.user_id, grantId: t.grant_id, refreshToken: next };
}
}
await c.query("UPDATE grants SET revoked_at = now(), revoked_why = 'refresh token reused' WHERE id = $1", [t.grant_id]);
await c.query("COMMIT");
return null;
} finally {
await c.query("ROLLBACK").catch(() => {}); // ends the transaction on the early returns
c.release();
}
}The row lock (FOR UPDATE OF t) is what makes it work across server instances: every request for the same token waits for the first one to commit, then sees rotated_at set and the sealed successor in place. The coordination happens in the database, so there is no lock service to run. Two conditions keep the forgiveness narrow: the token must be within its 30-second window, and its successor must still be unused. A retry or a race meets both. A thief who replays the token later, or after the real client has moved on, meets neither, and the grant is revoked.
What we tested#
Three copies of a small HTTP server around rotate.mjs, each a separate Node.js process with its own connection pool, all on one PostgreSQL 18 database. Eight checks passed:
- 60 concurrent refreshes with the same token, spread across the three instances: all 60 got status 200 and the same successor, the database held exactly one successor row, nothing was revoked, and the successor worked.
- A lost response: the retry with the old token got the successor the client never saw, and the session continued.
- A replay after the successor was used revoked the grant at once, inside the window, and the user's current token stopped working too.
- A replay 31 seconds later revoked the grant.
- A replay inside the window got the same successor as the user, not a new branch. When that copy was used again ten minutes later, after the user had refreshed, the grant was revoked.
- Storage: neither the token nor its successor appeared anywhere in the database, only hashes and AES-GCM ciphertext; a random token opened nothing.
- An idle-expired token was refused without revoking anything, and a revoked grant was refused.
The three instances together handled 3,761–3,893 rotations a second in two runs, with 30 sessions refreshing in parallel. Each rotation is one transaction with a row lock, an insert, and an update, so the database does about as much work as with plain rotation.
Compared with the other policies#
| Scenario | Reject | New token each time | Same successor |
|---|---|---|---|
| Concurrent refreshes | 1 succeeds; the rest are refused | All succeed, with different tokens | All succeed, with the same token |
| Lost response, retry | Refused: the user signs in again | Succeeds | Succeeds |
| Replay inside the window | Refused | The attacker gets an independent branch, never detected | The attacker shares the user's token; the next out-of-step use is detected |
| Replay later | Grant revoked | Grant revoked | Grant revoked |
The "reject" and "new token each time" columns are the refuse and reuse-window policies measured in our RFC 9700 article. "Same successor" keeps the forgiving behavior where it's needed, and turns the window's weakness from an undetectable fork into a shared token, which reuse detection still catches.
What it doesn't do#
- It doesn't stop a thief inside the window. Someone who replays a stolen token within 30 seconds of the real refresh gets a working token. They keep it only until one of the two parties uses the shared token out of step with the other, which happens at the next refresh unless the thief keeps matching the user within seconds. Keep the window short: long enough for a retry, not much more.
- It doesn't replace a careful client. A client without a lock still makes one useless refresh call per thread; the server just stops punishing it.
- It doesn't protect a token that keeps leaking. As with any rotation, an attacker who can read each new token as it arrives always has the current one.
FAQ#
Why not use a distributed lock, like Redis?
The refresh has to touch the token's row anyway, and the row lock already serializes every request for it, across all instances. A separate lock would add a service and a failure mode without adding safety.
Why encrypt the successor instead of storing it?
A readable successor would turn every database backup, replica, and log of that table into a list of working refresh tokens. Encrypted with a key derived from the old token, the stored value is useless to anyone who doesn't already hold that token.
What about the access token?
Issue a new one for every successful request, including the repeats. Access tokens are short-lived and independent, so several valid ones at a time do no harm.
How long should the window be?
Long enough to cover the client's timeout plus one retry. We used 30 seconds; a few seconds is enough if your clients retry quickly. The window only matters for the seconds right after a rotation.
Try it in your browser
- JWT Decoder, Encoder & Editor: decode the access tokens your token source hands out and check when they expire.
- Hash Generator: compute the SHA-256 of a refresh token, the only form the database keeps.