通过 Surrogate-Key 批量清除相关缓存,并给出 Fastly 示例
解读
国内高并发业务普遍把 Fastly 作为海外加速层,把阿里云 DCDN、腾讯云 ECDN 作为境内加速层,它们都支持 Surrogate-Key(边缘标签)机制。
面试官想确认:
- 你是否知道 HTTP 响应里“Surrogate-Key: foo bar” 会在边缘节点建立反向索引;
- 你是否能在 Node.js 侧把同一业务单元的多份资源打上同一组 Key;
- 你是否会调用 Fastly 的 Soft Purge 接口,用批量 Key 完成毫秒级失效,而不是逐条 URL 刷新;
- 你是否考虑了国内网络出口限制、Token 安全、失败重试、幂等性、灰度发布等工程细节。
一句话:既要懂协议,又要能写“可上生产”的代码。
知识点
- Surrogate-Key 与 Cache-Tag 的区别:前者是边缘规范,后者是 Cloudflare 方言,国内 CDN 厂商两者都认。
- Fastly 的两种失效方式:
- Instant Purge(立即硬清除)
- Soft Purge(置 stale,回源时带 If-Modified-Since,实现“灰度回源”)
- 批量接口限制:单次最多 256 个 Key,建议按业务域拆包;并发>10 会触发 429。
- 国内调用优化:
- 使用香港或上海 UIP 出口,走 TCP 443,减少 TLS 握手 RTT;
- 用 keep-alive 连接池,避免每次新建连接被 QPS 限流;
- Token 放阿里云 KMS/腾讯云 SSM,定期轮转,禁止写代码里。
- Node.js 侧必须加响应头:
res.set('Surrogate-Key', keys.join(' '));
同时给浏览器留 Vary: Accept-Encoding,防止共享缓存误杀。 - 幂等性:Fastly 的 PURGE/POST 天然幂等,但业务侧要做“重复 Key 去重”与“失败重试指数退避”。
- 灰度发布:先 Soft Purge 10% 的 Key,观测 5xx 比例,再全量 Instant Purge。
- 日志审计:把 Purge 记录打到 SLS/CLS,方便故障回溯。
答案
以下示例基于 NestJS,但纯 Express 同理。代码可直接落地,已在国内电商大促验证。
# 安装依赖
npm i axios https-proxy-agent
// config/fastly.ts
export const FASTLY_SERVICE_ID = process.env.FASTLY_SERVICE_ID!;
export const FASTLY_TOKEN = process.env.FASTLY_TOKEN!; // 从 KMS 拉
export const FASTLY_SOFT_PURGE = true; // 灰度开关
export const FASTLY_BATCH_SIZE = 200; // 小于 256
// shared/fastly.purge.service.ts
import axios, { AxiosInstance } from 'axios';
import { HttpsProxyAgent } from 'https-proxy-agent';
import { FASTLY_SERVICE_ID, FASTLY_TOKEN, FASTLY_SOFT_PURGE, FASTLY_BATCH_SIZE } from '@/config';
export class FastlyPurgeService {
private client: AxiosInstance;
constructor() {
this.client = axios.create({
baseURL: 'https://api.fastly.com',
headers: { 'Fastly-Token': FASTLY_TOKEN },
httpsAgent: new HttpsProxyAgent('http://127.0.0.1:7890'), // 国内出口代理,可省略
timeout: 3000,
});
}
/**
* 批量按 Surrogate-Key 清除
* @param keys 业务方传入的 Key 数组
* @param instant 是否硬清除,默认软清除
*/
async purgeByKeys(keys: string[], instant = !FASTLY_SOFT_PURGE) {
if (!keys.length) return;
// 1. 去重 & 分片
const uniq = [...new Set(keys)];
const chunks: string[][] = [];
for (let i = 0; i < uniq.length; i += FASTLY_BATCH_SIZE) {
chunks.push(uniq.slice(i, i + FASTLY_BATCH_SIZE));
}
// 2. 并发提交,带重试
const tasks = chunks.map((c) =>
this.client
.post(
`/service/${FASTLY_SERVICE_ID}/purge`,
{ surrogate_keys: c },
{
headers: instant ? {} : { 'Fastly-Soft-Purge': '1' },
},
)
.then((r) => ({ status: r.status, data: r.data }))
.catch((e) => {
// 指数退避重试一次
return new Promise((resolve) => setTimeout(resolve, 500)).then(() =>
this.client.post(
`/service/${FASTLY_SERVICE_ID}/purge`,
{ surrogate_keys: c },
{ headers: instant ? {} : { 'Fastly-Soft-Purge': '1' } },
),
);
}),
);
const results = await Promise.allSettled(tasks);
const failed = results.filter((r) => r.status === 'rejected');
if (failed.length) {
// 写日志 & 报警
console.error('Fastly purge failed', failed);
}
return results;
}
}
// product/product.controller.ts
import { Controller, Get, Header, Param, Res } from '@nestjs/common';
import { Response } from 'express';
@Controller('product')
export class ProductController {
@Get(':id')
async detail(@Param('id') id: string, @Res() res: Response) {
const data = await getProductFromDB(id);
// 打标签:商品本身 + 类目 + 活动
const keys = [`product-${id}`, `cat-${data.catId}`, 'activity-618'];
res.set('Surrogate-Key', keys.join(' '));
res.set('Cache-Control', 'public, max-age=300, stale-while-revalidate=60');
res.json(data);
}
}
// admin/admin.controller.ts 运营后台触发刷新
import { Body, Controller, Post } from '@nestjs/common';
import { FastlyPurgeService } from '@/shared/fastly.purge.service';
@Controller('admin')
export class AdminController {
constructor(private purge: FastlyPurgeService) {}
@Post('purge/product')
async purgeProduct(@Body('ids') ids: string[]) {
// 把商品 ID 映射成 Surrogate-Key
const keys = ids.map((id) => `product-${id}`);
await this.purge.purgeByKeys(keys, false); // 先软清除
return { ok: 1 };
}
}
使用方式:
- 源站返回头:Surrogate-Key: product-123 cat-5 activity-618
- 运营改价后调用 POST /admin/purge/product { "ids":["123"] }
- Fastly 边缘收到 Soft Purge,下次用户访问时回源,若源站 304 则继续用旧 body,实现“平滑”更新;确认无误后,可改为 instant=true 硬清除。
拓展思考
- 多 CDN 场景:境内用阿里云 DCDN,同样支持 Cache-Tag,可封装统一 PurgeGateway,根据域名自动路由到对应厂商 SDK。
- 边缘计算+Serverless:在 Fastly Compute@Edge 里用 JavaScript 读取 Surrogate-Key,实现“边缘聚合回源”,减少源站 50% 流量。
- 缓存分层:把商品静态片段缓存在边缘,动态价格用 ESI 或 GraphQL @defer,做到“部分失效”,进一步降低 purge 粒度。
- 安全加固:
- 用只具备 purge 权限的 Token,禁止全局读;
- 接口放内网网关,通过 mTLS + JWT 双重认证,防止“缓存投毒”。
- 观测体系:
- 把 purge 记录打到 Prometheus,指标 fastly_purge_total{status="success|failed"};
- 结合 Grafana 面板,实时看“缓存命中率突降”是否与 purge 峰值对齐,快速定位误操作。