---

title: Fetch Keepalive请求治理(大小/速率/终止)最佳实践

keywords:

  • fetch keepalive
  • 大小限制
  • 速率限制
  • 终止治理

description: 通过对fetch keepalive请求设置大小与速率限制,并在异常情况下终止与退避,降低后台上报与卸载阶段的资源风险。

categories:

  • 文章资讯
  • 编程技术

---

背景与价值

keepalive适用于卸载阶段上报,但过度使用会导致资源消耗与网络压力。统一限制与终止治理可提升稳定性。

统一规范

  • 大小:单请求体≤64KB。
  • 速率:每分钟≤60次。
  • 终止:异常时终止并退避。

核心实现

限制与终止

function withinSize(body: Blob | string | ArrayBuffer, max = 64 * 1024): boolean {
  if (typeof body === 'string') return new TextEncoder().encode(body).length <= max
  if (body instanceof Blob) return body.size <= max
  if (body instanceof ArrayBuffer) return body.byteLength <= max
  return false
}

class Rate { tokens = 0; cap = 60; last = Date.now(); refill(rpm = 60) { const now = Date.now(); const add = ((now - this.last) / 60000) * rpm; this.tokens = Math.min(this.cap, this.tokens + add); this.last = now } take(n = 1): boolean { this.refill(); if (this.tokens >= n) { this.tokens -= n; return true } return false } }

async function sendKeepalive(url: string, body: any, rate: Rate): Promise<boolean> {
  if (!withinSize(body)) return false
  if (!rate.take()) return false
  try {
    const r = await fetch(url, { method: 'POST', body, keepalive: true })
    return r.ok
  } catch { return false }
}

落地建议

  • 对keepalive上报设置大小与速率限制,异常时终止与退避,避免卸载阶段网络压力。

验证清单

  • 请求体是否≤64KB;速率是否在每分钟限制;异常是否终止并退避。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部