principle-make-operations-idempotent

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Make Operations Idempotent

让操作具备幂等性

Design operations so they converge to the correct state regardless of how many times they run or where they start from. Every state-mutating operation should answer: "What happens if this runs twice? What happens if the previous run crashed halfway?"
Why: Commands, lifecycle operations, and processing loops run where crashes, restarts, and retries are normal. If partial state changes the next run's outcome, every restart becomes a debugging session.
The pattern:
  • Convergent startup: scan for existing state, clean stale artifacts, adopt live sessions
  • Content-based cleanup: compare by content equivalence, not creation order
  • Self-healing locks: use PID-based stale lock detection
  • Idempotent scheduling: failed work respawns cleanly, fresh input regenerated after each cycle
The test:
  1. What happens if this runs twice in a row?
  2. What happens if the previous run crashed at every possible point?
  3. Does re-execution converge to the same end state?
If any answer is "it depends on what state was left behind," the operation needs a reconciliation step.
设计操作时,要确保无论运行多少次或从哪个状态开始,最终都能收敛到正确状态。每个会改变状态的操作都应该回答这些问题:“如果这个操作运行两次会发生什么?如果上一次运行中途崩溃了会发生什么?”
原因: 命令、生命周期操作和处理循环通常运行在容易发生崩溃、重启和重试的环境中。如果部分状态变更会影响下一次运行的结果,那么每次重启都会变成一次调试过程。
模式:
  • 收敛式启动:扫描现有状态,清理过期工件,接管活跃会话
  • 基于内容的清理:通过内容等价性进行比较,而非创建顺序
  • 自修复锁:使用基于PID的过期锁检测
  • 幂等调度:失败的任务可以干净地重新生成,每个周期后重新生成新的输入
测试方法:
  1. 连续运行两次会发生什么?
  2. 上一次运行在每个可能的节点崩溃会发生什么?
  3. 重新执行是否会收敛到相同的终端状态?
如果任何一个问题的答案是“这取决于遗留的状态”,那么该操作需要一个协调步骤。