# Why two workers are enough to kill an OAuth integration

> A conditional write keeps the database correct, yet the correct token it holds may already have been revoked.

Original: https://fdetimes.net/en/guides/oauth-refresh-token-race-condition/

Atlassian, by default, does not trigger breach detection when a refresh token is exchanged several times within 10 minutes. Okta's default grace period is only 30 seconds, and Auth0 leaves its overlap period off by default. The same code can run quietly for one customer and fail for another.

The failure is usually hard to see coming. Nango notes that refresh races rarely surface in development or in single-threaded testing. For an FDE, the demo may run smoothly until the customer turns on a second worker.

This exercise recreates the bug in a single Python file, tries a fix that falls short, then repairs it until only one refresh call remains. You need Python 3 and the standard library, plus PostgreSQL if you want to carry the fix over to real data.

## Step 1: Rule out other causes before blaming the workers

RFC 6749 uses `invalid_grant` for a token that is invalid, expired, revoked, mismatched on redirect URI or issued to another client. The error code alone is therefore not enough to diagnose a race.

Google has a trap of its own: each Google account is limited to 100 refresh tokens per OAuth client ID, and the oldest is invalidated without warning once that limit is exceeded. With Atlassian, a 403 `invalid_grant` can come from an application that fails to store the new refresh token it was given. The latter happens even with a single worker.

Add three fields to your logs: the connection ID, the worker name and the `version` of the token row at the time it was read. Do not log the token.

**Check:** if two workers refreshed from the same `version` just before the error appeared, the race hypothesis has support. If there was only one worker, look first at token storage, the client ID and the redirect URI.

## Step 2: Build an unforgiving server

RFC 9700 describes the core mechanism: when an invalidated token is sent again, the server cannot tell who sent it, so it revokes the active refresh token as well. The legitimate client also has to obtain authorization again.

Save the following as `race.py`. It is a simplified simulation: there is no HTTP and no access token, and the `db` dict stands in for a database.

```python
import threading

class InvalidGrant(Exception):
    pass

class FakeAuthServer:
    # Strict rotation: no grace period
    def __init__(self):
        self.mutex = threading.Lock()
        self.active = "rt-0"
        self.calls = 0

    def refresh(self, token):
        with self.mutex:
            self.calls += 1
            if token != self.active:
                self.active = None  # revoke the active token
                raise InvalidGrant("invalid_grant")
            self.active = f"rt-{self.calls}"
            return self.active

def naive(name, auth, db, gate):
    token = db["refresh_token"]
    gate.wait()  # force both workers to finish reading the old token
    try:
        db["refresh_token"] = auth.refresh(token)
        db["version"] += 1
        print(f"{name}: ok")
    except InvalidGrant as err:
        print(f"{name}: {err}")

def run(worker):
    auth = FakeAuthServer()
    db = {"refresh_token": "rt-0", "version": 0}
    gate = threading.Barrier(2)
    threads = [
        threading.Thread(target=worker, args=(name, auth, db, gate))
        for name in ("worker-A", "worker-B")
    ]
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    print(f"calls={auth.calls} db={db['refresh_token']} server={auth.active}")
    return auth, db

run(naive)
```

```bash
python3 race.py
```

**Check:** one worker prints `ok` and the other `invalid_grant`; the winner may vary. The last line must be `calls=2 db=rt-1 server=None`.

The telling detail is `db=rt-1`. The database holds the latest token, but the server has no live token left. An on-call engineer looking only at the table would think everything was fine.

## Step 3: What does a conditional write save?

WorkOS suggests adding a `version` column so that the UPDATE succeeds only if the version has not changed. Zero rows updated means another worker wrote first, so the losing worker re-reads the row and uses the value there without refreshing again.

In SQL, with an illustrative table name, the write looks like this:

```sql
UPDATE oauth_connection
SET refresh_token = 'new_token', version = version + 1
WHERE id = 42 AND version = 7;
```

Now try the idea in `race.py`. Insert this before the `run(naive)` line, then change the last line to `run(conditional)`:

