← 返回规律列表
架构

CAP 定理

在发生网络分区时,分布式系统必须在一致性和可用性之间做取舍。

显示原始英文内容

CAP Theorem

A distributed system can guarantee only two of: consistency, availability, and partition tolerance.

Takeaways

  • A distributed system can only guarantee two out of three things at once: Consistency, Availability, and Partition Tolerance. When the network is healthy you can have all three, but the moment a partition happens, you have to give one up.
  • When a network split occurs, you face a choice: stay consistent (every node agrees, but some requests may fail) or stay available (every request gets an answer, but the data might be slightly out of date). You can't fully have both.
  • Real databases pick a side. MongoDB leans toward consistency, blocking writes during a partition so all replicas stay in sync. Cassandra leans toward availability, keeping the lights on and serving queries even if replicas briefly disagree.

Overview

The CAP theorem states that a distributed system cannot simultaneously provide all three guarantees: Consistency (all nodes see the same data), Availability (every request receives a response), and Partition Tolerance (the system operates despite network failures).

Since network partitions are unavoidable in practice, systems must be partition-tolerant. This means choosing between consistency and availability when designing distributed architectures. The CAP theorem is a useful starting point, though it is a simplification that doesn't cover all aspects of the design space.

Examples

The Domain Name System (DNS) is designed as AP (Available and Partition-tolerant). If some name servers are partitioned, they still reply (availability), even if their information might be slightly outdated until zones sync up.

MongoDB is a CP (Consistent and Partition-Tolerant) database, blocking writes during a partition so all replicas stay in sync. Cassandra is an AP (Available and Partition-Tolerant) database, serving queries even if replicas briefly disagree.

Origins

Eric Brewer created the theorem in 2000 in the context of web services, and it was later formalized by Gilbert and Lynch in 2002. Brewer observed that designers of large-scale systems faced three concerns: keeping data consistent across nodes, keeping the service up, and handling network unreliability.

The formal proof showed that in a distributed system with shared data, you must sacrifice either consistency or availability when a network partition occurs. CAP became a guiding principle in the NoSQL movement and distributed database design in the 2000s.

核心含义

CAP 中的一致性指每次读取都能看到最新写入,可用性指每个请求都能得到响应,分区容错指网络分区发生时系统仍能继续工作。分区是分布式系统无法彻底避免的,因此真实选择通常是 CP 或 AP,而不是任意选两个。

不同业务可以做不同取舍:支付余额更重视一致性,社交动态可能更重视可用性和最终一致性。

实践例子

网络隔离时,CP 系统可能拒绝部分写入来避免数据冲突;AP 系统继续接受请求,但需要通过版本合并、补偿或异步同步处理暂时不一致。

来源与边界

CAP 由 Eric Brewer 提出,并由 Gilbert 和 Lynch 形式化。它描述的是分区发生时的约束,不是简单的“系统只能保证三个中的两个”的日常性能打分表。