O teorema CAP é o ponto onde muita gente trava em entrevistas de system design — geralmente porque o explicam errado. Ele não diz "escolha 2 de 3" de forma absoluta; diz algo mais sutil sobre o que acontece quando a rede falha. Entender isso de verdade muda como você projeta sistemas distribuídos.
O que são C, A e P
O teorema CAP trata de três propriedades de um sistema distribuído:
- C — Consistência: toda leitura enxerga a escrita mais recente. Todos os nós concordam sobre o valor atual.
- A — Disponibilidade (Availability): toda requisição recebe uma resposta (não um erro), mesmo que não seja a mais atual.
- P — Tolerância a Partição: o sistema continua funcionando mesmo quando a rede entre os nós falha e eles não conseguem se comunicar.
A partição é inevitável
Aqui está a interpretação correta: em um sistema distribuído de verdade, partições de rede vão acontecer — cabos caem, latência dispara, nós ficam isolados. Você não pode "abrir mão" de P, porque P não é uma escolha, é a realidade. Então o teorema vira: quando há uma partição, você escolhe entre C e A. Fora de partições, você pode ter os dois.
A analogia: dois caixas de banco que perdem contato entre si. Se um cliente quer sacar, o caixa tem duas opções. Recusar até reconectar e confirmar o saldo (escolhe C — consistente, mas indisponível). Ou permitir o saque com o saldo que conhece (escolhe A — disponível, mas arrisca inconsistência). Não dá para ter os dois durante a falha.
CP vs AP na prática
| Tipo | Prioriza | Na partição | Exemplo de uso |
|---|---|---|---|
| CP | Consistência | Recusa/bloqueia para não dar resposta errada | Banco, estoque, pagamentos |
| AP | Disponibilidade | Responde mesmo com dado possivelmente velho | Feed social, likes, timeline |
A escolha depende do domínio. Em um sistema de pagamentos, mostrar saldo errado é inaceitável — escolhe-se CP. Já num feed social, ver um like com alguns segundos de atraso não machuca ninguém — escolhe-se AP, priorizando que a tela sempre carregue.
Consistência forte vs eventual
Isso leva a dois modelos de consistência. Consistência forte: após uma escrita, toda leitura vê o novo valor imediatamente — o comportamento intuitivo, porém caro em sistemas distribuídos. Consistência eventual: as réplicas convergem para o mesmo valor "eventualmente", podendo divergir por um curto período. Sistemas AP abraçam a consistência eventual.
// Consistência eventual em ação:
escreve("perfil.nome", "Ana") // no nó 1
le("perfil.nome") no nó 2 -> "João" (valor antigo, ainda nao propagou)
... 200ms depois ...
le("perfil.nome") no nó 2 -> "Ana" (convergiu)
CAP não é "escolha 2 de 3". É: como a partição é inevitável, quando a rede falhar você escolherá entre responder consistente ou responder disponível. Fora da falha, pode ter ambos.
Além do CAP: PACELC
O CAP só fala do que acontece durante uma partição, e é aí que vale citar o PACELC: na partição (P) escolhe-se entre A e C; mas mesmo sem partição (Else, E), há um trade-off entre Latência (L) e Consistência (C) — manter tudo fortemente consistente custa tempo de resposta. PACELC é o CAP completado com a parte do dia a dia normal.
Conclusão
O teorema CAP é uma lente para decidir o comportamento do seu sistema sob falha de rede. Não é escolher arbitrariamente dois pilares: é entender que a partição manda, e que a decisão real é entre consistência e disponibilidade no momento da falha — e entre consistência e latência no resto do tempo. Essa decisão é inseparável de como você pensa escalabilidade.
The CAP theorem is where a lot of people get stuck in system design interviews — usually because they explain it wrong. It doesn't say "pick 2 out of 3" in an absolute way; it says something subtler about what happens when the network fails. Truly understanding it changes how you design distributed systems.
What C, A and P are
The CAP theorem deals with three properties of a distributed system:
- C — Consistency: every read sees the most recent write. All nodes agree on the current value.
- A — Availability: every request receives a response (not an error), even if it isn't the most up to date.
- P — Partition Tolerance: the system keeps working even when the network between nodes fails and they can't communicate.
Partitions are inevitable
Here is the correct interpretation: in a real distributed system, network partitions will happen — cables get cut, latency spikes, nodes become isolated. You can't "give up" P, because P isn't a choice, it's reality. So the theorem becomes: when there's a partition, you choose between C and A. Outside of partitions, you can have both.
The analogy: two bank tellers who lose contact with each other. If a customer wants to withdraw money, the teller has two options. Refuse until they reconnect and confirm the balance (chooses C — consistent, but unavailable). Or allow the withdrawal with the balance they know (chooses A — available, but risks inconsistency). You can't have both during the failure.
CP vs AP in practice
| Type | Prioritizes | During a partition | Example use |
|---|---|---|---|
| CP | Consistency | Refuses/blocks rather than give a wrong answer | Banking, inventory, payments |
| AP | Availability | Responds even with possibly stale data | Social feed, likes, timeline |
The choice depends on the domain. In a payments system, showing a wrong balance is unacceptable — you choose CP. In a social feed, seeing a like a few seconds late hurts no one — you choose AP, prioritizing that the screen always loads.
Strong vs eventual consistency
This leads to two consistency models. Strong consistency: after a write, every read sees the new value immediately — the intuitive behavior, but expensive in distributed systems. Eventual consistency: replicas converge to the same value "eventually", and may diverge for a short period. AP systems embrace eventual consistency.
// Eventual consistency in action:
write("profile.name", "Ana") // on node 1
read("profile.name") on node 2 -> "João" (old value, hasn't propagated yet)
... 200ms later ...
read("profile.name") on node 2 -> "Ana" (converged)
CAP is not "pick 2 out of 3". It's this: since partitions are inevitable, when the network fails you'll choose between answering consistently or answering availably. Outside of a failure, you can have both.
Beyond CAP: PACELC
CAP only talks about what happens during a partition, and that's where it's worth mentioning PACELC: during a partition (P) you choose between A and C; but even without a partition (Else, E), there's a trade-off between Latency (L) and Consistency (C) — keeping everything strongly consistent costs response time. PACELC is CAP completed with the everyday, normal-operation part.
Conclusion
The CAP theorem is a lens for deciding how your system behaves under network failure. It's not about arbitrarily picking two pillars: it's about understanding that the partition calls the shots, and that the real decision is between consistency and availability at the moment of failure — and between consistency and latency the rest of the time. That decision is inseparable from how you think about scalability.