Idempotency (Deep Workflow)
Most distributed systems deliver work at least once. Idempotency makes duplicate processing safe—critical for payments, inventory, and message consumers.
When to Offer This Workflow
Trigger conditions:
- - Retries on HTTP, queues, or background jobs
- Double charges, duplicate records, or “at-least-once” confusion
- Product asks for “exactly-once” semantics
Initial offer:
Use six stages: (1) identify side effects, (2) choose keys, (3) storage & scope, (4) API patterns, (5) worker patterns, (6) testing). Confirm storage (Redis, SQL) and retention window.
Stage 1: Identify Side Effects
Goal: Classify operations: reads vs creates vs monetary transfers vs state transitions.
Exit condition: List of mutations that must be idempotent under retries.
Stage 2: Choose Keys
Goal: Client-supplied Idempotency-Key header (Stripe-style) vs deterministic hash of normalized payload—trade UX vs collision risk.
Stage 3: Storage & Scope
Goal: Store key → outcome or result reference with TTL covering retry window; scope keys per tenant/user when needed.
Stage 4: API Patterns
Goal: Same key + same body → same outcome; reject or conflict if same key with different body.
Stage 5: Worker Patterns
Goal: Natural unique constraints in DB; dedupe table keyed by event_id or business idempotency key for consumers.
Stage 6: Testing
Goal: Chaos or integration tests that deliver duplicate messages; property tests for key behavior.
Final Review Checklist
- - [ ] Mutating paths classified
- [ ] Key strategy and scope documented
- [ ] Storage, TTL, conflict rules defined
- [ ] HTTP and async consumers aligned
- [ ] Duplicate delivery tests
Tips for Effective Guidance
- - True exactly-once end-to-end is rare—design for at-least-once + idempotent effects.
- Pair with message-queues and rest-best-practices for HTTP idempotency keys.
Handling Deviations
- - Financial flows: require stronger audit and longer key retention.
幂等性(深度工作流)
大多数分布式系统至少一次交付工作。幂等性使重复处理变得安全——这对支付、库存和消息消费者至关重要。
何时提供此工作流
触发条件:
- - HTTP、队列或后台任务的重试
- 重复扣费、重复记录或至少一次的混淆
- 产品要求恰好一次语义
初始方案:
使用六个阶段:(1) 识别副作用,(2) 选择键,(3) 存储与范围,(4) API模式,(5) 工作器模式,(6) 测试。确认存储(Redis、SQL)和保留窗口。
阶段1:识别副作用
目标: 对操作进行分类:读取 vs 创建 vs 资金转账 vs 状态转换。
退出条件: 列出在重试时必须保持幂等性的变更操作。
阶段2:选择键
目标: 客户端提供的Idempotency-Key头(Stripe风格)vs 规范化负载的确定性哈希——权衡用户体验与冲突风险。
阶段3:存储与范围
目标: 存储键→结果或结果引用,TTL覆盖重试窗口;必要时按租户/用户限定键范围。
阶段4:API模式
目标: 相同键+相同请求体→相同结果;相同键但不同请求体则拒绝或冲突。
阶段5:工作器模式
目标: 数据库中的自然唯一约束;以event_id或业务幂等键为键的去重表供消费者使用。
阶段6:测试
目标: 混沌测试或集成测试,发送重复消息;针对键行为的属性测试。
最终审查清单
- - [ ] 变更路径已分类
- [ ] 键策略和范围已记录
- [ ] 存储、TTL、冲突规则已定义
- [ ] HTTP和异步消费者已对齐
- [ ] 重复交付测试已完成
有效指导技巧
- - 真正的端到端恰好一次很罕见——设计为至少一次+幂等效果。
- 配合消息队列和REST最佳实践实现HTTP幂等键。
处理偏差