Home / Writing
Refresh tokens

Row lock plus grace window: why both are needed

From secure-refresh-tokens
In plain English

When you log into an app, it hands you a secret "key" so you don't have to type your password every single time. That key gets swapped for a new one regularly, kind of like a hotel giving you a fresh room key whenever you check back in. If a stolen key ever gets used, the app can tell something's wrong. The hard part is that sometimes it's just you, like two open tabs or a slow phone retrying, not a thief, and a badly built system can't always tell the two apart. This is a small trick that tells them apart correctly. Useful for any app that keeps you signed in for a while: phone apps, websites you don't log into every single visit, anything with accounts

A stolen refresh token looks identical to the real one, right up until someone presents it a second time. Rotation makes that second use detectable: every refresh revokes the old token and issues a new one, so a replayed token means two parties held it

The hard part is concurrency. Two legitimate requests (two open tabs, a retry racing a proactive refresh) look exactly like a replay. The library handles that in two layers. A row lock (with_for_update) serializes requests presenting the same token, so only one wins the rotation and the session family can't fork into two. A 20-second grace window then lets the loser recover onto the family's current token instead of being logged out. A token replayed after that window is treated as theft, and the whole family is revoked

secure_refresh_tokens/rotation.py
result = await db.execute(
    select(RefreshToken).where(RefreshToken.token_hash.in_(candidate_hashes)).with_for_update()
)
row = result.scalar_one_or_none()
...
if row.revoked_at is not None:
    if (now - row.revoked_at).total_seconds() <= REUSE_GRACE_PERIOD_SECONDS:
        ...  # benign concurrent race: recover onto the family's live token
    else:
        await _revoke_family(db, row.family_id)
        await db.commit()
        raise RefreshTokenReusedError(user_id=row.user_id, family_id=row.family_id)

Tested, not just reasoned about: on real Postgres in CI, 8 concurrent rotation attempts on one token land as a single unforked chain, and removing the lock makes that test fail. The other 27 tests cover the rest of the state machine on SQLite, which silently ignores row locks

All write-ups Contact