```python
store_lock = threading.Lock()  # simulates an atomic UPDATE

def conditional(name, auth, db, gate):
    seen, token = db["version"], db["refresh_token"]
    gate.wait()
    try:
        new = auth.refresh(token)
    except InvalidGrant as err:
        print(f"{name}: {err}")
        return
    with store_lock:
        if db["version"] == seen:
            db["refresh_token"] = new
            db["version"] += 1
    print(f"{name}: ok")
```

**Check:** the last line is still `calls=2 db=rt-1 server=None`. The conditional write worked correctly, but the damage was done by the call before it.

WorkOS separates the two failures as well. A lost update caused by an overwrite is one problem; token reuse detection cannot be undone once it has fired, and the only remedy is to avoid sending the second call.

The choice therefore depends on the provider. Before writing the fix, fill in this table for your customer:

| Provider | How long does the old token still work? | What to do first |
|---|---|---|
| Auth0 | Off by default; if enabled, only the immediately preceding token is accepted | Ask for the tenant's leeway setting |
| Okta | 30 seconds by default, adjustable from 0 to 60 | Confirm the customer has not set it to 0 |
| Atlassian 3LO | 10 minutes by default | Check that new tokens are being stored |
| Slack | Short grace period; tokens are designed for single use | Do not rely on the grace period; centralize refreshes |

If the provider has a grace period, a versioned write is a compact starting point. Verify that the winning worker's token still works after the losing worker has refreshed too. If you are not sure there is a grace period, prevent the second call.

## Step 4: Acquire the lock, then re-read

Insert the following function before the last line, then call `run(locked)`. `row_lock` plays the part of a database row lock:

```python
row_lock = threading.Lock()

def locked(name, auth, db, gate):
    seen = db["version"]
    gate.wait()
    with row_lock:
        if db["version"] != seen:
            print(f"{name}: using existing token")
            return
        db["refresh_token"] = auth.refresh(db["refresh_token"])
        db["version"] += 1
        print(f"{name}: refreshed")
```

**Check:** one worker refreshes and the other uses the existing token. The last line must be `calls=1 db=rt-1 server=rt-1`.

In PostgreSQL, `SELECT ... FOR UPDATE` makes any other transaction that wants to lock or modify the same row wait until the current one ends. A simplified skeleton follows; 42 and 7 are illustrative values:

```sql
BEGIN;
SELECT refresh_token, version
FROM oauth_connection
WHERE id = 42
FOR UPDATE;
-- version differs from the initial read: COMMIT, use the data just read
-- version is still 7: the application calls the token endpoint here
UPDATE oauth_connection
SET refresh_token = 'new_token', version = version + 1
WHERE id = 42 AND version = 7;
COMMIT;
```

Set a timeout on the HTTP call, because the transaction stays open and other workers wait while it runs.

**Check:** open two database sessions at the isolation level the customer's application uses, and have both run `SELECT ... FOR UPDATE` on row 42. The second session must block. When the first commits, see whether the second returns version 8, returns version 7 or raises an error.

Version 8 is the result you want. If the second session raises an error, the worker must roll back and re-read in a new transaction before deciding whether to refresh. If it still returns 7, do not deploy: the second worker would call refresh with the old token.

Without a shared PostgreSQL instance, Redis is another route:

```text
SET lock:oauth:42 random_value NX PX 30000
```

This lock expires on its own after 30000 milliseconds. The Redis documentation requires deleting it only while the value still matches, using `DELEX` from Redis 8.4 or a Lua script, so that a client past its deadline does not delete another client's lock.

Keep the version comparison to prevent overwrites, but it cannot help if the Redis lock expires midway. In that case the first worker has not finished writing, and the next still sees the old version and sends a second refresh call. Make the HTTP timeout well shorter than the lock's lifetime.

**Key point:** A lock without a re-read only makes two bad calls queue more politely.

## Step 5: Accept the fix over 100 rounds

