如何限制重试次数并做指数退避?
解读
在 Redux 业务里,异步副作用(接口请求、长连接、文件上传等)失败后的重试策略,是面试官最爱深挖的“工程化”考点。
国内一线团队普遍要求:
- 重试次数可配置,默认不超过 3 次;
- 退避间隔按指数增长,防止瞬间打挂后端;
- 重试逻辑对组件透明,不污染 UI 层;
- 失败原因、剩余次数、下次触发时间都要进 Store,方便埋点与调试。
面试官想听的不是“用 axios 的 retry 插件”,而是如何在 Redux 数据流里自己实现一套可预测、可回溯、可测试的重试机制。
知识点
- 纯函数 Reducer:重试计数、退避时间必须算出新 State,禁止直接 mutate。
- 中间件机制:redux-thunk、redux-saga、redux-observable 均可,但国内以 redux-saga 为主流,因其 Generator 语法对“阻塞-重试”语义表达最直观。
- 指数退避公式:delay = baseDelay * 2^attempt * (1 + jitter),jitter 取 0~0.1 随机值可打散惊群。
- Race 与 Cancel:saga 里用 race(task, delay) 实现超时,重试前需 cancel 上一次未完成的任务,防止并发写 State。
- 错误分类:可重试(5xx、网络超时)vs 不可重试(4xx 鉴权),只在可重试时才递增 attempt。
- Store 设计:
slice 结构示例
{
status: 'idle' | 'loading' | 'success' | 'failure',
data: any,
error: any,
attempt: 0..maxAttempt,
nextRetryAt: timestamp | null
} - 埋点要求:国内 APP 普遍接入阿里 SLS、腾讯灯塔,每次重试都要打一条日志带上 attempt 与退避时长,方便后端定位“用户一直刷不到数据”的元凶。
答案
下面给出 redux-saga + TypeScript 的完整实现,可直接写进简历项目经验。
- 定义 Store 片段
interface RetryState<T> {
data: T | null;
status: 'idle' | 'loading' | 'success' | 'failure';
error: any;
attempt: number;
nextRetryAt: number | null;
}
const initialState: RetryState<any> = {
data: null,
status: 'idle',
error: null,
attempt: 0,
nextRetryAt: null,
};
- Action 类型
const FETCH_START = 'retry/FETCH_START';
const FETCH_SUCCESS = 'retry/FETCH_SUCCESS';
const FETCH_FAILURE = 'retry/FETCH_FAILURE';
const RETRY_SCHEDULE = 'retry/RETRY_SCHEDULE';
- Reducer(纯函数,不可变)
export default function retryReducer(state = initialState, action: any) {
switch (action.type) {
case FETCH_START:
return { ...state, status: 'loading', error: null };
case FETCH_SUCCESS:
return { ...state, status: 'success', data: action.payload, attempt: 0, nextRetryAt: null };
case FETCH_FAILURE:
const { attempt, maxAttempt, baseDelay } = action.meta;
const nextAttempt = attempt + 1;
if (nextAttempt >= maxAttempt) {
return { ...state, status: 'failure', error: action.payload, attempt: nextAttempt, nextRetryAt: null };
}
const jitter = Math.random() * 0.1;
const delay = Math.floor(baseDelay * Math.pow(2, nextAttempt) * (1 + jitter));
return { ...state, status: 'failure', error: action.payload, attempt: nextAttempt, nextRetryAt: Date.now() + delay };
default:
return state;
}
}
- Saga(核心逻辑)
const MAX_ATTEMPT = 3;
const BASE_DELAY = 500;
function* fetchWorker() {
let attempt = 0;
while (attempt < MAX_ATTEMPT) {
try {
yield put({ type: FETCH_START });
const data: any = yield call(apiGet); // 你的真实请求
yield put({ type: FETCH_SUCCESS, payload: data });
return; // 成功就结束
} catch (e) {
const err = e as Error;
if (err.message.includes('401')) { // 不可重试错误
yield put({ type: FETCH_FAILURE, payload: err, meta: { attempt, maxAttempt: 0, baseDelay: 0 } });
return;
}
yield put({ type: FETCH_FAILURE, payload: err, meta: { attempt, maxAttempt: MAX_ATTEMPT, baseDelay: BASE_DELAY } });
const { nextRetryAt } = yield select((s) => s.retry);
if (nextRetryAt) {
yield delay(nextRetryAt - Date.now()); // 指数退避等待
}
attempt++;
}
}
}
export function* retryRootSaga() {
yield takeLatest('RETRY_FETCH_TRIGGER', fetchWorker);
}
- 组件层无感知
const { status, data, error, attempt } = useSelector((s) => s.retry);
UI 只根据 status 渲染,重试逻辑完全在 saga 闭环内。
拓展思考
- 动态 maxAttempt:把 maxAttempt 放到 action.meta 里,由后端响应头 X-Retry-Limit 下发,实现“降级开关”。
- 退避上限:指数增长容易爆掉,加硬顶 30 s,超过后按 30 s 线性重试。
- 离线场景:结合 navigator.onLine,网络断开时直接暂停 saga,恢复 online 后重新调度。
- 批量重试:列表页多卡片同时失败,可 合并相同 key 的请求,只发一次网络调用,节省 CDN 流量。
- 测试用例:使用 redux-saga-test-plan,断言 put 顺序与 delay 时长,国内 CI 普遍要求单测覆盖率 > 90%。
- SSR 场景:Node 层无 setTimeout,用 Promise + clock 模拟 delay,防止脱水时状态不一致。