{"id":998,"date":"2026-11-13T13:52:00","date_gmt":"2026-11-13T12:52:00","guid":{"rendered":"https:\/\/grindloop.ai\/blog\/?p=998"},"modified":"2026-11-12T18:22:43","modified_gmt":"2026-11-12T17:22:43","slug":"okhttp-too-many-follow-up-requests-21","status":"publish","type":"post","link":"https:\/\/grindloop.ai\/blog\/okhttp-too-many-follow-up-requests-21\/","title":{"rendered":"ProtocolException: Too Many Follow-Up Requests: 21 From an OkHttp Authenticator"},"content":{"rendered":"<p><code>java.net.ProtocolException: Too many follow-up requests: 21<\/code> from an OkHttp <code>Authenticator<\/code> means your 401 handler never gave up. OkHttp calls <code>authenticate()<\/code> 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 <code>addHeader<\/code>. 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 <code>header()<\/code>. Return <code>null<\/code> when <code>response.priorResponse<\/code> is set, because that 401 came from a retry. Refresh only when no other call has refreshed already.<\/p>\n\n<h2>A token refresh that makes 21 refresh calls for one request<\/h2>\n\n<p>The running example is a profile call behind a bearer token. An application interceptor adds the stored access token to every request. An <code>Authenticator<\/code> handles the 401 when that token expires. It refreshes synchronously, saves the new token and retries.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">class TokenStore { @Volatile var accessToken = \"t0\" }\n\nclass AuthInterceptor(private val store: TokenStore) : Interceptor {\n    override fun intercept(chain: Interceptor.Chain): Response =\n        chain.proceed(\n            chain.request().newBuilder()\n                .addHeader(\"Authorization\", \"Bearer ${store.accessToken}\")\n                .build()\n        )\n}\n\nclass TokenAuthenticator(\n    private val store: TokenStore,\n    private val refresher: AuthRefresher, \/\/ blocking POST \/oauth\/token\n) : Authenticator {\n    override fun authenticate(route: Route?, response: Response): Request? {\n        val newToken = refresher.refresh()\n        store.accessToken = newToken\n        return response.request.newBuilder()\n            .addHeader(\"Authorization\", \"Bearer $newToken\")\n            .build()\n    }\n}\n\nval client = OkHttpClient.Builder()\n    .addInterceptor(AuthInterceptor(store))\n    .authenticator(TokenAuthenticator(store, refresher))\n    .build()<\/pre>\n\n\n<p>We ran it against a local server built on the JDK&#8217;s <code>HttpServer<\/code>. The server accepts only the newest token. It reads the first <code>Authorization<\/code> value. The fake refresher issues <code>t1<\/code>, <code>t2<\/code> and so on. Each new token becomes the only valid one. The store starts with <code>t0<\/code>. The server already rejects it. The run used OkHttp 4.12.0, Kotlin 2.4.20 and OpenJDK 25.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">java.net.ProtocolException: Too many follow-up requests: 21\nrefresh calls=21 api hits=21<\/pre>\n\n\n<p>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.<\/p>\n\n<h2>addHeader keeps the expired token in front of the new one<\/h2>\n\n<p>OkHttp&#8217;s <a href=\"https:\/\/github.com\/square\/okhttp\/blob\/parent-4.12.0\/okhttp\/src\/main\/kotlin\/okhttp3\/Request.kt\" target=\"_blank\" rel=\"noopener\"><code>Request.Builder<\/code> source<\/a> documents two different methods. <code>header(name, value)<\/code> sets the header and replaces every existing value with that name. <code>addHeader(name, value)<\/code> appends another value. Its KDoc recommends it for headers that can repeat, like <code>Cookie<\/code>.<\/p>\n\n<p><code>response.request<\/code> inside <code>authenticate()<\/code> is the request that got the 401. The interceptor already put <code>Bearer t0<\/code> on it. So <code>addHeader<\/code> produces a request with two values, <code>t0<\/code> and then <code>t1<\/code>. The server reads <code>t0<\/code> and rejects it. The next round appends <code>t2<\/code> after both. The first value stays <code>t0<\/code> for all 20 retries.<\/p>\n\n<p>The client-side view hides this. <a href=\"https:\/\/github.com\/square\/okhttp\/blob\/parent-4.12.0\/okhttp\/src\/main\/kotlin\/okhttp3\/Headers.kt\" target=\"_blank\" rel=\"noopener\"><code>Headers.get<\/code><\/a> returns the last value for a name. So <code>request.header(\"Authorization\")<\/code> 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.<\/p>\n\n<p>Which value a server uses for a duplicated <code>Authorization<\/code> 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 <code>Authorization<\/code> header yet. Use <code>header()<\/code> there too.<\/p>\n\n<h2>Too many follow-up requests comes from a missing stop condition<\/h2>\n\n<p>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.<\/p>\n\n<p>OkHttp&#8217;s <a href=\"https:\/\/github.com\/square\/okhttp\/blob\/master\/okhttp\/src\/commonJvmAndroid\/kotlin\/okhttp3\/internal\/http\/RetryAndFollowUpInterceptor.kt\" target=\"_blank\" rel=\"noopener\"><code>RetryAndFollowUpInterceptor<\/code><\/a> handles a 401 by calling <code>client.authenticator.authenticate()<\/code>. A non-null result becomes the next request. The interceptor counts follow-ups against <code>MAX_FOLLOW_UPS<\/code>, a private constant set to 20. The 21st follow-up throws <code>ProtocolException(\"Too many follow-up requests: 21\")<\/code>. The same limit sits in the 4.12.0 source and on the current main branch. Redirects share this counter. That explains the error&#8217;s wording.<\/p>\n\n<p>The <a href=\"https:\/\/github.com\/square\/okhttp\/blob\/parent-4.12.0\/okhttp\/src\/main\/kotlin\/okhttp3\/Authenticator.kt\" target=\"_blank\" rel=\"noopener\"><code>Authenticator<\/code> KDoc<\/a> 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 <code>null<\/code> hands the 401 back to the caller. The same KDoc shows a <code>responseCount<\/code> helper that walks <code>priorResponse<\/code> to count attempts.<\/p>\n\n<p>To isolate this bug, we switched both <code>addHeader<\/code> calls to <code>header()<\/code> 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.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">expired token, 1 call: results=[200] refresh calls=1 api hits=2\nexpired token, 3 parallel calls: results=[200, 200, 200] refresh calls=4 api hits=7\nrevoked session, 1 call: results=[java.net.ProtocolException: Too many follow-up requests: 21] refresh calls=21 api hits=21<\/pre>\n\n\n<p>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 <code>authenticate()<\/code> runs on its own call&#8217;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 <a href=\"https:\/\/datatracker.ietf.org\/doc\/html\/rfc9700#section-4.14.2\" target=\"_blank\" rel=\"noopener\">OAuth 2.0 security best practice, RFC 9700<\/a>, describes that reuse as a sign of theft. The server then revokes the active refresh token. That logs the user out.<\/p>\n\n<h2>Replace the header, stop after one retry, refresh once<\/h2>\n\n<p>The fixed authenticator does three things in order. It returns <code>null<\/code> 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 <code>header()<\/code>.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">class AuthInterceptor(private val store: TokenStore) : Interceptor {\n    override fun intercept(chain: Interceptor.Chain): Response =\n        chain.proceed(\n            chain.request().newBuilder()\n                .header(\"Authorization\", \"Bearer ${store.accessToken}\")\n                .build()\n        )\n}\n\nclass TokenAuthenticator(\n    private val store: TokenStore,\n    private val refresher: AuthRefresher, \/\/ returns null when the refresh is refused\n) : Authenticator {\n    override fun authenticate(route: Route?, response: Response): Request? {\n        \/\/ This 401 answered a request we already retried: give the 401 to the caller.\n        if (response.priorResponse != null) return null\n\n        val sentToken = response.request.header(\"Authorization\")?.removePrefix(\"Bearer \")\n        val token = synchronized(this) {\n            if (sentToken != store.accessToken) {\n                store.accessToken \/\/ another call refreshed while this one waited\n            } else {\n                refresher.refresh()?.also { store.accessToken = it } ?: return null\n            }\n        }\n        return response.request.newBuilder()\n            .header(\"Authorization\", \"Bearer $token\")\n            .build()\n    }\n}<\/pre>\n\n\n<p>The same three scenarios against the fixed code:<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">expired token, 1 call: results=[200] refresh calls=1 api hits=2\nexpired token, 3 parallel calls: results=[200, 200, 200] refresh calls=1 api hits=6\nrevoked session, 1 call: results=[401] refresh calls=1 api hits=2<\/pre>\n\n\n<p>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 <code>priorResponse<\/code> check allows exactly one retry. Use the KDoc&#8217;s <code>responseCount<\/code> helper if your backend needs more.<\/p>\n\n<p><code>synchronized<\/code> is correct here because <code>authenticate()<\/code> is a blocking callback on an OkHttp thread. A coroutine <code>Mutex<\/code> would need <code>runBlocking<\/code> inside it. If the refresh lives in a suspend token cache, keep its own lock separate. Our <a href=\"https:\/\/grindloop.ai\/blog\/kotlin-mutex-withlock-deadlock\/\">Mutex withLock deadlock post<\/a> shows what happens when a refresh path locks the same <code>Mutex<\/code> twice. Also make the refresh call with a client that has no <code>Authenticator<\/code>. Otherwise a 401 from the token endpoint starts its own refresh.<\/p>\n\n<h2>The answer that covers both bugs in a live debugging round<\/h2>\n\n<p>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.<\/p>\n\n<ol>\n<li>Read the number. 21 means OkHttp made 20 follow-ups and refused the 21st. The authenticator returned a request every time.<\/li>\n<li>Ask why the retry fails. Look at how the new token goes on. <code>addHeader<\/code> appends, so the expired token is still the first value.<\/li>\n<li>Name the trap in logging. <code>header(\"Authorization\")<\/code> returns the last value, so a log shows the new token.<\/li>\n<li>Ask why it retried 20 times. There&#8217;s no check for a previous attempt. The <code>Authenticator<\/code> KDoc says to give up when the request already tried to authenticate.<\/li>\n<li>Fix both. Use <code>header()<\/code> in the interceptor and the authenticator. Return <code>null<\/code> when <code>priorResponse<\/code> is set.<\/li>\n<li>Raise the concurrency case before the interviewer does. Parallel 401s each call <code>authenticate()<\/code>. Compare the sent token with the stored one inside a lock. Refresh only on a match.<\/li>\n<\/ol>\n\n<p>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 <a href=\"https:\/\/grindloop.ai\/blog\/android-debugging-interview-second-bug\/\">finding the bug and still not passing<\/a>. Our <a href=\"https:\/\/grindloop.ai\/blog\/okhttp-interceptor-illegalstateexception-closed\/\">OkHttp interceptor body post<\/a> covers a different interceptor trap on the same client.<\/p>\n\n<h2>Wrong answers that keep the loop or break the refresh<\/h2>\n\n<p>&#8220;Copy the give-up check from the OkHttp recipe.&#8221; The <a href=\"https:\/\/github.com\/square\/okhttp\/blob\/parent-4.12.0\/docs\/recipes.md\" target=\"_blank\" rel=\"noopener\">OkHttp recipes<\/a> authenticator returns <code>null<\/code> when the failed request already has an <code>Authorization<\/code> header. That check suits the recipe&#8217;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.<\/p>\n\n<p>&#8220;Return <code>null<\/code> only when the refresh fails.&#8221; That handles a dead refresh token. It doesn&#8217;t handle the revoked-session case above, where every refresh succeeds and the API still says 401. That run produced 21 refreshes with the <code>header()<\/code> fix in place.<\/p>\n\n<p>&#8220;Catch <code>ProtocolException<\/code> and log the user out.&#8221; The 21 refresh calls have already happened by then. The caller also loses the real 401. It can&#8217;t tell an auth failure from a broken redirect chain.<\/p>\n\n<p>&#8220;Raise OkHttp&#8217;s follow-up limit.&#8221; <code>MAX_FOLLOW_UPS<\/code> is a private constant with no builder option. A higher limit would only add more refresh calls before the same failure.<\/p>","protected":false},"excerpt":{"rendered":"<p>Too many follow-up requests: 21 means your OkHttp Authenticator never gives up. addHeader keeps the expired token first. Runnable repro, fix, interview answer.<\/p>\n","protected":false},"author":2,"featured_media":1000,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"rank_math_title":"Too Many Follow-Up Requests: 21 From an OkHttp Authenticator","rank_math_description":"Too many follow-up requests: 21 means your OkHttp Authenticator never gives up. addHeader keeps the expired token first. Runnable repro, fix, interview answer.","rank_math_focus_keyword":"too many follow-up requests","footnotes":""},"categories":[9,6],"tags":[15,116,16,12,57,95,45],"class_list":["post-998","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-bug-squash","category-networking","tag-android","tag-authentication","tag-interview-prep","tag-kotlin","tag-networking","tag-okhttp","tag-technical-interview"],"_links":{"self":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/998","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/comments?post=998"}],"version-history":[{"count":1,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/998\/revisions"}],"predecessor-version":[{"id":999,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/998\/revisions\/999"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/media\/1000"}],"wp:attachment":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/media?parent=998"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/categories?post=998"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/tags?post=998"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}