Skip to content
tezvyn:

Explain Dio interceptors and automatic token refresh

Source: pub.devHardHow cards are made

Summary

Stateful middleware and async orchestration.

Key points

Define interceptors as hooks; queue concurrent 401s during refresh; retry with Bearer header via token manager.

Watch out for

Synchronous refresh or refresh storms.

What's really being asked

This question evaluates whether you understand HTTP middleware as stateful async machinery rather than simple decorators. The interviewer wants to see that you grasp request queuing, token lifecycle management, and error recovery in a Dart concurrency context. Specifically, they are looking for knowledge of Dio's interceptor API and how to prevent race conditions when multiple simultaneous requests hit a 401.

The full answer

First, define an interceptor as middleware implementing onRequest, onResponse, and onError hooks that mutate or short-circuit requests and responses. Second, explain the refresh flow in onError: detect a 401 or 403 via a shouldRefresh callback, lock the request queue so subsequent requests wait, then invoke an async onRefresh callback that posts to the refresh endpoint and updates a singleton TokenManager with new access and refresh tokens. Third, describe retrying the original failed request with the new token injected into the Authorization header via a TokenHeaderCallback, then unlocking the queue so queued requests automatically pick up the new token. Fourth, mention handling refresh failure with an onRefreshFailedCallback to clear state and redirect to login.

The mistakes people make

A naive answer proposes checking token expiry synchronously in onRequest and refreshing there, which blocks the request thread and ignores network latency. Another red flag is ignoring the thundering herd problem: without queue locking, ten simultaneous 401s would spawn ten separate refresh calls. Some candidates also forget to update the refresh token itself, assuming only the access token rotates, or they omit handling the case where the refresh endpoint also returns 401, leading to an infinite loop.

What usually comes next

The interviewer might ask how you would test this interceptor in unit tests without making real network calls. They could also probe how to handle partial failures when some queued requests have different header requirements, or how to add logging interceptors to the retry Dio instance without creating an infinite loop. Another follow-up is asking how to implement this without a singleton, perhaps via dependency injection.

A concrete example

Suppose a user opens a dashboard that fires three parallel API calls. All three return 401 because the access token expired. A DioRefreshInterceptor intercepts the first 401, triggers shouldRefresh, and locks the request queue. It calls onRefresh, which POSTs to /refresh with the stored refresh token, receives a new access token and refresh token, and calls tokenManager.setToken. The interceptor then retries the first request with the new Bearer header, unlocks the queue, and the remaining two queued requests automatically use the updated token via the authHeader callback. If the refresh fails, onRefreshFailedCallback clears the tokens and navigates to the login screen.

Interview question

When three parallel Dio requests return 401 due to an expired access token, how should an interceptor handle refresh and retries?

  • a.Refresh the token once, retry only the first request, and drop the remaining queued requests
  • b.Check token expiry synchronously in onRequest and refresh the token before any request is sent
  • c.Let each 401 independently trigger its own refresh call and race to update the shared token manager
  • d.Lock the queue, perform one async refresh, then let all queued requests resume with the new tokenCorrect
Why?

Locking the queue ensures only one async refresh runs and all queued requests automatically retry with the updated token. Letting each 401 trigger its own refresh causes a thundering herd, while synchronous onRequest checks block the thread and ignore network latency.

Just read this? Test yourself on what you have been reading.

Read the original → pub.dev

You just looked this up. Could you explain it out loud?

That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on flutter — each one lists the topics its interview covers.

See open roles