# 幂等性

**幂等性**（Idempotency）是指对某一操作执行多次与执行一次产生相同结果的特性。该术语起源于数学与代数，其中当 f(x, …, x) = x 时，运算 f 是幂等的；此后被计算机领域采用，用来描述 HTTP 请求、数据库写入和配置变更等可以安全重复的操作。在一个充满重试消息的世界里，幂等性是构建可靠系统的必备属性。<sup>[1](https://dl.acm.org/doi/10.1145/2181796.2187821)</sup>

| 关键事实 | 详情 |
|---|---|
| 核心定义 | 多次执行某一操作与恰好执行一次的效果相同<sup>[1](https://dl.acm.org/doi/10.1145/2181796.2187821)</sup> |
| 代数形式 | 定义域 D 上的运算 f 是幂等的，当且仅当对 D 中所有 x 满足 f(x, …, x) = x<sup>[2](https://www.sciencedirect.com/topics/computer-science/idempotent-operation)</sup> |
| 幂等的 HTTP 方法 | OPTIONS、HEAD、GET、PUT、DELETE 和 TRACE；POST 和 PATCH 不是<sup>[3](https://datatracker.ietf.org/doc/html/draft-ietf-httpapi-idempotency-key-header)</sup> |
| 标准化 | IETF 的 Idempotency-Key 请求头在一份互联网草案中有所描述<sup>[4](https://datatracker.ietf.org/doc/draft-ietf-httpapi-idempotency-key-header/history/)</sup> |
| 典型键有效期 | Stripe（v1）和 Modern Treasury 为 24 小时；建议范围为 24 至 72 小时<sup>[5](https://docs.stripe.com/api/idempotent_requests)</sup><sup> • </sup><sup>[6](https://www.moderntreasury.com/journal/why-idempotency-matters-in-payments)</sup><sup> • </sup><sup>[7](https://docs.precepts.dev/integration/guidelines/idempotency/)</sup> |
| 并发重复请求 | 原始请求仍在处理时的重试应收到 HTTP 409 Conflict，而非第二次执行<sup>[3](https://datatracker.ietf.org/doc/html/draft-ietf-httpapi-idempotency-key-header)</sup> |
| 投递语义 | 在不可靠网络上实现精确一次投递通常不切实际；至少一次投递加上幂等处理可以实现有效一次处理<sup>[8](https://vercel.com/i/what-is-idempotency)</sup> |

## 定义与起源

idempotent 一词源自拉丁语 *idem* 和 *potent*，合起来意为“相同的力量”。它进入数学领域，用于描述可以多次发生但只改变一次结果的运算。<sup>[6](https://www.moderntreasury.com/journal/why-idempotency-matters-in-payments)</sup> 云原生计算基金会（Cloud Native Computing Foundation）的术语表直接给出了计算领域的含义：如果参数相同，多次执行幂等操作不会产生额外效果。<sup>[9](https://glossary.cncf.io/idempotence/)</sup>

数学定义与计算定义在“相同”的判定标准上存在分歧。在代数中，比较的是函数的值。在计算中，尤其是在 HTTP 中，比较的是系统的状态，而且只约束*预期*效果。HTTP 规范仅从客户端对服务器的预期效果来定义幂等性；服务器仍然可以记录每次请求的接收时间，不同调用之间的响应也可能不同。<sup>[10](https://developer.mozilla.org/en-US/docs/Glossary/Idempotent)</sup> 2019 年 CIDR 的一篇论文直白地给出了实用版本：幂等意味着多做一次也无妨，因此如果至少发生一次，其行为与恰好发生一次相同——同时指出幂等性是一个忽略副作用的主观概念。<sup>[11](https://vldb.org/cidrdb/papers/2019/cidr2019_161.pdf)</sup>

## 数学与代数中的幂等性

在代数中，定义域 D 上的运算 f 是幂等的，当且仅当它对 D 中所有 x 满足 f(x, …, x) = x。<sup>[2](https://www.sciencedirect.com/topics/computer-science/idempotent-operation)</sup> 在布尔域上，一个分类结果表明，非投影的二元幂等运算只有两种：两种半格运算 ∧（与）和 ∨（或）。这一事实被用于约束语言的复杂性分类，包括 Schaefer 二分定理。<sup>[2](https://www.sciencedirect.com/topics/computer-science/idempotent-operation)</sup>

## 计算与 HTTP 中的幂等性

根据 RFC 9110——IETF 对 HTTP 语义的规范性规范——OPTIONS、HEAD、GET、PUT 和 DELETE 方法是幂等的，而 POST 和 PATCH 不是。<sup>[3](https://datatracker.ietf.org/doc/html/draft-ietf-httpapi-idempotency-key-header)</sup> 这一区分取决于重复操作对服务器状态的影响。发送两次相同的 POST 请求，例如“提交付款”，通常会产生两条独立记录并向客户收取两笔费用；重复一个相对变更，例如“余额加 5”，每次都会得到不同的最终值。<sup>[12](https://cloud.google.com/discover/idempotency)</sup> 相比之下，PUT 表示目标资源应被创建或完全替换为请求负载，因此重复执行会收敛到同一状态。<sup>[13](https://stripe.com/blog/idempotency)</sup>

**响应可以不同。** 幂等性约束的是服务器状态，而非响应。DELETE 仍然是幂等的，即使第一次调用可能返回 204 而后续调用返回 404，因为每次调用后的服务器状态是相同的。<sup>[14](https://www.sanity.io/glossary/idempotency)</sup> MDN 指出，在实践中由服务器负责确保其路由遵循规范的语义，因为标准只定义了预期效果。<sup>[10](https://developer.mozilla.org/en-US/docs/Glossary/Idempotent)</sup>

幂等性之所以重要，根本原因在于传输的不可靠性。HTTP 运行在 TCP 之上，虽然连接通常保持存活，但无法保证它一直如此，因此任何 HTTP 使用都可能导致同一请求被多次发送；为此，大多数 HTTP 请求被设计为幂等的。<sup>[1](https://dl.acm.org/doi/10.1145/2181796.2187821)</sup> AWS 的指南指出 POST、PUT 和 DELETE 方法以及数据库的插入、更新或删除操作通常需要幂等性，而只读查询通常不需要，除非它们带有副作用。<sup>[15](https://docs.aws.amazon.com/wellarchitected/latest/reliability-pillar/rel_prevent_interaction_failure_idempotent.html)</sup>

## 幂等键与支付 API

“幂等键”（idempotency key）一词源自 Stripe 的 API。<sup>[16](https://www.brandur.org/idempotency-keys)</sup> 该模式的工作方式如下：客户端为操作生成一个唯一标识符，并随正常负载一起发送；服务器将该标识符与请求状态关联；如果客户端发现失败，就用相同的标识符重试，由服务器决定如何处理重复请求。<sup>[13](https://stripe.com/blog/idempotency)</sup> 如果请求在中途失败，使用相同键的重试让服务器能够查找请求状态并从断点继续。<sup>[16](https://www.brandur.org/idempotency-keys)</sup>

Stripe 将此应用于所有变更型 POST 端点。<sup>[13](https://stripe.com/blog/idempotency)</sup> 在 Stripe API v1 中，给定键的第一次请求的状态码和响应体在端点开始执行后即被保存，使用相同键的重试返回已保存的响应，包括 500 错误；在 API v2 中，重试不会重复已成功的操作，Stripe 返回更新后的响应。<sup>[5](https://docs.stripe.com/api/idempotent_requests)</sup> 键最长可达 255 个字符，Stripe 建议使用 V4 UUID 或其他高熵随机字符串，并建议不要使用电子邮件地址等敏感数据。<sup>[5](https://docs.stripe.com/api/idempotent_requests)</sup> Modern Treasury 将键与请求及其结果一起记录 24 小时，在该时间窗口内对重复调用重放原始响应，而不重新执行支付。<sup>[6](https://www.moderntreasury.com/journal/why-idempotency-matters-in-payments)</sup> Shopify 对 GraphQL 操作采用相同策略，无论重试多少次，操作只执行一次。<sup>[17](https://shopify.engineering/building-resilient-graphql-apis-using-idempotency)</sup>

该模式目前正在被标准化。IETF 草案 *draft-ietf-httpapi-idempotency-key-header* 定义了 Idempotency-Key 请求头，通过让服务器识别同一请求的重试，使 POST 或 PATCH 等非幂等方法具备容错能力。<sup>[3](https://datatracker.ietf.org/doc/html/draft-ietf-httpapi-idempotency-key-header)</sup> 该请求头是一个条目结构化头（Item Structured Header，RFC 8941），其值必须为字符串；键必须唯一，且不得与不同的请求负载重复使用，建议使用 UUID（RFC 4122）或类似的随机标识符。<sup>[3](https://datatracker.ietf.org/doc/html/draft-ietf-httpapi-idempotency-key-header)</sup> MDN 记录了该请求头，并指出支持它的服务器应公布其支持情况，包括所需的端点和键的要求，如长度、计算方法和过期时间。<sup>[18](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Idempotency-Key)</sup>

## 分布式系统与消息队列中的幂等性

在事件驱动系统中，无法保证消息被精确一次地投递或处理，因此消费者必须使用幂等令牌配合持久化数据存储来避免重复副作用。<sup>[19](https://aws-samples.github.io/eda-on-aws/concepts/idempotency/)</sup> 键通常是 UUID 或事件负载的确定性哈希；基于负载的生成必须使用确定性算法以保证唯一性。<sup>[19](https://aws-samples.github.io/eda-on-aws/concepts/idempotency/)</sup> AWS 建议 Amazon SQS、MQ、Kinesis Streams 或 MSK 等队列的消费者跟踪收到的每个幂等令牌，并忽略包含重复令牌的消息。<sup>[15](https://docs.aws.amazon.com/wellarchitected/latest/reliability-pillar/rel_prevent_interaction_failure_idempotent.html)</sup>

**精确一次的声明需要仔细解读。** 一些消息代理，包括 [Apache Kafka](https://www.edgepedia.org/zh/apache-kafka) 和 Amazon SQS FIFO 队列，提供精确一次投递语义，但消费者仍可能多次读取同一条消息，因此仍须处理重复处理的问题。<sup>[19](https://aws-samples.github.io/eda-on-aws/concepts/idempotency/)</sup> Kafka 的精确一次保证仅适用于其自身的消息传递：如果 Kafka 对同一条消息多次调用消息处理器，它会检测并丢弃该处理器产生的重复消息，但处理器的数据库事务仍会重复执行，因此处理器本身必须是幂等的。<sup>[20](https://microservices.io/post/microservices/patterns/2020/10/16/idempotent-consumer.html)</sup> Vercel 将跨分布式系统的精确一次投递描述为一种局限性，同时解释说精确一次效果可以通过至少一次投递结合去重或幂等性来模拟。<sup>[8](https://vercel.com/i/what-is-idempotency)</sup>

2013 年 ACM 的一篇论文将这种分工形式化为幂等性（安全性）加上无失败性（进展性），并提出基于单子的语言支持，在无需分布式协调的情况下确保无失败幂等性。<sup>[21](https://dl.acm.org/doi/10.1145/2480359.2429100)</sup>

## 并发、存储与权衡

**竞态。** 使用相同键的两个请求可能同时到达。IETF 草案规定，在原始请求完成之前的重试应收到资源冲突错误，具体为 HTTP 409 并附带问题描述响应体。<sup>[3](https://datatracker.ietf.org/doc/html/draft-ietf-httpapi-idempotency-key-header)</sup> Stripe 的 v1 层采用不同方式：由于结果仅在端点开始执行后才保存，未通过验证或与并发执行的请求冲突的请求不会被保存，可以重试。<sup>[5](https://docs.stripe.com/api/idempotent_requests)</sup> 在存储层，先检查后设置的竞态必须以原子方式消除；Redis 的 SET key value NX EX 86400 命令在键不存在时返回 OK，已存在时返回 nil，在检查和写入之间不留间隙。<sup>[8](https://vercel.com/i/what-is-idempotency)</sup> AWS 建议将每个令牌及其状态（待处理、已完成或失败）存储在持久化存储中，并使用锁、事务或乐观并发控制来维持原子性。<sup>[15](https://docs.aws.amazon.com/wellarchitected/latest/reliability-pillar/rel_prevent_interaction_failure_idempotent.html)</sup>

**存储与有效期。** 一份实现指南建议幂等存储应捕获首次执行的完整响应（状态码、响应头和响应体），跨服务实例共享而非节点本地，并使用 24 至 72 小时之间的 TTL。<sup>[7](https://docs.precepts.dev/integration/guidelines/idempotency/)</sup> Stripe 在 v1 键至少存在 24 小时后自动删除，如果键在清理后被重用则生成新请求；其幂等层将传入参数与原始参数比较，不匹配则报错。<sup>[5](https://docs.stripe.com/api/idempotent_requests)</sup> AWS 建议使用过期时间戳定期清除旧令牌，因为令牌重用的可能性随时间推移而降低。<sup>[15](https://docs.aws.amazon.com/wellarchitected/latest/reliability-pillar/rel_prevent_interaction_failure_idempotent.html)</sup> 平台功能对开销明确定价：Vercel Queues 在原始消息的生命周期内对带键消息去重，默认 TTL 为 24 小时，范围为 60 秒至 7 天，带键发送按 2 倍操作计费。<sup>[8](https://vercel.com/i/what-is-idempotency)</sup>

## 配置与基础设施中的幂等性

基础设施即代码工具依赖幂等性，使得重复运行同一脚本是安全的。当脚本说“创建一个 10GB 的存储桶”时，工具会先检查云的当前状态，幂等性由工具自身管理，而非由开发者编写额外逻辑。<sup>[12](https://cloud.google.com/discover/idempotency)</sup> [HashiCorp](https://www.edgepedia.org/zh/hashicorp) 对比了其两款工具：Terraform 是声明式的，设计上即具备幂等性，比较当前状态与期望状态；而 [Ansible](https://www.edgepedia.org/zh/ansible-software) 是过程式的，期望开发者创建幂等模块；Terraform 是有状态的，基于[不可变基础设施](https://www.edgepedia.org/zh/immutable-infrastructure)原则，而 Ansible 是无状态的，基于可变基础设施原则。<sup>[22](https://developer.hashicorp.com/validated-patterns/terraform/terraform-integrate-ansible-automation-platform)</sup> Ansible 自己的术语表将幂等定义为：在各次执行之间没有其他操作的情况下，重复执行某一操作产生与执行一次相同的结果。<sup>[23](https://docs.ansible.com/projects/ansible/2.9/reference_appendices/glossary.html?highlight=idempotency)</sup>

数据库的“upsert”（更新或插入）可以是幂等的：如果记录存在则更新，不存在则创建，因此重复执行可以收敛到同一状态。<sup>[12](https://cloud.google.com/discover/idempotency)</sup>

更强的特性是收敛：一种持续将系统推向既定目标状态的操作。Terraform 和 [Kubernetes](https://www.edgepedia.org/zh/kubernetes) 采用这种模型，它在构造上就是幂等的。<sup>[14](https://www.sanity.io/glossary/idempotency)</sup> 形式化工作对两者做了区分：当对于任意一对执行顺序和任意状态，重复应用都产生相同的成功结果时，配置规范是收敛的——这一条件比普通幂等性更强，因为它还要求顺序无关性。<sup>[24](http://hummer.io/docs/2016-citac-oopsla.pdf)</sup> 关于配置管理测试的研究将操作 a 在状态 s 上的幂等性形式化为 (a a)(s) = a(s)。<sup>[25](https://repositum.tuwien.at/bitstream/20.500.12708/6733/2/Hanappi%20Oliver%20-%202016%20-%20Testing%20idempotence%20and%20convergence%20of%20automatic...pdf)</sup>

## 与相关概念的比较

幂等性是操作的属性；精确一次投递是传输的属性。幂等性不承诺消息到达多少次，只承诺多余的到达不会造成危害，而在不可靠网络上实现真正的精确一次投递通常不切实际，因此系统采用至少一次投递加幂等处理，称为有效一次处理。<sup>[14](https://www.sanity.io/glossary/idempotency)</sup> 在评估供应商声明时，还有一个区分很重要：精确一次*处理*指的是每条消息只被处理一次的理想状态，而精确一次处理*语义*意味着系统表现得好像每条消息只被处理一次，尽管底层存在重试或重复——一些营销材料模糊了这一区别。<sup>[26](https://livebook.manning.com/book/think-distributed-systems/chapter-4)</sup>

幂等性也不等于纯粹性。一个幂等的 HTTP 请求仍可能有服务器端副作用，例如记录每次请求的接收时间；只有客户端的预期状态效果受到约束。<sup>[10](https://developer.mozilla.org/en-US/docs/Glossary/Idempotent)</sup>

## 用法分歧之处

各参考资料之间在幂等方法列表上存在差异：IETF 草案列出 OPTIONS、HEAD、GET、PUT 和 DELETE，<sup>[3](https://datatracker.ietf.org/doc/html/draft-ietf-httpapi-idempotency-key-header)</sup> 而一些参考资料还列出 TRACE。<sup>[14](https://www.sanity.io/glossary/idempotency)</sup> RFC 9110 将 TRACE 归类为幂等的，因此草案列表中的省略并非 HTTP 语义上的差异。其次，关于使用不同负载重用键时的状态码：IETF 草案规定 HTTP 422，<sup>[3](https://datatracker.ietf.org/doc/html/draft-ietf-httpapi-idempotency-key-header)</sup> 而一份实现指南要求在这种情况下返回 409 Conflict。<sup>[7](https://docs.precepts.dev/integration/guidelines/idempotency/)</sup> 对于符合规范的实现，草案的规定具有更大权重，但实现者应预期已部署的 API 存在差异。

## 近期发展

若干进展已将幂等性从供应商惯例推向标准实践。RFC 9110 现已编纂了 HTTP 方法语义，包括哪些方法是幂等的。<sup>[27](https://www.rfc-editor.org/rfc/rfc9110.html)</sup> IETF HTTPAPI 工作组已在一份互联网草案中开发了 Idempotency-Key 请求头。<sup>[4](https://datatracker.ietf.org/doc/draft-ietf-httpapi-idempotency-key-header/history/)</sup> MDN 现已将该请求头记录为使 POST 和 PATCH 幂等的标准机制。<sup>[18](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Idempotency-Key)</sup> Stripe 的 API v2 改变了重试行为，使重试不会重复已成功的操作并返回更新后的响应，这是对 v1 重放已保存的首次响应的转变。<sup>[5](https://docs.stripe.com/api/idempotent_requests)</sup> 各平台已将带键去重内建于托管基础设施中，如 Vercel Queues。<sup>[8](https://vercel.com/i/what-is-idempotency)</sup>

## References

1. [Idempotence Is Not a Medical Condition, ACM Queue Vol. 10 No. 4](https://dl.acm.org/doi/10.1145/2181796.2187821)
2. [Idempotent Operation, ScienceDirect Topics](https://www.sciencedirect.com/topics/computer-science/idempotent-operation)
3. [draft-ietf-httpapi-idempotency-key-header-07, IETF](https://datatracker.ietf.org/doc/html/draft-ietf-httpapi-idempotency-key-header)
4. [History for draft-ietf-httpapi-idempotency-key-header, IETF Datatracker](https://datatracker.ietf.org/doc/draft-ietf-httpapi-idempotency-key-header/history/)
5. [Idempotent requests, Stripe API Reference](https://docs.stripe.com/api/idempotent_requests)
6. [What is Idempotency and Why It Matters in Payments, Modern Treasury](https://www.moderntreasury.com/journal/why-idempotency-matters-in-payments)
7. [Idempotency Design, Precepts](https://docs.precepts.dev/integration/guidelines/idempotency/)
8. [What is idempotency in APIs, Vercel](https://vercel.com/i/what-is-idempotency)
9. [Idempotence, Cloud Native Glossary (CNCF)](https://glossary.cncf.io/idempotence/)
10. [Idempotent, MDN Glossary](https://developer.mozilla.org/en-US/docs/Glossary/Idempotent)
11. [CIDR 2019 paper on idempotence, VLDB](https://vldb.org/cidrdb/papers/2019/cidr2019_161.pdf)
12. [What is Idempotency? A guide to API reliability, Google Cloud](https://cloud.google.com/discover/idempotency)
13. [Designing robust and predictable APIs with idempotency, Stripe Blog](https://stripe.com/blog/idempotency)
14. [What is idempotency? Definition, HTTP methods, and examples, Sanity](https://www.sanity.io/glossary/idempotency)
15. [Implement idempotent operations, AWS Well-Architected Reliability Pillar](https://docs.aws.amazon.com/wellarchitected/latest/reliability-pillar/rel_prevent_interaction_failure_idempotent.html)
16. [Implementing Stripe-like Idempotency Keys in Postgres, brandur.org](https://www.brandur.org/idempotency-keys)
17. [Building Resilient GraphQL APIs Using Idempotency, Shopify Engineering](https://shopify.engineering/building-resilient-graphql-apis-using-idempotency)
18. [Idempotency-Key header, MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Idempotency-Key)
19. [Idempotency, Event-driven Architecture on AWS](https://aws-samples.github.io/eda-on-aws/concepts/idempotency/)
20. [Handling duplicate messages using the Idempotent consumer pattern, microservices.io](https://microservices.io/post/microservices/patterns/2020/10/16/idempotent-consumer.html)
21. [Fault tolerance via idempotence, ACM SIGPLAN Notices](https://dl.acm.org/doi/10.1145/2480359.2429100)
22. [Integrate Terraform with Ansible Automation Platform, HashiCorp](https://developer.hashicorp.com/validated-patterns/terraform/terraform-integrate-ansible-automation-platform)
23. [Ansible Glossary: Idempotency](https://docs.ansible.com/projects/ansible/2.9/reference_appendices/glossary.html?highlight=idempotency)
24. [Asserting Reliable Convergence for Configuration Management Scripts, OOPSLA/CITAC 2016](http://hummer.io/docs/2016-citac-oopsla.pdf)
25. [Testing idempotence and convergence of automatic configuration management, TU Wien](https://repositum.tuwien.at/bitstream/20.500.12708/6733/2/Hanappi%20Oliver%20-%202016%20-%20Testing%20idempotence%20and%20convergence%20of%20automatic...pdf)
26. [Message delivery and processing, Think Distributed Systems, Manning](https://livebook.manning.com/book/think-distributed-systems/chapter-4)
27. [RFC 9110: HTTP Semantics, IETF](https://www.rfc-editor.org/rfc/rfc9110.html)

---
*Initially written Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 软件与编程 › Software engineering and development process › Software design and architecture › Titles 4 to Mo

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/idempotency

English original: https://www.edgepedia.org/idempotency
