Consistency is a per-statement choice, and the arithmetic is the whole idea. Every read and write names a consistency level - how many replicas must respond before the operation succeeds.
Write levels: ANY (even a hint counts - effectively no guarantee), ONE, TWO, QUORUM (a majority of all replicas), LOCAL_QUORUM (a majority in the local datacentre), EACH_QUORUM, ALL. Read levels are the same set minus ANY.
R + W > RF gives you strong consistency. With RF=3, QUORUM write (2) plus QUORUM read (2) is 4 > 3, so the read is guaranteed to see the write. ONE plus ONE is 2, which is not greater than 3, so a read can miss a write that succeeded. That single inequality is the most useful thing in this module, and it means consistency is an engineering decision you make per query - strong where it matters, fast where it does not.
In a multi-datacentre deployment, use LOCAL_QUORUM. QUORUM across datacentres means waiting for a cross-continental round trip on every operation, and LOCAL_QUORUM with RF=3 per datacentre gives you strong consistency within a datacentre and asynchronous replication between them. This is the default production configuration for a reason.
Conflict resolution is last-write-wins by timestamp, per column. Every write carries a microsecond timestamp, and when two writes to the same column conflict, the higher timestamp wins. Two consequences you must internalise. First, clock skew between nodes causes silent data loss: a node whose clock is two seconds fast writes timestamps that beat correct writes for two seconds, and nothing reports it - so NTP is a correctness requirement in Cassandra, not an operational nicety. Second, resolution is per column, so two concurrent updates to different columns of the same row both survive, which is often what you want and occasionally a surprise.
Lightweight transactions provide compare-and-set: IF NOT EXISTS, IF EXISTS, IF column = value. They use Paxos, which means four round trips among the replicas instead of one, so they are roughly an order of magnitude more expensive than a normal write and they do not scale the way the rest of Cassandra does. Use them for genuine uniqueness requirements - a username registration - and never in a hot path. Note also that mixing LWT and non-LWT writes to the same partition breaks the guarantee, and that the [applied] column in the result is how you tell whether it happened.
Batches are misunderstood, and the misunderstanding is expensive. A logged batch guarantees that all its statements will eventually be applied - the coordinator writes a batch log to two other nodes first, then applies. It is not isolated and not a transaction. A multi-partition logged batch is usually a mistake: it makes one coordinator responsible for writes spread across the cluster, serialises them, and routinely performs worse than the same statements sent in parallel. The legitimate use is atomicity across the denormalised copies of one logical write. A single-partition batch is different and genuinely good: it is applied as one mutation, isolated, and cheaper than separate writes.
Driver configuration decides what your users actually see. Token-aware routing sends a request straight to a replica, saving a hop. Retry policies decide what happens on a timeout - and a retry on a non-idempotent statement (a counter increment) double-applies, so the driver needs to know which statements are idempotent. Speculative execution sends a second copy of a slow request to another replica, which cuts tail latency and multiplies load. These are not tuning details; they are part of the correctness story.
Laboratory exercise 3 - consistency, measured.
Build an event service and run at least 100 concurrent clients against your three-node cluster.
Demonstrate R + W > RF empirically. Write at ONE and read at ONE in a tight loop while a node is down or under load, and count how often the read misses the write. Then do QUORUM/QUORUM and show zero misses. Then tabulate latency for every sensible combination - this table is the module's main artefact.
Demonstrate clock skew causing data loss: skew one node's clock forward by five seconds, write through it, then write the correct value through another node, and show the stale value winning. Record that nothing warned you.
Implement a username registration with IF NOT EXISTS and measure its latency against a plain insert. Run it concurrently for the same username and show exactly one succeeding.
Demonstrate the batch anti-pattern: write to 100 different partitions as a logged batch, then as 100 parallel statements, and compare throughput and coordinator load. Then show a single-partition batch being faster than separate writes.
Configure the driver properly - token-aware, idempotence flags, speculative execution - and measure p99 with and without speculative execution while one node is slow.
Deliverable: the service, the consistency-level table with miss rates and latencies, the clock skew demonstration, the LWT measurements including the concurrent uniqueness test, both batch comparisons, and the driver policy measurements.
-- ==================================================================
-- TUNABLE CONSISTENCY. R + W > RF is the whole idea.
-- ==================================================================
CONSISTENCY; -- shows the current level
CONSISTENCY QUORUM;
-- WRITE levels: ANY ONE TWO THREE QUORUM LOCAL_QUORUM EACH_QUORUM ALL
-- READ levels: the same, minus ANY
--
-- RF = 3:
-- W=ONE + R=ONE = 2 NOT > 3 -> a read CAN MISS the write
-- W=QUORUM + R=ONE = 3 NOT > 3 -> can still miss
-- W=QUORUM + R=QUORUM = 4 > 3 -> STRONG. Guaranteed.
-- W=ONE + R=ALL = 4 > 3 -> strong, slow reads
-- W=ALL + R=ONE = 4 > 3 -> strong, fragile writes
-- (ONE node down = no writes)
--
-- THE MOST USEFUL INEQUALITY IN THIS COURSE. It means consistency is
-- an ENGINEERING DECISION PER QUERY: strong where it matters, fast
-- where it does not.
-- The combination to measure in the lab:
CONSISTENCY ONE;
INSERT INTO events_by_id (event_id, user_id, kind) VALUES (now(), 7f3c..., 'login');
SELECT * FROM events_by_id WHERE event_id = ...; -- SOMETIMES EMPTY
CONSISTENCY QUORUM;
-- ... same loop, zero misses. Count them both; the numbers are the
-- module's main artefact.
-- MULTI-DATACENTRE: use LOCAL_QUORUM. This is the default production
-- configuration, for a reason.
CONSISTENCY LOCAL_QUORUM;
-- QUORUM across DCs waits for a CROSS-CONTINENTAL ROUND TRIP on
-- every operation. LOCAL_QUORUM with RF=3 per DC gives strong
-- consistency WITHIN a DC and asynchronous replication between.
-- EACH_QUORUM (writes) is for the rare case where you need both.
-- ==================================================================
-- LAST WRITE WINS, PER COLUMN, BY TIMESTAMP.
-- ==================================================================
SELECT WRITETIME(kind), kind FROM events_by_id WHERE event_id = ...;
-- writetime is MICROSECONDS since epoch.
INSERT INTO events_by_id (event_id, kind) VALUES (..., 'manual')
USING TIMESTAMP 1764500460000000;
-- You can set it explicitly. Which is also how you can make a
-- write that NOTHING CAN EVER OVERWRITE, by using a far-future
-- timestamp. Do not do this by accident.
-- *** CLOCK SKEW CAUSES SILENT DATA LOSS ***
-- node2's clock is 5 SECONDS FAST
-- t=0 write 'A' via node2 -> timestamp 5,000,000 us in the future
-- t=1 write 'B' via node1 -> timestamp "now"
-- -> 'A' WINS, for five seconds. 'B' is gone.
-- -> NOTHING REPORTS THIS. No error, no warning, no metric.
--
-- SO: NTP IS A CORRECTNESS REQUIREMENT IN CASSANDRA, not an
-- operational nicety. Monitor clock offset on every node and alarm
-- on it. Demonstrate the loss in the lab - it is the most
-- persuasive five minutes in the module.
-- Resolution is PER COLUMN, so two concurrent updates to DIFFERENT
-- columns of the same row BOTH SURVIVE. Usually what you want;
-- occasionally a surprise.
-- ==================================================================
-- LIGHTWEIGHT TRANSACTIONS: Paxos. ~10x the cost.
-- ==================================================================
INSERT INTO users (username, user_id, created_at)
VALUES ('ada', 7f3c..., toTimestamp(now()))
IF NOT EXISTS;
-- [applied]
-- -----------
-- True <- it happened
--
-- On a conflict:
-- [applied] | username | user_id
-- -----------+----------+---------
-- False | ada | 1a2b... <- and the EXISTING row
-- THE [applied] COLUMN IS HOW YOU TELL. A driver that ignores it
-- treats a refused write as a success.
UPDATE events_by_id SET kind = 'verified'
WHERE event_id = ... IF kind = 'pending';
DELETE FROM users WHERE username = 'ada' IF EXISTS;
-- THE COSTS, stated:
-- * PAXOS: four round trips among replicas instead of one
-- * roughly an ORDER OF MAGNITUDE more expensive than a normal write
-- * it DOES NOT SCALE the way the rest of Cassandra does
-- * MIXING LWT AND NON-LWT WRITES TO THE SAME PARTITION BREAKS
-- THE GUARANTEE - the non-LWT write does not participate in Paxos
-- * SERIAL / LOCAL_SERIAL are the read levels that see uncommitted
-- Paxos state:
CONSISTENCY SERIAL;
SELECT * FROM users WHERE username = 'ada';
--
-- USE FOR: genuine uniqueness (a username), a state machine
-- transition that must not race.
-- NEVER IN: a hot path.
-- ==================================================================
-- BATCHES. The misunderstanding is expensive.
-- ==================================================================
-- A LOGGED batch guarantees all statements WILL EVENTUALLY BE
-- APPLIED - the coordinator writes a batch log to two other nodes
-- first, then applies. IT IS NOT ISOLATED AND IT IS NOT A
-- TRANSACTION. There is no rollback and no atomicity of visibility.
-- *** THE ANTI-PATTERN *** 100 different partitions:
BEGIN BATCH
INSERT INTO events_by_user_day (...) VALUES (user1, ...);
INSERT INTO events_by_user_day (...) VALUES (user2, ...);
-- ... 98 more, all different partitions ...
APPLY BATCH;
-- ONE COORDINATOR becomes responsible for writes spread across
-- the whole cluster. It serialises them, writes a batch log first,
-- and ROUTINELY PERFORMS WORSE than the same statements sent in
-- parallel. It also produces coordinator heap pressure and
-- BatchSizeWarning / BatchSizeFailure in the logs.
--
-- Measure both. The parallel version usually wins by a lot.
-- THE LEGITIMATE USE: atomicity across the DENORMALISED COPIES of
-- ONE logical write. Three tables, one event:
BEGIN BATCH
INSERT INTO events_by_user_day (...) VALUES (...);
INSERT INTO events_by_id (...) VALUES (...);
INSERT INTO events_by_kind_day (...) VALUES (...);
APPLY BATCH;
-- Still not isolated; still guarantees eventual completion, which
-- is exactly what you want for keeping copies together.
-- A SINGLE-PARTITION batch is DIFFERENT AND GENUINELY GOOD: applied
-- as ONE MUTATION, isolated, and CHEAPER than separate writes:
BEGIN UNLOGGED BATCH
INSERT INTO events_by_user_day (user_id, day, event_at, event_id, kind)
VALUES (7f3c..., '2026-11-30', '...14:04:00+0000', now(), 'login');
INSERT INTO events_by_user_day (user_id, day, event_at, event_id, kind)
VALUES (7f3c..., '2026-11-30', '...14:04:01+0000', now(), 'click');
APPLY BATCH;
-- UNLOGGED skips the batch log. Correct here, because one
-- partition is one mutation anyway.
-- ==================================================================
-- DRIVER POLICIES: part of the CORRECTNESS story, not tuning.
-- ==================================================================
-- TOKEN-AWARE routing: the driver computes the token and sends the
-- request STRAIGHT TO A REPLICA, saving a coordinator hop. On by
-- default in modern drivers - verify it.
--
-- IDEMPOTENCE: the driver only retries statements MARKED
-- IDEMPOTENT. A retried COUNTER INCREMENT DOUBLE-COUNTS, and a
-- retried LWT may report the wrong [applied]. You must mark them:
-- statement.setIdempotent(true) -- a plain INSERT: yes
-- statement.setIdempotent(false) -- a counter update: NO
-- The default is usually false, which means your plain inserts are
-- NOT being retried when they safely could be. Check it.
--
-- RETRY POLICY: on a read timeout, retry at a lower consistency?
-- Only if your application can tolerate the weaker guarantee -
-- and a retry policy that silently downgrades consistency has
-- turned your R + W > RF arithmetic into a lie.
--
-- SPECULATIVE EXECUTION: send a second copy of a slow request to
-- another replica. CUTS TAIL LATENCY AND MULTIPLIES LOAD. Measure
-- p99 with and without, while one node is slow:
-- ConstantSpeculativeExecutionPolicy(delay = p99, maxExecutions = 2)
-- Only for IDEMPOTENT statements, for the same reason as retries.
Discussion
No questions on this topic yet. Sign in to ask the first one.