← 中文资源

简体中文版本

Web 应用缓存策略

为每一层选择合适的缓存,用标签和版本失效,并通过 stale-while-revalidate 在不引发惊群的情况下提供新鲜数据。

阅读英文原文

引言

缓存是延迟和成本的主要杠杆,也是不一致的主要来源。策略必须回答:缓存什么、在哪一层、存多久、何时失效、失效失败怎么办。

分层与取舍

浏览器、CDN、应用内存和数据库查询缓存各有边界。HTTP 缓存适合静态资源和可公开的响应;应用缓存适合计算昂贵的数据。越靠近客户端,失效越难,因此要按数据变化频率和一致性要求分层。

HTTP 缓存

用 Cache-Control 的 max-age、s-maxage、stale-while-revalidate 和 stale-if-error 表达意图。带用户信息的响应应使用 private 或 no-store。用内容哈希或版本化 URL 处理静态资源。

应用缓存与失效

内存缓存必须有大小上限和 TTL,避免无界增长。失效优先使用显式删除或版本化 key,而不是依赖 TTL 猜测。对关联数据使用标签,一次失效一组 key。缓存更新失败要记录并告警。

惊群与一致性

热 key 过期时用 single-flight 合并回源请求,或用分布式锁。stale-while-revalidate 让一个请求刷新、其他请求继续拿旧值。接受最终一致时要在产品上明确可见性延迟。

结论

缓存策略是业务一致性的一部分。先定义可接受的新鲜度,再选择层和失效机制,最后用指标验证命中率和回源压力。

代码示例

// A hashed asset: cache forever, it is addressed by content hash.
res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
res.setHeader("Vary", "Accept-Encoding"); // cache gzip and brotli separately

// A user-specific API response: cache briefly, only in the browser.
res.setHeader("Cache-Control", "private, max-age=10");
res.setHeader("Vary", "Authorization"); // do not share across users
class LRUCache<K, V> {
  private map = new Map<K, V>();
  constructor(private readonly max: number) {}
  get(key: K): V | undefined {
    const value = this.map.get(key);
    if (value !== undefined) { this.map.delete(key); this.map.set(key, value); } // move to most-recent
    return value;
  }
  set(key: K, value: V) {
    if (this.map.has(key)) this.map.delete(key);
    this.map.set(key, value);
    if (this.map.size > this.max) this.map.delete(this.map.keys().next().value!); // evict least-recent
  }
}
// Tag-based cache: store with tags, invalidate by tag.
const cache = new Map<string, { value: unknown; tags: Set<string> }>();
const tagIndex = new Map<string, Set<string>>(); // tag -> keys

function set(key: string, value: unknown, tags: string[]) {
  cache.set(key, { value, tags: new Set(tags) });
  for (const t of tags) (tagIndex.get(t) ?? tagIndex.set(t, new Set()).get(t)!).add(key);
}
function invalidate(tag: string) {
  for (const key of tagIndex.get(tag) ?? []) cache.delete(key);
  tagIndex.delete(tag);
}

// Cache a product, tagged so invalidating "product:42" or "products" drops it.
set("product:42", product, ["product:42", "products"]);
// When the product changes:
invalidate("product:42"); // drops the specific entry
invalidate("products");   // drops every product-list entry
async function swr<T>(key: string, maxAgeMs: number, staleMs: number, fetch: () => Promise<T>): Promise<T> {
  const entry = store.get(key);
  const now = Date.now();
  if (entry) {
    if (now - entry.fetchedAt < maxAgeMs) return entry.value; // fresh
    if (now - entry.fetchedAt < maxAgeMs + staleMs) {
      // stale but usable: serve now, refresh in the background.
      if (!entry.refreshing) { entry.refreshing = true; fetch().then(v => { store.set(key, { value: v, fetchedAt: Date.now(), refreshing: false }); }).catch(() => { entry.refreshing = false; }); }
      return entry.value;
    }
  }
  // no usable cache: fetch and serve.
  const value = await fetch();
  store.set(key, { value, fetchedAt: now, refreshing: false });
  return value;
}
const inflight = new Map<string, Promise<unknown>>();

async function singleFlight<T>(key: string, fetcher: () => Promise<T>): Promise<T> {
  if (cache.has(key)) return cache.get(key) as T;
  if (inflight.has(key)) return inflight.get(key) as Promise<T>;
  const promise = fetcher().then((value) => { cache.set(key, value); inflight.delete(key); return value; })
                            .catch((err) => { inflight.delete(key); throw err; });
  inflight.set(key, promise);
  return promise;
}
// Probabilistic early refresh: refresh in the background if the entry is "near" expiry.
function shouldRefresh(ttl: number, fetchDuration: number, beta = 1): boolean {
  // The probability of refresh increases as ttl decreases relative to fetchDuration.
  return -Math.log(Math.random()) * beta * fetchDuration > ttl;
}