Intermittent 401s That Aren't Actually Auth Failures
A 401 is supposed to mean one thing: the request wasn't authenticated. In practice I've seen teams spend hours rotating credentials, regenerating tokens and rewriting auth fixtures, only to find the credentials were fine all along. The 401 was a symptom. The cause was a race in token setup, a clock that drifted, a stale header on a shared session, or a request that landed on a server configured differently from the rest.
Intermittent 401s have become more common as suites run in parallel and as agents enter the picture. Several test workers, or several agent sessions, sharing one cached token is a reliable way to produce them. They also attract the worst kind of fix. Ask an assistant to make the failures go away and it will often add a retry on 401 or fetch a fresh token before every call. The tests pass, and you lose the signal that something in your token handling, or in the API's, is wrong.
Here are the non-auth causes I check first, how I instrument a suite to catch the real culprit, and the fixes that stop these 401s coming back.
Learn Node.js, Cucumber, GitHub Copilot, APIs, CI/CD, and modern automation by building a complete framework.
The non-auth causes behind most intermittent 401s
Token refresh races
Two tests, or two parallel workers, notice the token is about to expire and both refresh it. With providers that rotate refresh tokens, the second refresh can invalidate the first token, and whichever test is still holding it gets a 401. The failure depends on timing, so it comes and goes.
Clock skew
JWTs carry iat, nbf and exp claims. If the machine issuing the token and the service validating it disagree about the time, a brand-new token can look "not yet valid", or an almost-expired one can look expired early. CI runners and containers are common places for clocks to drift. Many validators allow a small leeway; if yours doesn't, small skew is enough.
Stale or leaking headers on a shared session
A test that sets a different Authorization header on a shared requests.Session, say to check a lower-privileged role, and doesn't restore it, changes the credentials for every test that runs after it. Whether you see a 401 depends on test order.
Inconsistent servers behind a load balancer
If one instance has an outdated signing key, a stale key cache, or different configuration, only the requests routed to it fail. From the test's point of view, the same token works most of the time.
Tokens issued for the wrong place
A token cached for one environment, audience or tenant gets reused against another. This often shows up after someone runs the suite locally against staging and then against dev without clearing a token cache file.
Instrumenting the suite to catch the real culprit
The goal is that the next intermittent 401 arrives with enough context to tell these causes apart. I log the token's claims (never the token itself), the local clock, the server's clock from the Date header, and which worker made the call:
import base64
import json
import os
import time
from email.utils import parsedate_to_datetime
def jwt_claims(token):
payload = token.split(".")[1]
payload += "=" * (-len(payload) % 4)
return json.loads(base64.urlsafe_b64decode(payload))
def describe_401(response):
auth = response.request.headers.get("Authorization", "")
claims = jwt_claims(auth.removeprefix("Bearer ")) if auth.count(".") == 2 else {}
server_date = response.headers.get("Date")
server_time = parsedate_to_datetime(server_date).timestamp() if server_date else None
now = time.time()
return {
"url": response.request.url,
"worker": os.getenv("PYTEST_XDIST_WORKER", "main"),
"local_time": int(now),
"server_time": int(server_time) if server_time else None,
"skew_seconds": round(now - server_time) if server_time else None,
"iat": claims.get("iat"),
"nbf": claims.get("nbf"),
"exp": claims.get("exp"),
"seconds_to_expiry": claims["exp"] - int(now) if "exp" in claims else None,
"aud": claims.get("aud"),
"www_authenticate": response.headers.get("WWW-Authenticate"),
"request_id": response.headers.get("X-Request-Id"),
}
Decoding the payload without verifying the signature is fine here: it's diagnostic output, not an auth decision. The WWW-Authenticate header is worth logging because many servers put the actual reason there, such as an expired or invalid token. Use whatever request ID header your API returns so you can find the server-side log for the failing call.
Attach that to the assertion message, or log it from your client whenever a 401 comes back. After a few failures, the pattern usually answers the question:
- Small
seconds_to_expiry, or failures clustered by worker: refresh race or expiry handling. - Non-zero skew and a very recent
iat: clock skew. - Failures only after particular tests: header leakage on a shared session.
- Healthy claims and random distribution: look at the server side, starting with which instance handled the request.
- Unexpected
aud: a token for the wrong environment or tenant.
When the cause turns out to be on the API side, the same data makes a report developers can act on. I go into that in reproducing authentication errors your devs can actually fix.
Fixing the suite so these 401s stop coming back
- One token owner per process. Put token acquisition behind a single session-scoped fixture with a lock, and refresh ahead of expiry rather than on failure. Under pytest-xdist each worker is its own process, so give each worker its own token, or its own test user, instead of sharing a cache file between workers.
- Never mutate shared headers. When a test needs a different role, create a separate client for that role rather than changing the shared session.
- Keep clocks honest. Make sure CI runners and containers sync time, and log skew at session start so drift is visible before it causes failures.
- Scope caches to the environment. Key any cached token by base URL and audience, or don't cache across runs at all.
A minimal token fixture that refreshes ahead of expiry looks like this:
import threading
import time
import pytest
class TokenProvider:
def __init__(self, fetch, margin=60):
self._fetch = fetch # returns (access_token, expires_in_seconds)
self._margin = margin
self._lock = threading.Lock()
self._token, self._expires_at = None, 0.0
def get(self):
with self._lock:
if time.monotonic() >= self._expires_at - self._margin:
token, expires_in = self._fetch()
self._token = token
self._expires_at = time.monotonic() + expires_in
return self._token
@pytest.fixture(scope="session")
def tokens(fetch_token):
return TokenProvider(fetch_token)
For the wider pattern of getting tokens without hard-coding them, see testing OAuth-protected APIs without hardcoding tokens.
Keeping agents from masking the signal
Two rules go in my repository instructions, in .github/copilot-instructions.md or the equivalent for whichever agent works in the repo. First, never retry on 401 and never fetch a new token per request to make a test pass; a 401 is a finding to investigate. Second, all authentication goes through the token fixture, so there is exactly one place that handles credentials.
The same causes show up when agents call your API as a tool. Several agent sessions sharing one service credential will hit the same refresh races as parallel test workers. An agent that gets a 401 back from a tool may retry repeatedly or tell the user the action worked. When I test agent tool integrations, I include a case where the tool returns 401 and assert that the agent reports the failure clearly instead of carrying on.
An intermittent 401 usually isn't about credentials. Log the claims, the clocks and the worker, and the cause tends to reveal itself. Token expiry across environments has its own set of traps, which I cover in diagnosing token expiry failures across test environments. If you'd like to build auth handling like this into a suite from the start, my API testing courses cover it with VS Code and GitHub Copilot.