One correct run proves little. Replace the last line of `race.py` with the code below; each round uses a fresh simulated server and two workers:

```python
def accept(worker, rounds=100):
    total = mismatched = 0
    for _ in range(rounds):
        auth, db = run(worker)
        total += auth.calls
        if db["refresh_token"] != auth.active:
            mismatched += 1
    print(f"total={total} mismatched={mismatched}")
    assert total == rounds, "extra refresh calls detected"
    assert mismatched == 0, "database does not match server"

accept(locked)
```

**Check:** the `locked` version must end with `total=100 mismatched=0`. Switch to `accept(conditional)` and you will see `total=200 mismatched=100` followed by an `AssertionError`: the test catches the incomplete fix.

## Three bugs that slip through code review

The easiest mistake is to read the token before waiting for the lock, then reuse the stale variable. Try it in `locked`: save `token` before `gate.wait()`, remove the version comparison and pass `token` to `auth.refresh`. The second worker will get `invalid_grant` again even though the lock still works.

The next is to retry every `invalid_grant` automatically with the old token. With Auth0, even with leeway enabled, exchanging a token older than the immediately preceding one triggers breach detection. Such retries can easily make an incident worse.

The third is to miss a write path. RFC 6749 requires the client to replace its old refresh token when the server returns a new one, so cron jobs, webhooks and APIs must all share one refresh function. A single path around the lock is enough to bring the race back.

Even with a lock, the integration can still break for other reasons. The process may die after the server issues a new token but before the database has saved it, so the runbook still needs a reauthorization step.

## What to bring to the customer's incident call

When the integration has just failed, pause the refresh workers for that connection, preserve the logs and establish whether two calls came from the same version. If the active token has been revoked, ask someone with authority on the customer's side to reauthorize, then deploy the fix before turning multiple workers back on.

Do not accept "it's running again" as sign-off. Give the customer the results of the Step 5 test, before and after the fix.

That test also makes a good portfolio piece. On your CV, describe how you reproduced the bug, chose the lock and verified the number of calls; in an interview, explain why the conditional write still gives `calls=2`. If a job posting mentions OAuth, SaaS integrations or background jobs, this is a story to prepare.

Customers will never see the lock you added. What they will notice is that they no longer have to click "reconnect" whenever the system gets a little busier.

**Try this week:**

- Run race.py with all three worker versions and record the calls count for each.
- Find every place that calls refresh in an integration you own, including cron jobs and webhooks, and check whether they all go through the same function.
- Add each provider's refresh token reuse policy to the runbook, along with the person on the customer's side who has authority to reauthorize the connection.

## Sources

- [RFC 6749 - The OAuth 2.0 Authorization Framework](https://www.rfc-editor.org/rfc/rfc6749.html)

- [RFC 9700 - Best Current Practice for OAuth 2.0 Security](https://www.rfc-editor.org/rfc/rfc9700.html)

- [Configure Refresh Token Rotation](https://auth0.com/docs/secure/tokens/refresh-tokens/configure-refresh-token-rotation)

- [Refresh access tokens and rotate refresh tokens](https://developer.okta.com/docs/guides/refresh-tokens/main/)

- [OAuth 2.0 (3LO) apps](https://developer.atlassian.com/cloud/jira/platform/oauth-2-3lo-apps/)

- [Using token rotation](https://docs.slack.dev/authentication/using-token-rotation/)

- [Using OAuth 2.0 to Access Google APIs](https://developers.google.com/identity/protocols/oauth2)

- [OAuth token refresh has a race condition. Fix it with a conditional write, not a distributed lock.](https://workos.com/blog/oauth-refresh-token-race-condition)

- [Distributed Locks with Redis](https://redis.io/docs/latest/develop/clients/patterns/distributed-locks/)

- [PostgreSQL: Documentation: 19: 13.3. Explicit Locking](https://www.postgresql.org/docs/current/explicit-locking.html)

- [How to handle concurrency with OAuth token refreshes](https://nango.dev/blog/concurrency-with-oauth-token-refreshes)
