Concurrent refreshes sign users out
When two parts of one application refresh with the same refresh tokenA longer-lived credential that a client sends to the authorization server, never to an API, to get new access tokens without asking the person again., a server that detects reuse cannot tell them from a thief and ends the whole family. This lesson follows the printing company's sync service after it scaled out, finds the race in its own trace, and repairs it with one renewal per stored tokenA piece of data issued by a trusted service that a client presents as a credential, for example to call an API or to report a sign-in. Some tokens carry readable claims; others are random strings that only the issuer can interpret. while the reuse check stays strict.
Customers are signed out when the service is busy
All names, domains and identifiers in these examples are fictional. Mara writes in for the second time in a week: "I got another email asking me to reconnect my photo account. I reconnected on Monday. Is something wrong with my account?" Support finds a pattern behind her ticket. A dozen or so customers a day get the same email, nearly all of them in the evening, when the printing company's order volume peaks. Nobody has changed a password, and reconnecting always works.
The email comes from the printing company's sync service. When a customer orders a photo book, background workers fetch the full-resolution photos from the photo service's APIAn application programming interface: a defined way for software to interact with a service. A web API offers endpoints where other programs send HTTP requests. and render the print files. Each customer's connection is one row in a shared database, holding an access tokenA token that a client presents to an API to use access it has been granted, usually limited in what it allows and how long it lasts. It authorizes API calls; it does not tell the client who signed in., its expiry and a refresh token. When a worker finds the access token about to expire, it refreshes it. If the refresh fails, the service marks the connection as needing to be reconnected and emails the customer.
"Only when we are busy" is a timing clue. A busy evening means several workers handling the same customer's order at once, and the deployment history adds the other half: three weeks ago the sync service went from one instance to four. The refresh code has not changed since it ran on a single machine.
Rotation and reuse detection
The photo service rotates refresh tokens. Every successful refresh returns a new refresh token along with the new access token, and the one just used stops working. The chain of tokens descended from one authorizationDeciding whether a requested action is permitted, such as whether a signed-in account may delete a particular photo. Authentication says which account is asking; authorization decides what it can do. is called a family, as Refresh tokens and rotation described. RFC 9700, the OAuthA framework that lets a person give an application limited access to their resources at another service, using tokens instead of sharing their password. OAuth is about access; OpenID Connect adds sign-in. security best current practice summarized in OAuth security best practices, says in section 4.14.2 that refresh tokens for public clients must be either sender-constrained or rotated. The printing company's sync service is a confidential clientAn OAuth client, typically running on a backend, that can keep a credential such as a client secret or private key protected, and so can authenticate itself to the authorization server., which the rule does not cover, but the photo service rotates for every client.
Rotation gives the server a way to notice theft. If a refresh token that has already been used shows up again, two parties are holding the same token, and one of them may be an attacker who copied it. The server cannot tell which one is legitimate, so RFC 9700 describes it revoking the active refresh token, which ends the whole family. The thief's copy and the legitimate client's newest token stop working together, and the user has to authorize again. Refresh token theft walks through how that plays out when a real thief is involved.
An application that sends the same refresh token twice looks exactly like that to the server, however innocent the reason.
Reconstruct the family from fingerprints
You need to see which refresh token each request carried without writing any token into a log. The sync service records a fingerprint instead: the first eight hex characters of a SHA-256 hashTurning data into a short, fixed-size value called a hash, in a way that cannot be reversed and where changing one character changes the result completely. Services store password hashes instead of passwords, and signatures are made over a hash. of the token. Two requests with the same fingerprint carried the same token, and the fingerprint cannot be turned back into a usable credential. Here is the trace for Mara's connection on the evening of her second email:
19:42:17.204 sync-3 conn=c-88213 refresh.request rt_fp=9c41e0b2
19:42:17.209 sync-7 conn=c-88213 refresh.request rt_fp=9c41e0b2
19:42:17.396 sync-3 conn=c-88213 refresh.response status=200 new_rt_fp=5ad7713f expires_in=3600
19:42:17.405 sync-7 conn=c-88213 refresh.response status=400 error=invalid_grant request_id=e41f07c2-5b8d-4a39-9e61-2d7f3c0a8b55
19:42:17.406 sync-7 conn=c-88213 job.requeue reason=refresh_failed
20:41:55.102 sync-5 conn=c-88213 refresh.request rt_fp=5ad7713f
20:41:55.290 sync-5 conn=c-88213 refresh.response status=400 error=invalid_grant request_id=73c2b9e0-1f4a-4d86-b5e3-8a09d6c1e27f
20:41:55.291 sync-5 conn=c-88213 connection.mark needs_reconnectTwo workers, on two different instances, sent the same refresh token five milliseconds apart. The photo service handled sync-3's request first and answered with a normal rotation:
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-store
{"access_token": "<redacted>", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "<redacted>", "scope": "photos.read"}By the time sync-7's request was processed, its token had just been used. It got the same answer an expired or revoked token gets:
HTTP/1.1 400 Bad Request
Content-Type: application/json
Cache-Control: no-store
{"error": "invalid_grant", "error_description": "The refresh token is invalid, expired or revoked."}sync-7 requeued its job and nothing looked wrong for an hour, because sync-3 had stored the new tokens and the renders kept working with the new access token. At 20:41 that access token neared expiry, sync-5 refreshed with the stored replacement, 5ad7713f, and was refused. That third request is the one that sent Mara her email, and it failed because of what happened an hour earlier. The photo service's audit trail shows why:
2026-10-15T19:42:17.391Z oauth.token.refresh succeeded client=printer-sync subject=user-5521 grant=g-77d0
2026-10-15T19:42:17.399Z oauth.token.refresh rejected client=printer-sync subject=user-5521 grant=g-77d0
reason=refresh_replayed action=family_revoked request_id=e41f07c2-5b8d-4a39-9e61-2d7f3c0a8b55
2026-10-15T20:41:55.288Z oauth.token.refresh rejected client=printer-sync subject=user-5521 grant=g-77d0
reason=family_revoked request_id=73c2b9e0-1f4a-4d86-b5e3-8a09d6c1e27fThe second request was treated as reuse, and the server revoked family g-77d0 on the spot, including the replacement it had issued to sync-3 eight milliseconds before. This photo service revokes the family's refresh tokens and lets access tokens already issued run out, which is why the renders kept working. Some servers revokeCancelling a credential, token, certificate, or authenticator before it would expire, so that it is no longer accepted. Whether every copy stops working at once depends on how services check it. those access tokens as well, and then the failure shows up within seconds instead of an hour later.
Was it theft? The server could not know, so it did the right thing. You can know more. Both requests appear in your own trace, from two of your own workers, authenticated as printer-sync, five milliseconds apart. A thief's request would be one your trace does not contain. Searching the audit trail for refresh_replayed from printer-sync since the scale-up finds 214 revoked families, and for every one of them the trace shows two of your workers sending the same fingerprint within a few milliseconds. This is a race in your service.
One renewal for each stored token
The refresh code does have a lock, but it is an in-memory mutex: a flag inside one running process that lets only one of that process's workers into the refresh code at a time. It worked when one process ran every worker. With four instances, each has its own mutex, and none of them knows about the others. Any coordination has to cover every process that can read the same stored refresh token.
There are two common designs. One is a single owner: a small token service holds each connection's refresh token, and workers ask it for a current access token instead of refreshing themselves. The other is a shared lock per connection, held somewhere every instance can see, such as the database that already stores the tokens. The sync service takes the second route. In outline, a worker first checks whether the stored access token is still good. Only if it is about to expire does the worker take the lock, read the row again, refresh and store the result. Here is that logic as the sync service's TypeScript:
async function accessTokenFor(connectionId: string): Promise<string> {
let conn = await db.connections.get(connectionId);
if (!expiresSoon(conn)) return conn.accessToken;
// The lock lives in the shared database, so it covers every worker on every instance.
return db.withLock(`refresh:${connectionId}`, { leaseMs: 15000 }, async () => {
// Another worker may have renewed while this one waited for the lock.
conn = await db.connections.get(connectionId);
if (!expiresSoon(conn)) return conn.accessToken;
const tokens = await refreshAtTokenEndpoint(conn.refreshToken);
// One write for the new refresh token, access token and expiry,
// applied only if nobody else changed the row since it was read.
await db.connections.update(connectionId,
{ ...tokens, version: conn.version + 1 },
{ whereVersion: conn.version });
return tokens.accessToken;
});
}Three details carry the repair. The worker reads the row again after taking the lock, so a worker that waited uses the renewal another worker just made instead of refreshing a second time. The new refresh token, access token and expiry are stored in one write, so no reader can ever see a new access token next to an old refresh token. The write is conditional on the row's version, so a slow response arriving late cannot overwrite newer tokens. The lock's lease has to outlast the token request and the write, or a second worker could take the lock while the first is still waiting for the server.
One failure remains that no lock prevents. If a worker crashes after the photo service rotates the token but before the write, the replacement is lost and the stored token has already been used. The next refresh is reuse, and the family ends. Keeping the write immediately after the response, with nothing slow in between, makes that window as small as it can be.
The reuse grace trade-off
A teammate suggests asking the photo service to turn off reuse detection for printer-sync. That would hide the race by removing the check that notices stolen tokens, and the race would still be there, quietly sending two refreshes where one is enough.
Some authorization servers offer a narrower option: a short reuse grace period, often a few seconds, during which the previous refresh token is still accepted after rotation. It is a real trade-off. Within the window, a legitimate client whose response was lost can recover without the family being revoked. Within the same window, someone holding a stolen copy can use it too, and the server cannot tell the two apart. A grace period can soften the crash window described above. It is not a substitute for coordination, because with a correct lock the second refresh is never sent.
Verify one renewal and the reuse check
Before the fix goes to production, the team tests it in staging with forty workers spread across four instances, all handed jobs for the same test connection just as its access token expires. The trace is the proof, not the absence of errors: each renewal shows exactly one refresh.request, and no fingerprint is ever sent twice. Every worker's photo request answers 200 with the access token from that one renewal.
Then they check that the server's protection still works. With a separate test connection, they refresh once and send the old refresh token again by hand. It must still be refused with invalid_grant, and the audit trail must show refresh_replayed and the family revoked. A repair that made this request succeed would have removed a protection, not fixed a fault.
Revoked families cannot be revived. The 214 affected customers, Mara included, need a fresh authorization, so support sends them one reconnection email with an apology instead of the automated one, and confirms after the release that the daily count of refresh_replayed events for printer-sync has dropped to zero.
Worked example: the handoff note
The note separates what was ruled out from what was repaired, because "was it theft?" is the first question anyone reading it will ask:
Symptom: Customers emailed to reconnect photo accounts, about 10 a day, evenings only.
Failed stage: Refresh at auth.photos.example: 400 invalid_grant.
Cause: Two sync workers on different instances refreshed one connection with the same
refresh token (rt_fp 9c41e0b2, 5 ms apart). The second was treated as reuse
(audit reason refresh_replayed) and family g-77d0 was revoked. The winner's
replacement was refused an hour later (request 73c2b9e0-1f4a-4d86-b5e3-8a09d6c1e27f).
The in-memory refresh lock stopped covering all workers when the service
scaled to four instances.
Ruled out: Theft. Every replayed token in the 214 affected families was sent by two of our
own workers within milliseconds.
Repair: Refresh behind a per-connection lock in the shared database, re-read after
locking, conditional single write of all token fields (release 2026.10.16-1).
Verification: Staging, 40 workers on 4 instances: one refresh per renewal, all reads 200.
Manual replay of a used refresh token: still invalid_grant, family revoked.
Not changed: Photo service reuse detection, rotation and grace settings.
Follow-up: 214 customers asked to reconnect once; monitor refresh_replayed for printer-sync.The reply to Mara is short: the problem was on the printing company's side, her account was never at risk, and one more reconnection should be the last.
Check your understanding
Try these questions before moving on. If an answer isn't right, use the feedback and try again.
Try it in the Lab
- Find why two panels lose their connectionReproduce two panels renewing with the same refresh token, read the reuse containment, repair the pattern with one shared renewal and keep replay containment strict.