java.net.ProtocolException: Too many follow-up requests: 21 from an OkHttp Authenticator means your 401 handler never gave up. OkHttp calls authenticate() after every 401. Each request it returns is one follow-up. After 20 follow-ups, OkHttp throws on the next one. In the code below, two stacked bugs cause it. First, the retry adds the new token with addHeader. So the request now carries the expired token and the new one. A server that reads the first value still sees the expired token and answers 401 again. Second, the authenticator has no stop condition. It refreshes on every 401, even when the request it just built has already failed. Our repro made 21 refresh calls for one API call. The fix is to replace the header with header(). Return null when response.priorResponse is set, because that 401 came from a retry. Refresh only when no other call has refreshed already.
A token refresh that makes 21 refresh calls for one request
The running example is a profile call behind a bearer token. An application interceptor adds the stored access token to every request. An Authenticator handles the 401 when that token expires. It refreshes synchronously, saves the new token and retries.
class TokenStore { @Volatile var accessToken = "t0" }
class AuthInterceptor(private val store: TokenStore) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response =
chain.proceed(
chain.request().newBuilder()
.addHeader("Authorization", "Bearer ${store.accessToken}")
.build()
)
}
class TokenAuthenticator(
private val store: TokenStore,
private val refresher: AuthRefresher, // blocking POST /oauth/token
) : Authenticator {
override fun authenticate(route: Route?, response: Response): Request? {
val newToken = refresher.refresh()
store.accessToken = newToken
return response.request.newBuilder()
.addHeader("Authorization", "Bearer $newToken")
.build()
}
}
val client = OkHttpClient.Builder()
.addInterceptor(AuthInterceptor(store))
.authenticator(TokenAuthenticator(store, refresher))
.build()
We ran it against a local server built on the JDK’s HttpServer. The server accepts only the newest token. It reads the first Authorization value. The fake refresher issues t1, t2 and so on. Each new token becomes the only valid one. The store starts with t0. The server already rejects it. The run used OkHttp 4.12.0, Kotlin 2.4.20 and OpenJDK 25.
java.net.ProtocolException: Too many follow-up requests: 21 refresh calls=21 api hits=21
Every refresh worked. Every retry still got 401. The caller gets an exception instead of a response. The auth server took 21 refresh requests for one profile load. Retrofit runs on OkHttp, so a Retrofit call fails with the same exception.
addHeader keeps the expired token in front of the new one
OkHttp’s Request.Builder source documents two different methods. header(name, value) sets the header and replaces every existing value with that name. addHeader(name, value) appends another value. Its KDoc recommends it for headers that can repeat, like Cookie.
response.request inside authenticate() is the request that got the 401. The interceptor already put Bearer t0 on it. So addHeader produces a request with two values, t0 and then t1. The server reads t0 and rejects it. The next round appends t2 after both. The first value stays t0 for all 20 retries.
The client-side view hides this. Headers.get returns the last value for a name. So request.header("Authorization") shows the fresh token. A log line that prints that value looks correct. Only a full header dump, or a network interceptor log, shows both values.
Which value a server uses for a duplicated Authorization header depends on the server. Ours read the first, so the retry failed every time. The interceptor has the same problem in a quieter form. It works only because the first request has no Authorization header yet. Use header() there too.
Too many follow-up requests comes from a missing stop condition
The duplicate header is why every retry fails. The missing stop condition is why the failure costs 21 refreshes and an exception. The two bugs are separate. Fixing the first one leaves the second one in place.
OkHttp’s RetryAndFollowUpInterceptor handles a 401 by calling client.authenticator.authenticate(). A non-null result becomes the next request. The interceptor counts follow-ups against MAX_FOLLOW_UPS, a private constant set to 20. The 21st follow-up throws ProtocolException("Too many follow-up requests: 21"). The same limit sits in the 4.12.0 source and on the current main branch. Redirects share this counter. That explains the error’s wording.
The Authenticator KDoc puts the stop condition on you. Implementations should check whether the request already tried to authenticate. If so, further attempts are likely useless and the authenticator should give up. Returning null hands the 401 back to the caller. The same KDoc shows a responseCount helper that walks priorResponse to count attempts.
To isolate this bug, we switched both addHeader calls to header() and left the authenticator otherwise unchanged. Then we revoked the session on the server, so it rejects every access token. The refresh endpoint still issued tokens. That can happen when the session check and the token endpoint are separate services.
expired token, 1 call: results=[200] refresh calls=1 api hits=2 expired token, 3 parallel calls: results=[200, 200, 200] refresh calls=4 api hits=7 revoked session, 1 call: results=[java.net.ProtocolException: Too many follow-up requests: 21] refresh calls=21 api hits=21
The normal expiry case now works. The revoked session brings back the same 21 refreshes and the same exception. The app never sees the 401 it needs to log the user out. The parallel case shows a third cost. Three calls hit 401 together and caused four refreshes in this run. Each authenticate() runs on its own call’s thread. One refresh can replace a token another call just got, so that call fails and refreshes again. With refresh token rotation, the second refresh may send an already used refresh token. The OAuth 2.0 security best practice, RFC 9700, describes that reuse as a sign of theft. The server then revokes the active refresh token. That logs the user out.
Replace the header, stop after one retry, refresh once
The fixed authenticator does three things in order. It returns null if this 401 answered a retry. It refreshes only if the failed request sent the token that is still current. Otherwise another call already refreshed, so it reuses that token. Then it sets the header with header().
class AuthInterceptor(private val store: TokenStore) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response =
chain.proceed(
chain.request().newBuilder()
.header("Authorization", "Bearer ${store.accessToken}")
.build()
)
}
class TokenAuthenticator(
private val store: TokenStore,
private val refresher: AuthRefresher, // returns null when the refresh is refused
) : Authenticator {
override fun authenticate(route: Route?, response: Response): Request? {
// This 401 answered a request we already retried: give the 401 to the caller.
if (response.priorResponse != null) return null
val sentToken = response.request.header("Authorization")?.removePrefix("Bearer ")
val token = synchronized(this) {
if (sentToken != store.accessToken) {
store.accessToken // another call refreshed while this one waited
} else {
refresher.refresh()?.also { store.accessToken = it } ?: return null
}
}
return response.request.newBuilder()
.header("Authorization", "Bearer $token")
.build()
}
}
The same three scenarios against the fixed code:
expired token, 1 call: results=[200] refresh calls=1 api hits=2 expired token, 3 parallel calls: results=[200, 200, 200] refresh calls=1 api hits=6 revoked session, 1 call: results=[401] refresh calls=1 api hits=2
One refresh per expiry, even with three calls in flight. A revoked session now costs one refresh and returns a plain 401. Your repository can map that 401 to a logout. The priorResponse check allows exactly one retry. Use the KDoc’s responseCount helper if your backend needs more.
synchronized is correct here because authenticate() is a blocking callback on an OkHttp thread. A coroutine Mutex would need runBlocking inside it. If the refresh lives in a suspend token cache, keep its own lock separate. Our Mutex withLock deadlock post shows what happens when a refresh path locks the same Mutex twice. Also make the refresh call with a client that has no Authenticator. Otherwise a 401 from the token endpoint starts its own refresh.
The answer that covers both bugs in a live debugging round
In a live debugging round you may get the stack trace and these two classes. Start with the error and reason backward to the code.
- Read the number. 21 means OkHttp made 20 follow-ups and refused the 21st. The authenticator returned a request every time.
- Ask why the retry fails. Look at how the new token goes on.
addHeaderappends, so the expired token is still the first value. - Name the trap in logging.
header("Authorization")returns the last value, so a log shows the new token. - Ask why it retried 20 times. There’s no check for a previous attempt. The
AuthenticatorKDoc says to give up when the request already tried to authenticate. - Fix both. Use
header()in the interceptor and the authenticator. ReturnnullwhenpriorResponseis set. - Raise the concurrency case before the interviewer does. Parallel 401s each call
authenticate(). Compare the sent token with the stored one inside a lock. Refresh only on a match.
Say step 3 out loud. It explains why the developer believed the code was correct. Hass explains how the round scores a second bug in finding the bug and still not passing. Our OkHttp interceptor body post covers a different interceptor trap on the same client.
Wrong answers that keep the loop or break the refresh
“Copy the give-up check from the OkHttp recipe.” The OkHttp recipes authenticator returns null when the failed request already has an Authorization header. That check suits the recipe’s case, where the first request carries no credentials. In a bearer setup, the interceptor adds the header to every request. We added that line to the authenticator and ran it. Every call returned 401 with zero refreshes, because the check gave up on the first expiry.
“Return null only when the refresh fails.” That handles a dead refresh token. It doesn’t handle the revoked-session case above, where every refresh succeeds and the API still says 401. That run produced 21 refreshes with the header() fix in place.
“Catch ProtocolException and log the user out.” The 21 refresh calls have already happened by then. The caller also loses the real 401. It can’t tell an auth failure from a broken redirect chain.
“Raise OkHttp’s follow-up limit.” MAX_FOLLOW_UPS is a private constant with no builder option. A higher limit would only add more refresh calls before the same failure.