website logo

← All articles

Notes to Myself: The CAP Theorem for the Jungle

A quick overview of the CAP theorem so you won't be embarassed anymore in an impromptu db deep conversation.

I’ve been meaning to write this down for a while. Every few months, I find myself in a architecture discussion where someone asks, “Can’t we just use Postgres for this?” or “Why not just throw Redis at it?” And every time, I have to mentally walk through the same jungle of trade-offs.

This is my quick hand-drawn map of that jungle. The CAP theorem isn’t just an academic curiosity from 2000. It’s the reason a Rails app behaves the way it does when the network hiccups, and it’s the difference between a system that gracefully degrades and one that wakes you up at 3 AM.

Let’s get into it.

The Theorem, Stripped Down

Eric Brewer’s CAP theorem states that a distributed data store can only guarantee two of three properties: Consistency (every read sees the latest write), Availability (every request gets a non-error response), and Partition Tolerance (the system keeps working when the network drops messages between nodes).

Here’s the part that took me years to internalize: Partition tolerance isn’t optional. Networks fail. Clouds have hiccups. If you’re running more than one node, you will encounter partitions. So the real choice is always between C and A when the network splits.

When a partition happens, you datastore either:

  • Refuses to answer (or error out) because you can’t guarantee the data is fresh → CP
  • Answers anyway with possibly stale data, hoping it reconciles later → AP

That’s it. That’s the jungle. Now let’s look at the animals.

PostgreSQL: The Reliable Workhorse (CP, with a Caveat)

PostgreSQL is my default. It’s ACID-compliant, it’s predictable, and it has an ecosystem that Rails developers have spent two decades building around. In CAP terms, a standard PostgreSQL cluster is CP: when a primary fails and a failover is in progress, you might get errors rather than stale reads. It prioritizes correctness.

The scalability story is more nuanced than the Twitter hot takes suggest. A single well-tuned Postgres node on modern hardware can handle hundreds of thousands of transactions per second and tens of terabytes of data. For most Rails apps, even the successful ones, that envelope is plenty.

When you outgrow it, you have real options:

  • Read replicas for scaling reads horizontally
  • Native partitioning for managing large tables
  • Citus for sharding across multiple nodes while keeping SQL semantics. Citus turns Postgres into a distributed cluster that can handle 100+ nodes and petabyte-scale data for the right workloads

The constraint: Postgres isn’t magic. If your workload requires massive write concurrency across geographies, or if you have hot rows that every request mutates, you’ll hit the single-writer bottleneck. That’s not a Postgres flaw, it’s the price of consistency. And honestly? For most Rails apps, that price is worth paying.

Redis: The Speed Demon (AP for Caching, CP for Coordination)

Redis is the jungle cat of the datastore world: blazing fast, deceptively simple, and occasionally bites you when you least expect it.

Redis is AP by default. In a cluster, if a master node goes down, a replica takes over, but you might lose recent writes (the replication is asynchronous). That’s fine for caching. It’s not fine for your primary source of truth.

The scalability angle is where Redis gets interesting. Redis is single-threaded for command execution, ie. one core, one event loop. That means vertical scaling has a hard ceiling. Clustering helps, but it introduces complexity: keys need hash tags to stay on the same node, and cross-slot operations become your problem.

Where Redis shines: caching (obviously), session storage, rate limiting, leaderboards, and lightweight job queues. Where it hurts: using it as a primary database when you need durability guarantees. If you’re storing anything you can’t afford to lose, Redis should be a cache in front of Postgres, not the source of truth.

Columnar Databases (ClickHouse, Redshift): The Analytics Beasts

These aren’t OLTP databases. They’re built for scanning huge datasets and aggregating them fast. The CAP conversation here is different because the access patterns are different.

ClickHouse is AP-leaning in practice. It’s designed for high-ingest, high-concurrency analytical queries. It scales horizontally by adding shards, and it prioritizes availability and query throughput over strict consistency. For real-time dashboards and event analytics, it’s phenomenal.

Redshift is a managed cloud warehouse. It’s more traditional in its consistency model, but its concurrency limits (50 concurrent queries across queues) make it painful for user-facing analytics. It’s designed for batch BI, not real-time product features.

The scalability constraint: Columnar stores scale beautifully for reads over large datasets but are terrible for single-row lookups or frequent small writes. If your Rails app is trying to serve a dashboard with sub-second latency over millions of events, you don’t want to query Postgres for that. You want to stream events to ClickHouse and let it do what it does best.

Graph Databases (Neo4j, JanusGraph): The Relationship Specialists

