This article explains the CAP theorem (Consistency, Availability, Partition Tolerance) by demonstrating its practical implications in building a distributed rate limiter. It contrasts a naive in-memory approach with a more robust Redis-backed solution, highlighting the explicit trade-offs between consistency and availability in distributed systems during network partitions.
Read original on Dev.to #systemdesignThe CAP theorem states that a distributed data store can only guarantee two out of three properties during a network partition: Consistency, Availability, and Partition Tolerance. Partition Tolerance (P) is a given in any distributed system, meaning systems must continue to operate despite network failures that split the system into isolated sub-systems. Therefore, the core trade-off is between Consistency (C) and Availability (A).
When a network partition occurs, a system must choose to prioritize either Consistency (CP) or Availability (AP):
The article uses the example of a distributed API rate limiter to illustrate the CAP theorem. A naive in-memory rate limiter on multiple service instances behind a load balancer inherently becomes an AP system by accident. Each instance maintains its own counter, leading to inconsistent rate limits where a user can exceed their quota by switching instances. This provides availability but sacrifices consistency.