Skip to content
javahacks.dev
Microservices

CAP Theorem and What It Means for Your Java Services

The CAP theorem explained for Java services: consistency, availability and partition tolerance, and how it shapes database and design choices.

6 min read
Summarize in AI
Flat illustration of a database beside the table it holds, with the OpenJDK, PostgreSQL, MySQL and Redis logos.

The CAP theorem gets quoted as "pick two of three: consistency, availability, partition tolerance", which is wrong in a way that makes it useless. You do not get to pick partition tolerance. Networks between your services will fail, so the real statement is narrower and more practical: when a partition happens, a replicated system must choose between answering with possibly stale data and refusing to answer. This post explains what the three letters mean, what a partition looks like in a Java service, where you already make this choice without noticing, how to make it per operation, what the theorem leaves out and the common misreadings. The examples use Spring Boot 4, Kafka and a replicated database; the argument is about behavior, not a product.

The three letters

The theorem, from Gilbert and Lynch's formalization of Brewer's conjecture, uses narrow definitions.

LetterMeaning in the theoremNot the same as
ConsistencyLinearizability: every read sees the latest completed write, as if there were one copyThe "C" in ACID, which is about constraints
AvailabilityEvery request to a working node gets a non-error responseHigh uptime of the whole system
Partition toleranceThe system keeps working when messages between nodes are lost or delayedA feature you opt out of

Because partitions are a fact of networks, a distributed system is either CP (it sacrifices availability during a partition to stay consistent) or AP (it stays available and may return stale or conflicting data). A single-node database on one machine has no partition to tolerate, and so the theorem does not apply to it at all.

What a partition looks like

Two services, or two replicas of a database, cannot reach each other. Nothing crashes. Each side is healthy and sure that the other has vanished. You can see it in a few lines of Java: a call to another service that neither succeeds nor fails quickly.

src/main/java/dev/javahacks/cap/InventoryClient.javajava
@Component
class InventoryClient {

    private final RestClient http;

    InventoryClient(RestClient.Builder builder) {
        var factory = new JdkClientHttpRequestFactory();
        factory.setReadTimeout(Duration.ofSeconds(2));
        this.http = builder.baseUrl("http://inventory").requestFactory(factory).build();
    }

    int stockOf(String sku) {
        return http.get().uri("/stock/{sku}", sku).retrieve().body(Integer.class);
    }
}

When the network between the two services is cut, stockOf throws ResourceAccessException: I/O error ... Read timed out after two seconds. From the caller's side, a partitioned peer and a crashed peer and a slow peer look identical: you got no answer. A timeout is how every distributed system detects a partition, and every timeout is also a decision. Whatever your code does in the catch is your answer to the CAP question, whether you thought about it or not.

Where you see it in Java services

The choice appears in places that do not mention CAP.

A fallback that returns a default. The recommendations service is down, so the page shows popular items. That is availability over consistency, and it is the right call for recommendations.

java
try {
    return recommendations.forUser(userId);
} catch (ResourceAccessException e) {
    return popularItems.top(10);       // available, possibly not personalized
}

A read from a replica. The primary accepts a write, the replica has not caught up, and the user reloads and does not see their change. The read path chose availability and latency, accepting staleness. The behavior and what to do about it are covered in eventual consistency explained for Java developers.

A producer that waits for acknowledgment. Kafka lets you pick on each send:

java
Properties props = new Properties();
props.put(ProducerConfig.ACKS_CONFIG, "all");
props.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true);
// broker/topic side: min.insync.replicas=2 with replication.factor=3

With acks=all and min.insync.replicas=2, a write succeeds only if two replicas have it. If a partition leaves the leader with only itself, the send fails with NotEnoughReplicasException. That is CP behavior: refuse the write to avoid losing it. With acks=1 the leader acknowledges alone and the write can be lost on failover, which is AP behavior with a durability cost.

A write that must not be duplicated. An unreachable payment provider leaves you not knowing whether a charge went through. Blocking the user is consistent and unavailable; guessing is available and risky. The tools that make the retry safe are in duplicate messages and idempotent consumers.

Choose per operation

A whole system is rarely purely CP or AP. Decide per operation, by asking what the cost of each wrong answer is.

OperationWrong answer if stale or lostChoose
Show product descriptionA slightly old descriptionAvailability
Show "items in cart"A stale count for a secondAvailability
Reserve the last seatTwo people hold the same seatConsistency
Debit an accountMoney created or lostConsistency
Record a page viewOne missing countAvailability
Check a passwordLetting in a revoked credentialConsistency

For the operations that need consistency across services, a two-phase commit across HTTP services is rarely available. The usual answers are a saga with compensating actions, covered in the saga pattern in Java, or keeping those operations inside one database and one service. The broader trade-offs are in handling distributed transactions in Java.

Make the choice visible in code. A method named reserveSeat that throws SeatServiceUnavailable when it cannot confirm is honest. A reserveSeat that catches the error and returns true is claiming a consistency it does not have.

Beyond CAP: latency

CAP describes behavior during a partition, which is the rare case. Daniel Abadi's PACELC extension adds the common one: when there is no partition, you still trade between latency and consistency. A synchronous replica makes every write wait for the second copy; an asynchronous one is faster and can lose or show stale data. Most of the time your service is not partitioned, and the trade you feel daily is the slower write against the stale read. The practical lesson is that "consistency versus availability" is mostly a latency budget in disguise. The CAP twelve years later article by Eric Brewer, who stated the original conjecture, makes this point and rejects the "pick two" framing.

Practical consequences

  1. Set timeouts everywhere. Without a timeout, a partition becomes a hung thread, then an exhausted pool, then an outage. Every remote call needs a connect and read timeout, and a deadline for the whole request.
  2. Design the degraded mode. For each dependency, write down what the user sees when it is unreachable: a default, a cached value or an error. Implement it before the incident.
  3. Make retries safe. If a request may be repeated, repeating it must not repeat its effect.
  4. Expose staleness to the caller. A response that says "asOf": "2026-11-06T09:30:00Z" lets the client decide whether the data is fresh enough.
  5. Test the partition. Cut the network in a test with a tool such as Toxiproxy or Testcontainers' network faults, and watch what your service returns. The design you believe in and the behavior you have are often different.

Common misreadings

"We chose CA." There is no CA distributed system, since a partition forces the choice. A single-node database is "CA" only because it is not distributed.

"Our database is consistent, so we are CP." Many databases offer tunable consistency; your settings decide. A read at the weakest level on a "consistent" store behaves like an AP system.

"Eventually consistent means it is broken." It is a deliberate model with known patterns. A shopping cart that merges concurrent edits is eventually consistent by design.

"CAP means every microservice needs a distributed transaction." The usual response is the opposite: avoid the need by keeping data that must agree in one service.

When this does not apply

If your system is a single database with one writer and replicas used only for backup or reporting, CAP is not your daily concern; ordinary transaction isolation is. If all of your state lives in one managed database whose consistency you accept, the theorem shapes the vendor's design, not yours. And inside one JVM, on one machine, there is no partition to speak of; the problems there are about concurrency and the memory model, not about the network.

Taggedexplainer
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.