Graph databases exist because relational joins across many-to-many relationships become pathological at depth. If your queries look like “find friends of friends who bought this product and also follow this brand,” you feel the pain in SQL.

CAP stance: This varies by implementation. Neo4j (the most popular) is generally CP for its clustered deployments. It prioritizes consistency and will refuse writes if it can’t achieve quorum. JanusGraph, built for distributed deployments, leans more toward AP with tunable consistency.

The advantage: Traversal performance. What takes a recursive CTE in Postgres milliseconds for depth-2 takes a graph database single-digit milliseconds for depth-5 or depth-6.

The constraint: Graph databases are specialized tools. They’re not great at bulk analytics, they’re not great at simple CRUD, and the operational overhead of running a cluster is non-trivial. For a Rails app with a social feature, you might be better served with a well-indexed Postgres schema and a materialized view than a whole new database.

Datomic: The Immutable Time Machine (CP)

Datomic is the weird one in the best way and my foray into Clojure couldn’t let me to skip that one. It’s not a database in the traditional sense; it’s an immutable fact store with a Datalog query engine, built by Rich Hickey for the Clojure world.

CAP stance: Datomic is CP. It uses a single transactor process to serialize writes with compare-and-swap semantics, ensuring consistency. Reads scale horizontally through peers that cache data locally.

The advantage: Datomic gives you something almost no other database does time travel as a first-class feature. Every fact is timestamped. You can query the database as of any moment. For auditing, debugging, and event-sourced architectures, this is transformative.

The constraints are real: The single transactor becomes a write bottleneck. The peer model (which caches data in your app process) is incredibly fast for reads but requires JVM-based services and careful memory management. And the licensing cost makes it a tough sell for small teams.

Datomic is what I reach for when the problem domain involves complex, evolving relationships and the history of those relationships matters as much as the current state. It’s not a general-purpose replacement for Postgres. It’s a scalpel.

Array Datastores (kdb+): The Vector-Native Specialist

kdb+ doesn’t fit neatly into the same taxonomy as Postgres or Redis. It’s not a general-purpose relational store, not a cache, not a graph engine. It’s an array datastore: a vector-native, column-oriented time-series engine built around the q language, and it has been the quiet workhorse of capital markets for over 25 years.

CAP stance: Pragmatically AP with CP characteristics, but the framework doesn’t map cleanly onto a system designed for ingest-and-query rather than transactional consistency. Out of the box, a single kdb+ process is effectively CP: one writer, no distributed consensus, no partition to tolerate because there’s no cluster to partition. For high availability, KX’s reference architecture recommends hot-hot mirrored pairs: a secondary system captures the same data and serves the same queries, with failover triggered at the process level. This is operational redundancy, not mathematical guarantee: no Raft, no Paxos, no quorum. For market data capture and real-time analytics, that trade-off is correct. You don’t want consensus latency on a tickerplant ingesting millions of updates per second.

The advantage: The “array” in array datastore isn’t marketing. kdb+ treats lists, dictionaries, and tables as primitive types, and q operates on entire vectors rather than iterating row by row. The entire system is under 1 MB and fits in CPU cache: no JVM, no query planner overhead. Benchmark comparisons against traditional RDBMS on billion-row datasets show point queries 20–100× faster, aggregations 100–200× faster, and time-series joins 100–300× faster. Market data ingestion sustains 5–10 million Level 1 quote updates per second.

The scalability constraints: kdb+ scales vertically better than almost anything, a single box with enough RAM and fast NVMe handles trillions of historical records. The tiered architecture (RDB in memory, IDB for intraday, HDB memory-mapped on disk) keeps hot data in RAM and routes queries seamlessly. Horizontal scaling is possible but it’s an engineering project, not a configuration flag: sharding topology, gateway routing, and operational complexity are yours to design. And like Redis, a single kdb+ process is single-threaded ie. parallelism comes from running multiple processes, not from within one.

I’d reach for kdb+ when the problem is time-series analytics at scale with sub-millisecond latency: financial tick data, IoT streams, real-time risk calculations. The honest framing: kdb+ is a specialized instrument. Rails writes transactional state to Postgres; events stream to kdb+ for analytics. Each does what it’s built for.

The Real Lesson: Match the Tool to the Failure Mode

Here’s what I wish someone had told me earlier: CAP isn’t about picking a database and calling it a day. It’s about understanding what happens when things go wrong, and deciding whether that behavior is acceptable for this specific feature.

Your payment processing needs CP. Your “likes” counter can be AP. Your analytics pipeline can be eventual. Your user session store should probably be Redis with a Postgres fallback.

The jungle is dense. But once you know which animals are dangerous and which are just loud, you can move through it with confidence.