← 中文资源

简体中文版本

构建幂等键存储

构建幂等键存储:完整覆盖 request deduplication,含 Key store、Result cache 与测试的端到端实现。

阅读英文原文

项目概述

本项目实现一个面向 request deduplication 的完整系统,核心要解决的问题是 remembering the result of a request keyed by an idempotency key so a retry returns the same response。整体由 Key store、Result cache、In-flight tracker、TTL evictor、Conflict responder 五个模块组成,每个模块单一职责、可独立测试,最后通过集成测试验证端到端正确性。设计上把 a key collision where two unrelated requests share a key and the second receives the first request result 作为第一类需求先行处理,而非事后再补。

架构与关键决策

数据模型为 a store mapping idempotency keys to either an in-flight marker or a cached response, expiring after a configurable window。Key store 定义其余阶段共同依赖的数据形状并在边界处校验输入;Result cache 承载 request deduplication 的正确性逻辑;In-flight tracker 专门处理 a key collision where two unrelated requests share a key and the second receives the first request result,在失败路径上给出明确的拒绝、重试或降级策略;TTL evictor 提供可观测性,每次操作输出带关联 id 的结构化事件;Conflict responder 在过载时按既定方式降级,避免过载演变为数据损坏。配置与代码分离,使风险变更可经 diff 审阅。

实施与测试

按五个阶段依次实现 Key store、Result cache、In-flight tracker、TTL evictor、Conflict responder,每阶段配套聚焦单测。集成测试组合各模块并驱动真实 request deduplication 场景:先验证正常路径,再刻意触发 a key collision where two unrelated requests share a key and the second receives the first request result 并断言系统降级而非损坏。所有依赖均在进程内或被桩替换,用例在 CI 中确定可复现。

限制与后续

  • 单区域设计,多区域复制超出范围。
  • Key store 默认进程内,未水平共享。
  • 无鉴权层,假定部署在强制身份的边缘之后。

代码示例

# setup for idempotency-key-store
pnpm init
pnpm add redis fastify
pnpm add -D typescript tsx vitest
idempotency_key_store/
├── src/index.ts
├── src/key-store.ts
├── src/result-cache.ts
├── tests/idempotency_key_store.test.ts
└── package.json
// Key store: request deduplication core
export function keystore(input: KeystoreInput): KeystoreResult {
  // Build the key store that anchors request deduplication and defines the core data shape.
  return processKeystore(input);
}
// Result cache — handles request deduplication Add the result cache so
export class Resultcache {
  constructor(private opts: ResultcacheOptions) {}
  async run(ctx: Context): Promise<ResultcacheOutput> {
    return this.execute(ctx);
  }
}
// In-flight tracker: request deduplication stage
export const inflighttracker = (next: Next) => async (req: Request) => {
  const out = await transform(req);
  return next(out);
};
// TTL evictor for request deduplication
export async function ttlevictor(stream: AsyncIterable<Chunk>): Promise<Aggregate> {
  let acc = init();
  for await (const c of stream) acc = merge(acc, c);
  return acc;
}
// Conflict responder: request deduplication finalization
export function conflictresponder(state: State): Result {
  validate(state);
  return finalize(state);
}
# run the request deduplication test suite
pnpm vitest run