Skip to content

Cassandra Tunable Consistency ​

Consistency Level Per Query ​

Write consistency levels:

cql
-- Chạy trong cqlsh trên một nút (RF=1: mọi mức CL đều đủ replica)
CREATE KEYSPACE IF NOT EXISTS myapp WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};
CREATE TABLE IF NOT EXISTS myapp.users (user_id int PRIMARY KEY, email text, name text, status text);
USE myapp;

-- CL đặt bằng lệnh cqlsh CONSISTENCY, hoặc theo từng request trong driver (CQL không có USING CONSISTENCY)
-- ANY: nhanh nhất, ít bền nhất (ghi vào 1 nút hoặc chỉ lưu hint); ANY chỉ dùng cho ghi
CONSISTENCY ANY;
INSERT INTO users (user_id, name) VALUES (1, 'An');

-- ONE: ghi vào 1 replica (nhanh)
CONSISTENCY ONE;
INSERT INTO users (user_id, name) VALUES (2, 'Binh');

-- QUORUM: ghi vào (RF/2)+1 replica (cân bằng)
CONSISTENCY QUORUM;
INSERT INTO users (user_id, name) VALUES (3, 'Chi');

-- ALL: ghi vào mọi replica (chậm nhất, bền nhất)
CONSISTENCY ALL;
INSERT INTO users (user_id, name) VALUES (4, 'Dung');

-- LOCAL_QUORUM: quorum trong datacenter cục bộ (multi-DC)
CONSISTENCY LOCAL_QUORUM;
INSERT INTO users (user_id, name) VALUES (5, 'Em');

Read consistency levels:

cql
-- Chạy sau khối trên (keyspace myapp, bảng users đã có dữ liệu)
USE myapp;

-- ONE: đọc 1 replica (nhanh, có thể cũ)
CONSISTENCY ONE;
SELECT user_id, name FROM users WHERE user_id = 1;

-- QUORUM: đọc (RF/2)+1 replica (cân bằng)
CONSISTENCY QUORUM;
SELECT user_id, name FROM users WHERE user_id = 3;

-- ALL: đọc mọi replica (chậm nhất, mạnh nhất)
CONSISTENCY ALL;
SELECT user_id, name FROM users WHERE user_id = 4;

-- ANY không dùng cho đọc: InvalidRequest "ANY ConsistencyLevel is only supported for writes"

Không đủ replica sống thì lỗi Unavailable:

cql
-- Minh hoạ: RF=3 nhưng cụm chỉ có 1 nút (đo trên cassandra:5 một nút; cụm 3 nút thì QUORUM thành công)
CREATE KEYSPACE IF NOT EXISTS ks3 WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3};
CREATE TABLE IF NOT EXISTS ks3.users (user_id int PRIMARY KEY, email text, name text, status text);
USE ks3;

CONSISTENCY QUORUM;
INSERT INTO users (user_id, name) VALUES (1, 'An');
-- Unavailable: Cannot achieve consistency level QUORUM (required_replicas 2, alive_replicas 1)

CONSISTENCY ONE;
INSERT INTO users (user_id, name) VALUES (1, 'An');  -- thành công: ONE chỉ cần 1 replica

Strong Consistency Formula ​

text
Write CL + Read CL > RF = Strong Consistency

Examples (RF=3):
─────────────────────────────────────────────────────────
Write     Read      Total    Strong?   Latency   Use Case
─────────────────────────────────────────────────────────
QUORUM(2) QUORUM(2) 4        ✅ Yes    Medium    Balanced
ONE(1)    ALL(3)    4        ✅ Yes    High read Analytics
ALL(3)    ONE(1)    4        ✅ Yes    High write Logs
ONE(1)    ONE(1)    2        ❌ No     Low       Cache
ONE(1)    QUORUM(2) 3        ❌ No     Low       Metrics

Practical example:

javascript
// Node.js (cassandra-driver); chạy trong hàm async, sau khối tạo myapp.users ở mục Consistency Level Per Query
const cassandra = require('cassandra-driver')
const client = new cassandra.Client({
  contactPoints: ['node1', 'node2', 'node3'],
  localDataCenter: 'datacenter1',  // bắt buộc ở driver 4.x
  keyspace: 'myapp'
})

// Write with QUORUM
await client.execute(
  'INSERT INTO users (user_id, name) VALUES (?, ?)',
  [7, 'Gia'],
  { prepare: true, consistency: cassandra.types.consistencies.quorum }
)

// Read with QUORUM (strong consistency)
const result = await client.execute(
  'SELECT * FROM users WHERE user_id = ?',
  [7],
  { prepare: true, consistency: cassandra.types.consistencies.quorum }
)

Lightweight Transactions (LWT) ​

Compare-and-set (CAS) operations:

cql
-- Chạy sau khối tạo myapp.users (cột user_id, email, name, status) ở mục Consistency Level Per Query
USE myapp;

-- Insert if not exists (atomic)
INSERT INTO users (user_id, email, name)
VALUES (123, 'john@example.com', 'John')
IF NOT EXISTS;

-- Update if condition matches (atomic)
UPDATE users
SET email = 'newemail@example.com'
WHERE user_id = 123
IF email = 'john@example.com';

-- Delete if condition matches (status phải đang là 'inactive')
UPDATE users SET status = 'inactive' WHERE user_id = 123;
DELETE FROM users
WHERE user_id = 123
IF status = 'inactive';

How it works:

text
Dùng đồng thuận Paxos (Paxos v1 cổ điển: 4 vòng trao đổi, là mặc định ở 5.0; Paxos v2 có từ 4.1, bật bằng `paxos_variant: v2`, giảm còn khoảng 2 vòng)
1. Prepare/Promise
2. Read/Results
3. Propose/Accept
4. Commit/Ack

Chi phí: nhiều vòng trao đổi hơn ghi thường nên độ trễ cao hơn

Performance:

text
Số tuyệt đối đổi theo cụm và tải: đo ghi thường (QUORUM) và LWT trên cụm của bạn (ví dụ bằng TRACING ON trong cqlsh).
LWT chậm hơn ghi thường vì dùng Paxos. Đọc kết quả LWT mới nhất: CONSISTENCY SERIAL; rồi SELECT.

When to use LWT:

  • ✅ Unique constraints (email, username)
  • ✅ Account balance updates
  • ✅ Resource allocation (prevent double-booking)
  • ❌ High-throughput writes (too slow)
  • ❌ Analytics (eventual consistency OK)

Phải nhớ

  • W + R > RF: QUORUM ghi + QUORUM đọc ở RF=3 cho đọc thấy ghi đã thành công gần nhất. Không đủ replica sống thì lỗi Unavailable (đo: RF=3 trên 1 nút, QUORUM cần 2 replica, chỉ 1 sống).
  • LWT (IF …) dùng Paxos nên chậm hơn ghi thường; chỉ dùng cho ràng buộc cần compare-and-set.
  • BATCH không phải ACID đầy đủ: chỉ cô lập trong một partition; UNLOGGED lỗi có thể áp dụng một phần. Đừng dùng batch để tăng tốc.