Course contentsShow
← Web Development
Lesson 1612 of 2,98229. Web Authentication PatternsFree lesson

Race Conditions in Token Refresh

Prevent multiple simultaneous refresh requests by queuing API calls until a single refresh operation completes.

Race Conditions in Token Refresh

What you'll learn: How to prevent multiple API calls from triggering duplicate token refresh requests simultaneously.


When your access token expires, you need to refresh it. But what happens when multiple API calls all fail at the same moment because the token is expired? Without proper handling, each call might trigger its own refresh request—leading to race conditions where several refresh attempts happen in parallel.

The Problem

Imagine three API requests (/profile, /messages, /settings) all firing within milliseconds. The access token has just expired. Each request fails with a 401 status, and each independently tries to refresh the token. Now you have three refresh requests racing to complete, potentially causing:

  • Wasted network bandwidth
  • Server load from duplicate requests
  • Token rotation issues (if your refresh invalidates previous tokens)
  • Unpredictable application state

The Solution: Queue and Wait

The pattern is simple: only one refresh operation should run at a time, while all other requests wait for it to complete.

Think of it like a bathroom door. If one person is inside refreshing (the token), everyone else queues outside. When the door opens, everyone benefits from the same refreshed token—no need for each person to refresh separately.

Implementation approach:

  1. Track whether a refresh is currently in progress (a flag or promise)
  2. If a refresh is already running, queue the failed request to retry after it completes
  3. Once the refresh succeeds, resolve all queued requests with the new token
  4. If the refresh fails, reject all queued requests together

This ensures a single refresh operation serves all pending API calls, preventing race conditions entirely.

Key Takeaway: Prevent race conditions during token refresh by ensuring only one refresh request executes at a time while queuing other API calls to retry once the refresh completes.