Skip to content

Cassandra & ScyllaDB in Depth ​

"Cassandra is a distributed storage system for managing very large amounts of structured data spread out across many commodity servers, while providing highly available service with no single point of failure." — Lakshman & Malik, Cassandra: A Decentralized Structured Storage System, LADIS 2009 (abstract)

Summary: Cassandra and ScyllaDB are masterless, partitioned, replicated wide-column databases that trade joins and multi-row transactions for writes that never stop and a data model built around the query. Focus: The token ring, consistency levels and quorum math, the write and read path, CQL data modeling, tombstones, compaction, repair, lightweight transactions, and what ScyllaDB changes (shard-per-core, tablets, workload prioritization, Alternator). Learning goal: Design a table per query, pick a consistency level and a compaction strategy on purpose, predict what breaks (wide partitions, tombstones, unrepaired replicas), and operate the cluster with nodetool.

This page is the complete reference for the Cassandra family: the masterless ring, vnodes and tablets, gossip and snitches, replication strategies, every consistency level, hinted handoff, read repair and anti-entropy repair, CQL data modeling (partition key, clustering columns, static columns, collections, UDTs, materialized views and why to avoid them), tombstones and TTL, lightweight transactions (Paxos and Accord), batches, the four compaction strategies, counters, SAI indexes and vector search, time-series bucketing, and ScyllaDB's differences. The conceptual comparison of wide-column and key-value stores (Bigtable, DynamoDB, HBase) is in Wide-Column & Key-Value at Scale; the map of all NoSQL families is NoSQL: Families & Data Models. This page does not re-teach the LSM tree (see Storage Engines), consistent hashing (see Consistent Hashing), Bloom filters (Bloom Filters & Probabilistic Structures), the theory of weaker consistency (Eventual Consistency in Database Systems) or consensus (Distributed SQL, Consensus & 2PC); each is explained in one sentence where it is needed and linked.

Page map ​

If you are looking forGo to
Tables you can memorise in one minuteEverything in one minute
Why a masterless database exists, and what you give upWhy Cassandra exists
The paper, the Dynamo and Bigtable parents, versionsWhere it comes from
Ring, vnodes, gossip, snitch, replication strategy, consistency levelsCluster concepts
Write path, read path, hints, read repair, anti-entropy repairData path and repair
Partition key, clustering, static, collections, UDT, MV, query-first, partition sizeData modeling
Tombstones, TTL, gc_grace_seconds, zombiesDeletes and tombstones
LWT, Paxos, Accord, batches, counters, timestampsConcurrency and atomicity
STCS, LCS, TWCS, UCSCompaction strategies
SAI, secondary indexes, vector search, time-series bucketingIndexes and time series
Cassandra vs ScyllaDB vs DynamoDB vs relationalPer-product behaviour
shard-per-core, Seastar, tablets, workload prioritization, AlternatorScyllaDB differences
nodetool, cassandra.yaml knobs, error codesMechanics
Unique usernames, two lookups, queues, hot partitions, counters, paging, bulk loadSolving the classic problems
Go and PHP/Laravel clients, retry wrapperGo and PHP clients, Retries
Which strategy, level, productChoosing
Monolith to multi-regionIn architecture
Operational pitfallsPitfalls
Three-node Docker cluster, quorum and tombstone experimentsLab
Wrong beliefs, cheat sheet, questions, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The model.

IdeaIn plain wordsWhy it matters
Masterless ringEvery node can take any request; there is no primaryNo failover event, no single point of failure
Partition keyThe part of the primary key that is hashed to pick the nodesDecides where data lives and how big a partition grows
Clustering columnsThe rest of the primary key; they sort rows inside a partitionRange queries and "latest N" are one sequential read
Replication factor (RF)How many copies of every partitionRF=3 survives one dead replica at QUORUM
Consistency level (CL)How many replicas must answer, chosen per statementYour consistency/availability dial
Query-first modelingOne table per query; copy data on writeReads touch one partition; no joins exist
TombstoneA delete is a new write that hides older dataDeletes cost space and read time until compaction
CompactionBackground merge of immutable SSTablesKeeps reads fast and reclaims space; costs IO
RepairAnti-entropy sync of replicas with Merkle treesThe only thing that guarantees convergence

Consistency levels with RF=3 (one datacenter).

LevelReplicas that must answerSurvives down replicasTypical use
ANY (writes only)1, or a stored hint3 of 3Logging where loss is acceptable
ONE / LOCAL_ONE12Fast reads of data that may be a bit stale
TWO / THREE2 / 31 / 0Rare
QUORUM / LOCAL_QUORUM21Default for reads and writes you care about
ALL30Almost never in production
SERIAL / LOCAL_SERIALPaxos quorum1Reads that must see committed LWT state

Four rules that prevent 90% of incidents.

RuleReason
Model one table per query, and keep every partition under about 100 MB and 100,000 rowsWide partitions cause GC pressure (Cassandra), slow reads, and repair problems
Never use Cassandra as a queue, and never delete in a hot loopTombstones make reads slower until gc_grace_seconds and compaction clear them
Run repair on every node at least once per gc_grace_seconds (default 10 days)Otherwise deleted data can come back (zombies)
Use LOCAL_QUORUM for reads and writes with a real NetworkTopologyStrategy keyspaceStrong enough for read-your-writes in a datacenter, no cross-region latency

Why Cassandra exists ​

A relational database keeps one authoritative copy and makes that one machine faster and safer: bigger disks, a replica for failover, maybe sharding by hand. That works until the write rate or the data size no longer fits one primary, or until "the primary is down for 30 seconds during failover" is not acceptable. Cassandra starts from the opposite assumption, taken from Amazon's Dynamo: components fail all the time, so every partition has several equal replicas and any of them can accept a write. The paper's own words: at this scale "small and large components fail continuously". The price is that you must model your data around the questions you will ask, and that you must think about consistency on every call.

Single-primary relational (PostgreSQL, MySQL)Masterless wide-column (Cassandra, ScyllaDB)
One writer per shard; failover is an eventAny replica takes the write; no failover event
Joins, constraints, multi-row transactionsNo joins, no foreign keys, partition-local atomicity only
Flexible queries on any column (with indexes)Fast queries only along the primary key (plus SAI filters)
Strong consistency by defaultTunable per statement; eventual by default at low levels
Scale up first, shard later (hard)Scale out by adding nodes (the ring rebalances)
Normalise; one place per factDenormalise; one table per query; duplicate on write

An everyday picture. Think of a library with three branches that each hold a copy of every book. You can borrow from any branch, and when a branch is closed you simply go to another one. If you want to be sure that you read the latest edition, you ask two of the three branches and trust the newer one. Occasionally a librarian walks between branches comparing shelves (repair). The catch: the catalogue is organised by the questions readers ask, not by author, so the same book may appear in several catalogues.

Three common misunderstandings, up front ​

BeliefReality
"Cassandra is eventually consistent, so it can lose my writes"An acknowledged write at QUORUM is durable on a majority; with QUORUM reads and writes you read your own writes. Weak guarantees come from low levels (ONE, ANY) and from skipping repair
"NoSQL means no schema"CQL tables have a strict schema (typed columns, primary key). Adding a column is a metadata change, but the key cannot be changed afterwards
"I can add an index and query anything"The primary key defines the cheap queries. Indexes (SAI) help filtering but do not replace modeling, and ALLOW FILTERING scans

Where it comes from ​

Cassandra was built at Facebook for Inbox Search. The paper says the system "was launched in June of 2008 for around 100 million users" and that before launch they indexed "7TB of inbox data for over 100M users". It combines two designs the authors name: Amazon's Dynamo for the distribution layer (partitioning, replication, membership by gossip, failure detection) and Google's Bigtable for the data model and storage (column families, commit log, memtable, SSTable). The paper is short, six pages in the LADIS 2009 version; it describes consistent hashing, an accrual failure detector, and the commit log, memtable and SSTable write path that is still the core today.

Since then the project changed a lot; the Apache documentation (read for this page, version 5.0 tree) summarises what stayed: "Dataset partitioning using consistent hashing", "Multi-master replication using versioned data and tunable consistency", gossip-based membership, and incremental scale-out on commodity hardware. What changed is the user-visible layer: CQL replaced the Thrift API, vnodes replaced single tokens, a deterministic token allocator replaced random tokens, and Cassandra 5.0 added Storage-Attached Indexes (SAI), the Unified Compaction Strategy (UCS), trie-based SSTables (BTI) and a vector type with ANN search. Transactions across partitions come through Accord, which the project's CHANGES.txt first lists in the 6.0-alpha1 section (the 5.0 branch has no Accord entry), so it is not part of 5.0.

EraWhat it broughtWhy you may meet it
Paper, 2009Dynamo ring plus Bigtable storageThe vocabulary: commit log, memtable, SSTable, gossip
2.xRandom tokens, 256 vnodes per node by defaultOld clusters still run num_tokens: 256
3.xDeterministic token allocator, materialized views, me/md SSTablesMV problems are why they are off by default now
4.0Audit logging, transient replication (experimental), read_repair table optionMost production clusters today
5.0SAI, UCS, BTI trie index, vector type, num_tokens: 16 default with the allocatorNew clusters; the docker image used in the lab is 5.0.9
6.0 lineAccord transactions: CHANGES.txt lists "General Purpose Transactions (Accord) [CEP-15]" in the 6.0-alpha1 section, none in the 5.0 branchCross-partition transactions; not for 5.0
ScyllaDBA C++ rewrite on Seastar: shard-per-core, no JVMSame CQL, same drivers, much higher per-node throughput

The Apache documentation states the stance plainly: "Cassandra chooses Availability and Partition Tolerance from the CAP guarantees, compromising on data Consistency to some extent." — Apache Cassandra documentation, Guarantees

Cluster concepts ​

N1R1N2R2N3R3 downN4coord.N5N6hash(key) = tokentoken ringwalk clockwise,take 3 distinct nodesClientRF = 3, QUORUM readQUORUM = floor(RF / 2) + 1 = 2data request to R1 (fastest)digest request to R22 of 3 answered: digests matchR3 is down, read still succeedsW + R > RFQUORUM write + QUORUM read:2 + 2 > 3, sets always overlap1 requestdatadigestno answer

The picture shows a QUORUM read: a key hashed to a token, the next three distinct nodes clockwise as replicas, a coordinator that asks one replica for the data and another for a digest, and one replica that is down. The write that preceded it went to all three replicas and waited for two answers. Every concept in this section is a part of that picture.

Masterless ring and tokens Must-know ​

In plain words: Cassandra hashes the partition key to a number (a token) and places that number on a circle. Each node owns slices of the circle, and the node that owns the token, plus the next nodes clockwise, hold the copies.

Common misunderstanding: "There is a leader somewhere, or the seed node is the leader." There is none. A seed node only helps new nodes find the cluster by gossip. Any node you connect to becomes the coordinator for that one request and then forgets it.

Definition: the partitioner (Murmur3Partitioner, the default) maps a partition key to a 64-bit token between -2^63 and 2^63-1. A token range is owned by the node holding the token at its upper end; replicas are found by "walking" the ring clockwise until the replication strategy has chosen RF distinct nodes. The Apache documentation words it this way: ranges of keys, also known as token ranges, "map to the same physical set of nodes".

text
Request path for  INSERT ... WHERE id = 7   (RF=3, QUORUM)
1  client driver (token aware) hashes id=7 -> token 6120565781388772718
2  driver picks a replica as coordinator, or any node if it is not token aware
3  coordinator looks up the token map: owners = N2, N3, N4 (clockwise)
4  coordinator sends the mutation to all three owners in parallel
5  N2 and N4 answer; coordinator has 2 of 3 -> acknowledges the client
6  N3 answers later, or a hint is stored if it is down

Real scenario: adding the fourth node to a three-node ring. The new node picks tokens, then streams exactly the ranges it now owns; the other nodes keep serving. Nothing else moves, which is the whole point of consistent hashing (see Consistent Hashing for the generic algorithm and why hash mod N fails).

ProductHow data is placed
CassandraToken ring, Murmur3Partitioner, vnodes (default num_tokens: 16 in 5.0 docker config)
ScyllaDBSame ring by default for vnode keyspaces; tablets (default for new keyspaces) split tables into movable ranges
DynamoDBHidden partitions by hash of the partition key; you do not see tokens
MongoDBChunks of a shard key range (or hashed shard key) on shards with config servers and a router
Redis Cluster16,384 hash slots assigned to primaries
PostgreSQL, MySQLNo built-in placement; you shard by hand or with Citus/Vitess
sql
-- Which nodes own this key? (shell command, not CQL)
-- nodetool getendpoints shop profile_by_id 6cd8e6a4-8a2b-11f1-9c3e-0242ac110002
-- The token CQL computed for a row:
SELECT token(id), id FROM shop.profile_by_id LIMIT 3;

Virtual nodes (vnodes) and token allocation Important ​

In plain words: instead of one slice of the circle per machine, every machine owns many small slices. When a machine joins or leaves, it takes data from, or hands it to, many neighbours at once.

Common misunderstanding: "More vnodes is always better balanced." The documentation says the opposite after a point: "Every token introduces up to 2 * (RF - 1) additional neighbors on the token ring", so more tokens mean more combinations of node failures that make part of the ring unavailable, and slower repairs. The 2.x default of 256 came from random token choice; since 3.x the deterministic allocator achieves balance with far fewer.

Definition: a token is one position on the ring, an endpoint is one IP and port, a host ID identifies one physical node, and a vnode is a token owned by that host. num_tokens sets how many tokens a node takes; with allocate_tokens_for_local_replication_factor: 3 the allocator picks tokens that balance the ring for RF=3. The cassandra.yaml in the 5.0 docker image used in the lab shows num_tokens: 16.

SettingEffect
num_tokens: 256 (legacy)Smooth balance with random tokens; many neighbours; slow repair; more unavailability combinations
num_tokens: 16 with the allocator (5.0 image default)Good balance with fewer neighbours; recommended for new clusters
num_tokens: 1Manual token assignment; hard to scale in small steps
ScyllaDB tabletsNo num_tokens per table; the load balancer moves tablets (see ScyllaDB differences)

Timeline: a node joins.

text
1  N5 starts with auto_bootstrap=true and contacts a seed
2  N5 gossips its state: JOINING, with its chosen tokens
3  N5 streams the ranges it will own from the current replicas (RF=3: each range has 3 sources)
4  N5 becomes NORMAL (UN); the previous owners still hold stale data
5  operator runs  nodetool cleanup  on the old owners to drop ranges they no longer own

Gossip, failure detector and seeds Important ​

In plain words: nodes chat with each other every second about who is in the cluster and whether they are alive. There is no central registry.

Common misunderstanding: "A node being DOWN in nodetool status means the cluster has removed it." UP and DOWN are local opinions of each node, not propagated cluster state. A node is only removed by an operator (decommission, removenode, or a replacement); the documentation says this is deliberate "to allow Cassandra nodes to temporarily fail without causing data to needlessly re-balance".

Definition: every second, every node updates its own heartbeat, gossips with one random node, probabilistically with an unreachable one, and with a seed if needed. State is versioned by (generation, version). The failure detector is a variant of the Phi Accrual Failure Detector: it "convicts" a peer when its heartbeat stops increasing for long enough, after which reads stop being routed to it and writes become hints. Gossip also carries token ownership and the schema version.

ItemDetail
Seed nodesOnly a bootstrap contact; choose two or three per datacenter; not special at runtime except as gossip hot spots
nodetool gossipinfoRaw state of every endpoint: generation, heartbeat, DC, RACK, RELEASE_VERSION, HOST_ID, LOAD
nodetool statusUN up/normal, DN down/normal, UJ joining, UL leaving, UM moving
Schema disagreementnodetool describecluster shows schema versions; more than one means a node is behind
ScyllaDBSame gossip; topology and schema changes also go through Raft, so a quorum of nodes is needed to change them

Snitch and replica placement Important ​

In plain words: the snitch tells Cassandra which datacenter and rack each node is in, so replicas are spread across racks and requests prefer nearby nodes.

Common misunderstanding: "Rack awareness is free to enable." The documentation warns: with NetworkTopologyStrategy, a single node bootstrapped into a new rack becomes a replica for the entire ring, and an uneven node count per rack overloads the smallest rack. Many operators therefore treat a whole availability zone as one rack.

Definition: the snitch maps endpoints to (datacenter, rack). GossipingPropertyFileSnitch is the recommended production choice: each node declares its own DC and rack in cassandra-rackdc.properties and gossips it. Others: SimpleSnitch (single DC tests), PropertyFileSnitch (a topology file on every node), Ec2Snitch, Ec2MultiRegionSnitch, GoogleCloudSnitch, AzureSnitch, RackInferringSnitch. The dynamic snitch (dynamic_snitch_update_interval: 100ms) additionally steers reads away from slow replicas by recent latency.

SnitchUse when
GossipingPropertyFileSnitchDefault recommendation, on-prem or any cloud
Ec2Snitch, GoogleCloudSnitch, AzureSnitchYou want region = DC and zone = rack read from instance metadata
PropertyFileSnitchLegacy; every node needs the same topology file
SimpleSnitchOne datacenter, no racks, tests only

Replication factor and replication strategy Must-know ​

In plain words: the replication factor says how many copies exist; the replication strategy says where they go. Both are set per keyspace.

Common misunderstanding: "SimpleStrategy is fine because I only have one datacenter today." The documentation says "All production deployments should use the NetworkTopologyStrategy", even for one datacenter, "to make it easier to add new physical or virtual datacenters to the cluster later". SimpleStrategy ignores racks and datacenters.

Definition: NetworkTopologyStrategy takes an RF per datacenter and tries to place each replica in a different rack. RF=3 per datacenter is the common production choice. Raising RF later needs a full repair to copy data to the new replicas (Cassandra prints a warning: "When increasing replication factor you need to run a full (-full) repair").

sql
CREATE KEYSPACE shop
  WITH replication = {'class': 'NetworkTopologyStrategy', 'dc1': 3, 'dc2': 3}
  AND durable_writes = true;

-- Add a datacenter: change the keyspace, then stream data into it
ALTER KEYSPACE shop WITH replication =
  {'class': 'NetworkTopologyStrategy', 'dc1': 3, 'dc2': 3, 'dc3': 3};
-- on every node of dc3:  nodetool rebuild -- dc1
RF (per DC)QUORUM sizeReplicas that can be down at QUORUMNotes
110Tests only; no redundancy
220Pays double storage but QUORUM tolerates nothing; avoid
321Standard production setting
532Two failures tolerated; 5/3 storage overhead of RF=3

Transient replication (a subset of replicas that only keep unrepaired data, written as 3/1) exists in 4.0 and later as an experimental feature that "is not ready for production use" according to the documentation. Alternator tables on ScyllaDB use RF=3 on clusters of three or more nodes, and RF=1 on smaller ones.

Consistency levels and quorum math Must-know ​

In plain words: every statement states how many replicas must answer before you hear "OK". Write to a majority and read from a majority and the two groups must share at least one replica, so the read sees the write.

Common misunderstanding: "QUORUM writes go to only two replicas." Writes are always sent to all replicas; the consistency level only sets how many answers the coordinator waits for. The docs state: "Write operations are always sent to all replicas, regardless of consistency level." Reads, by contrast, are normally sent to just enough replicas (plus a digest request).

Definition: Dynamo's R + W > N rule: with replication factor RF, if write level W and read level R satisfy W + R > RF, the sets overlap and every acknowledged write is visible to a later read (barring clock problems). QUORUM is floor(RF / 2) + 1. In several datacenters, LOCAL_QUORUM counts only the coordinator's DC, EACH_QUORUM needs a quorum in every DC (writes only), and QUORUM counts all replicas across DCs, which pays cross-region latency.

text
RF=3; coordinator N4; replicas N1, N2, N3

Write QUORUM (2)                          Read QUORUM (2)
  N1  ack                                   N1  returns value v2 (timestamp t5)
  N2  ack                                   N3  returns value v1 (timestamp t3)   <- stale
  N3  (slow or down)                        coordinator picks t5, repairs N3
  W=2, R=2, W+R=4 > 3: overlap = N1 or N2  -> read sees v2
Write / read combination (RF=3)W + ROverlap guaranteedBehaviour
QUORUM / QUORUM4yesRead your writes; survives one down replica
ONE / ALL4yesWrites cheap, reads fail if any replica is down
ALL / ONE4yesWrites fail if any replica is down
ONE / ONE2noFastest and least available-consistent: stale reads happen
LOCAL_QUORUM / LOCAL_QUORUM (2 DCs)local 4within the DCRead your writes in one DC; remote DC lags by replication delay
ANY / ONE1 + 1noHint counts as success; data may be absent from all replicas for a while

The lab proves both sides on a real ring: with one node down ALL fails and QUORUM succeeds; with two down QUORUM fails with "Cannot achieve consistency level QUORUM" but ONE still works.

Fix / how to use it (Go). Set a default on the cluster config and override per statement; use LOCAL_QUORUM with a DC-aware, token-aware policy.

go
// Package main builds a production-shaped gocql session. It exits early when
// CASSANDRA_HOSTS is not set, so it compiles and runs without a cluster.
package main

import (
	"fmt"
	"os"
	"strings"
	"time"

	"github.com/gocql/gocql"
)

// NewSession returns a session that is token aware inside the local datacenter.
func NewSession(hosts []string, localDC string) (*gocql.Session, error) {
	cluster := gocql.NewCluster(hosts...)
	cluster.Keyspace = "shop"
	cluster.ProtoVersion = 4

	// LOCAL_QUORUM: a majority of the replicas in the coordinator's datacenter.
	cluster.Consistency = gocql.LocalQuorum
	// Serial consistency is only used by the Paxos phase of lightweight transactions.
	cluster.SerialConsistency = gocql.LocalSerial

	// Route each request to a replica that owns the partition, prefer the local DC.
	cluster.PoolConfig.HostSelectionPolicy = gocql.TokenAwareHostPolicy(
		gocql.DCAwareRoundRobinPolicy(localDC),
	)

	cluster.Timeout = 6 * time.Second        // per-request timeout, above read_request_timeout (5000ms)
	cluster.ConnectTimeout = 3 * time.Second // TCP + CQL startup handshake
	cluster.NumConns = 2                     // connections per host; the ScyllaDB fork opens one per shard instead
	cluster.PageSize = 500                   // rows per page when a partition is large

	// Retries are skipped for statements not marked Idempotent(true) (gocql v1.7.0 query_executor.go).
	cluster.RetryPolicy = &gocql.ExponentialBackoffRetryPolicy{
		NumRetries: 3,
		Min:        100 * time.Millisecond,
		Max:        2 * time.Second,
	}
	cluster.SocketKeepalive = 15 * time.Second

	return cluster.CreateSession()
}

func main() {
	raw := os.Getenv("CASSANDRA_HOSTS")
	if raw == "" {
		fmt.Println("set CASSANDRA_HOSTS=127.0.0.1 to connect; nothing to do")
		return
	}
	session, err := NewSession(strings.Split(raw, ","), "dc1")
	if err != nil {
		fmt.Fprintln(os.Stderr, "connect:", err)
		os.Exit(1)
	}
	defer session.Close()

	var release string
	if err := session.Query("SELECT release_version FROM system.local").Scan(&release); err != nil {
		fmt.Fprintln(os.Stderr, "query:", err)
		os.Exit(1)
	}
	fmt.Println("connected to Cassandra", release)
}
go
// Package main shows per-statement consistency levels and how to read the
// error types that tell you which side of the quorum failed.
package main

import (
	"context"
	"errors"
	"fmt"
	"os"
	"strings"
	"time"

	"github.com/gocql/gocql"
)

// WriteProfile stores a profile; the caller chooses the consistency level.
func WriteProfile(ctx context.Context, s *gocql.Session, cl gocql.Consistency, id gocql.UUID, name string) error {
	return s.Query(`INSERT INTO shop.profile_by_id (id, name, updated_at) VALUES (?, ?, ?)`,
		id, name, time.Now()).
		WithContext(ctx).
		Consistency(cl).
		Idempotent(true). // a plain INSERT with the same values is safe to retry
		Exec()
}

// ReadProfile reads one row at the chosen level.
func ReadProfile(ctx context.Context, s *gocql.Session, cl gocql.Consistency, id gocql.UUID) (string, error) {
	var name string
	err := s.Query(`SELECT name FROM shop.profile_by_id WHERE id = ?`, id).
		WithContext(ctx).
		Consistency(cl).
		Scan(&name)
	return name, err
}

// Classify turns driver errors into the action an operator or caller should take.
func Classify(err error) string {
	var unavailable *gocql.RequestErrUnavailable
	var wTimeout *gocql.RequestErrWriteTimeout
	var rTimeout *gocql.RequestErrReadTimeout
	switch {
	case err == nil:
		return "ok"
	case errors.Is(err, gocql.ErrNotFound):
		return "no such row"
	case errors.As(err, &unavailable):
		// The coordinator knew before trying that fewer than Required replicas were alive.
		return fmt.Sprintf("Unavailable: required=%d alive=%d, lower the level or fix the nodes",
			unavailable.Required, unavailable.Alive)
	case errors.As(err, &wTimeout):
		// The write may still have been applied on some replicas.
		return fmt.Sprintf("WriteTimeout: received=%d of blockfor=%d type=%s, outcome unknown, retry only if idempotent",
			wTimeout.Received, wTimeout.BlockFor, wTimeout.WriteType)
	case errors.As(err, &rTimeout):
		return fmt.Sprintf("ReadTimeout: received=%d of blockfor=%d dataPresent=%v",
			rTimeout.Received, rTimeout.BlockFor, rTimeout.DataPresent)
	default:
		return "other: " + err.Error()
	}
}

func main() {
	raw := os.Getenv("CASSANDRA_HOSTS")
	if raw == "" {
		fmt.Println("set CASSANDRA_HOSTS=127.0.0.1 to run the QUORUM / ONE experiment")
		return
	}
	cluster := gocql.NewCluster(strings.Split(raw, ",")...)
	cluster.Timeout = 3 * time.Second
	session, err := cluster.CreateSession()
	if err != nil {
		fmt.Fprintln(os.Stderr, "connect:", err)
		os.Exit(1)
	}
	defer session.Close()

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	id := gocql.TimeUUID()

	// W=QUORUM and R=QUORUM: 2 + 2 > 3, the read always overlaps the write.
	fmt.Println("write QUORUM:", Classify(WriteProfile(ctx, session, gocql.Quorum, id, "Ada")))
	name, err := ReadProfile(ctx, session, gocql.Quorum, id)
	fmt.Println("read QUORUM:", name, Classify(err))

	// W=ONE and R=ONE: 1 + 1 < 3, a stale read is possible until repair or read repair.
	fmt.Println("write ONE:", Classify(WriteProfile(ctx, session, gocql.One, id, "Ada L.")))
	name, err = ReadProfile(ctx, session, gocql.One, id)
	fmt.Println("read ONE:", name, Classify(err))
}

Timestamps, last-write-wins and clocks Important ​

In plain words: every cell is written with a timestamp, and when two replicas disagree the newer timestamp wins. There is no merge and no vector clock.

Common misunderstanding: "Two updates to different columns of the same row conflict." Each column of each row is versioned separately ("Cassandra applies separate mutation timestamps to every column of every row"), so concurrent updates to different columns both survive, and even set/map elements resolve independently.

Definition: Cassandra uses a last-write-wins element-set CRDT per CQL row. The timestamp is client-supplied (drivers add one by default) or comes from the coordinator's clock; deletes are timestamped too. "Cassandra's correctness does depend on these clocks", so NTP or chrony is mandatory; a node whose clock is hours ahead can write cells that nobody can overwrite until real time catches up. USING TIMESTAMP lets you set it yourself, and WRITETIME(col) reads it back.

sql
INSERT INTO shop.profile_by_id (id, name, version) VALUES (uuid(), 'Ada', 1) USING TIMESTAMP 1700000000000000;
SELECT name, WRITETIME(name), TTL(name) FROM shop.profile_by_id LIMIT 1;

Data path and repair ​

MutationCommit logappend-only, sharedMemtablesorted, in memoryper tableImmutable SSTable (one flush = one set of files)Filter.dbBloom filter of partition keysPartitions.db / Index.dbpartition key to offsetStatistics.dbmin/max timestamps, tombstones, TTLsCompressionInfo.dbchunk offsetsData.db: partitions in token orderPartition (customer 7) token = 3.1e18row ts=t9 total=40 | row ts=t8 total=15 | row ts=t3 total=8clustering order DESC: newest row first, one sequential readtombstonestatic column + partition header come firstPartition (customer 9) token = 5.4e18row ts=t7 total=99 | row ts=t2 total=12partitions are sorted by token, not by key valuea partition can span many SSTables until compaction merges themread = merge memtable + every SSTable that may hold the key1 append2 apply3 flush

The picture shows what a single node does with a mutation: append to the commit log, apply to the memtable, flush to an immutable SSTable whose data file is ordered by token, then by clustering key inside each partition.

The write path: commit log, memtable, SSTable Must-know ​

In plain words: a write is an append to a log file plus an insert into a sorted structure in memory. Nothing is read from disk and nothing is updated in place, which is why writes are so cheap.

Common misunderstanding: "An acknowledged write is on disk." With the default commitlog_sync: periodic and commitlog_sync_period: 10000ms the commit log is fsynced every ten seconds, so a power cut on a single node can lose up to that window on that node. Durability against single-node loss comes from replication (other replicas have it); commitlog_sync: batch waits for the fsync before acknowledging, at a latency cost.

Definition: the node (1) appends the mutation to the commit log (shared by all tables, segments of commitlog_segment_size: 32MiB), (2) applies it to the table's memtable, (3) when a threshold is reached flushes the memtable to a new immutable SSTable, and (4) lets compaction later merge SSTables. After a crash, the commit log is replayed into memtables. nodetool drain flushes everything before a planned stop, so restart needs no replay.

text
Write on one replica (periodic commit log sync)
1  mutation arrives: INSERT (stream='q', seq=7, body='x')
2  append to commit log segment (sequential, buffered, fsync every 10 s)
3  insert into memtable (sorted, in memory) -> ack to the coordinator
4  ... time passes, memtable reaches memtable_cleanup_threshold or commit log space limit ...
5  flush: write nb-12-big-Data.db, Index, Filter (Bloom), Statistics, ... as a new SSTable
6  commit log segments older than the flush are recycled

SSTable component files in Cassandra 5.0 (default big format; the BTI trie format replaces the index files with Partitions.db and Rows.db): Data.db (rows), Index.db (partition key to offset), Summary.db (every 128th index entry sampled), Filter.db (Bloom filter), CompressionInfo.db, Statistics.db (timestamps, tombstones, TTLs), Digest.crc32, TOC.txt, and SAI*.db if SAI is on. The lab lists the files of a real flush.

SettingDefault seen in 5.0What it controls
commitlog_syncperiodicperiodic or batch fsync mode
commitlog_sync_period10000msMaximum fsync gap in periodic mode
commitlog_segment_size32MiBSegment size; max_mutation_size is half of it
memtable_allocation_typeheap_buffersOn-heap or off-heap memtable memory
concurrent_writes / concurrent_reads32 / 32Stage thread counts
durable_writes (keyspace)trueSetting false skips the commit log; never do it for real data

The read path: memtable, Bloom filter, SSTables Must-know ​

In plain words: to read a partition, a replica merges the memtable with every SSTable that might hold the key. A small Bloom filter in memory says "definitely not here" for most SSTables.

Common misunderstanding: "Reads are as fast as writes." Reads are the expensive side of an LSM engine: the more SSTables a partition spans, and the more tombstones it has to skip, the slower the read. Compaction exists to keep that number small.

Definition: for each candidate SSTable the replica consults the Bloom filter (bloom_filter_fp_chance default 0.01), then the key cache and partition index (or the BTI trie in 5.0), then the compression chunk, then merges the rows from all sources by timestamp and drops anything shadowed by a tombstone. The coordinator asks one replica for data and others for digests; a digest mismatch triggers read repair. nodetool tablestats keyspace.table shows SSTable count, Bloom filter false positives, partition size and average tombstones per slice.

text
Read QUORUM of one partition, RF=3
1  coordinator sends a data request to the fastest replica (dynamic snitch)
2  coordinator sends digest requests to a second replica
3  each replica: memtable + [Bloom -> index -> data] for each SSTable, then merge
4  digests equal: return data to the client
5  digests differ: ask for full data from both, pick newest per cell, write the winner back
   to the stale replica (blocking read repair), then return

Hinted handoff Important ​

In plain words: when a replica is down during a write, the coordinator keeps a note and delivers the write when the replica comes back.

Common misunderstanding: "Hints make repair unnecessary." The documentation is explicit that "Hints are best effort, however, and do not guarantee eventual consistency like anti-entropy repair does." Hints are kept only for max_hint_window (3 hours default); a node down for longer misses data until repair.

Definition: the coordinator stores the mutation in its hints directory with the original timestamp, so replay is idempotent. Hints are also written for writes that time out. hinted_handoff_throttle (1024KiB) is deliberately conservative: a 10-minute restart at 100 Mbps of ingest produces about 7 GiB of hints that take around 2 hours to deliver at the default throttle, so raise it at runtime with nodetool sethintedhandoffthrottlekb. Consistency level ANY counts a stored hint as success.

text
t0  client write at LOCAL_QUORUM, RF=3; replica_2 is restarting
t1  replicas 1 and 3 ack -> coordinator acks the client (durable and visible)
t2  after write_request_timeout (2000ms) the coordinator stores a hint for replica_2
t3  replica_2 starts, gossips UP
t4  the coordinator replays the hint to replica_2 (rate limited)

Read repair and speculative retry Important ​

In plain words: when a read finds replicas that disagree, Cassandra fixes the stale ones with the newest value before answering.

Common misunderstanding: "Read repair happens on every read, so repair is unnecessary." It only touches the rows a query covers, only when replicas that took part disagree, and rarely-read data is never repaired this way. The docs call it a best-effort technique next to hints; guaranteed convergence needs anti-entropy repair.

Definition: the read_repair table option is BLOCKING (default) or NONE. BLOCKING gives "monotonic quorum reads" (a second quorum read never goes back in time) by blocking the read until the repair writes reach the consistency level; NONE gives partition-level write atomicity but allows reads to go back in time. speculative_retry (default 99PERCENTILE, also written 99p) lets the coordinator send a redundant read to another replica if the first is slower than the 99th percentile, cutting tail latency. The lab shows a stale ONE read return nothing, a QUORUM read repairing it, and the next ONE read returning the value.

sql
ALTER TABLE shop.profile_by_id WITH read_repair = 'BLOCKING' AND speculative_retry = '99p';

Anti-entropy repair Must-know ​

In plain words: repair is the housekeeper that compares replicas and copies whatever is missing. It is not automatic; you schedule it.

Common misunderstanding: "Incremental repair makes full repair obsolete." The docs say incremental repair, once it marks data as repaired, never looks at it again, so it "doesn't protect against things like disk corruption, data loss by operator error, or bugs in Cassandra", and recommend an occasional full repair.

Definition: replicas compute Merkle trees (hash trees) over their data for a token range, compare them, and stream the differing sections. Full repair covers all data in the range; incremental repair (the default; CHANGES.txt records "Make incremental repair default" in 2.2.0-beta1) only repairs data written since the last incremental repair, tracked by moving SSTables between "repaired" and "unrepaired" sets (anticompaction). nodetool repair -pr repairs only the node's primary ranges so running it on every node does not repeat work; --full forces full repair; -prv previews streaming; -vd validates repaired data. Subrange repair splits ranges into smaller pieces for finer trees and bounded work.

TaskCommandNotes
Incremental repair of the primary rangesnodetool repair -pr shopRun on each node in turn
Full repair after raising RF or adding a DCnodetool repair -full shopStreams SSTables
Estimate the worknodetool repair -prv shopBuilds trees, prints expected streaming, no streaming
Check repaired data matchesnodetool repair -vd shopTroubleshooting; if it differs, run a full repair
Schedule itCassandra Reaper (also bundled in K8ssandra)Orchestrates subrange repairs with pause and resume

The schedule rule from the documentation: at minimum, repair often enough that gc_grace_seconds never expires on unrepaired data; with the default ten days, "repairing every node in your cluster at least once every 7 days" leaves slack. A starting point: incremental every 1 to 3 days, full every 1 to 3 weeks. Cassandra Reaper is the open-source scheduler for this; ScyllaDB uses ScyllaDB Manager for the same job.

Data modeling ​

Partition key, clustering columns and the primary key Must-know ​

In plain words: the first part of the primary key chooses the node (the partition), the rest sorts the rows inside it. Think of one partition as one sorted file that lives on three machines.

Common misunderstanding: "The primary key is just a uniqueness rule like in SQL." Here it is a physical layout. PRIMARY KEY (id, c) means partition key id, clustering column c; PRIMARY KEY ((id1, id2), c1, c2) means a composite partition key (id1, id2) and clustering columns c1, c2. You cannot change it after creation, and you can only query by restricting the partition key fully and then the clustering columns in order.

Definition: the partition key is hashed to a token. Within a partition, rows are stored in clustering order, which CLUSTERING ORDER BY sets (ascending or descending per column). A query must give all partition key columns with = or IN; clustering columns may then be restricted left to right, with at most one range. The Apache documentation: "Data is modeled around specific queries. Queries are best designed to access a single table".

sql
CREATE TABLE shop.orders_by_customer (
  customer_id uuid,
  order_ts    timeuuid,
  order_id    uuid,
  total_cents bigint,
  status      text,
  PRIMARY KEY ((customer_id), order_ts)
) WITH CLUSTERING ORDER BY (order_ts DESC);

-- good: one partition, newest first, bounded
SELECT * FROM shop.orders_by_customer WHERE customer_id = ? LIMIT 20;
-- good: range on the clustering column
SELECT * FROM shop.orders_by_customer WHERE customer_id = ? AND order_ts > minTimeuuid('2026-11-01') ;
-- rejected: no partition key (would scan the cluster)
SELECT * FROM shop.orders_by_customer WHERE status = 'paid';
-- InvalidRequest: Cannot execute this query as it might involve data filtering and thus may have unpredictable performance...
Query shapeAllowed?Cost
Full partition key =, clustering rangeYesOne replica set, sequential read
Partition key IN (a, b, c)Yes, butCoordinator fans out; keep the list small (3 to 10)
Clustering column without partition keyNoNeeds ALLOW FILTERING (scan) or an index
Partition key range (token(id) > x)Yes, for scans and exportsWalks the ring; use for batch jobs only
ORDER BY other than clustering orderNoModel another table
COUNT(*) on a large partition or tablePossible, avoidReads every row; keep counters yourself

Query-first design and one table per query Must-know ​

In plain words: you start from the screens and API calls of your application, list the queries, and give each query its own table with exactly the key it needs. If two queries need different keys, you store the data twice.

Common misunderstanding: "Duplicating data is a design flaw." Here it is the design. The docs: "Since each query is backed by a table, data is duplicated across multiple tables in a process known as denormalization. Data duplication and a high write throughput are used to achieve a high read performance." Storage is cheap and writes are cheap; joins across nodes are neither.

Definition: process: (1) list entities and relationships, (2) list application queries with their filters and ordering, (3) pick partition and clustering keys per query, (4) check partition size, (5) write each event to every table that serves a query, in application code or with a logged batch.

text
Queries (a small shop)
Q1  get a customer by id                       -> customers_by_id          PK (customer_id)
Q2  log in by e-mail                           -> customers_by_email       PK (email)
Q3  last 20 orders of a customer               -> orders_by_customer       PK ((customer_id), order_ts DESC)
Q4  all items of an order                      -> items_by_order           PK ((order_id), line_no)
Q5  orders placed per day, for the ops team    -> orders_by_day            PK ((day), order_ts)   <- hot partition risk, bucket it
One order is written to Q3, Q4 and Q5 tables; that is the "one table per query" rule.
Relational habitCassandra replacement
Foreign key and JOINCopy the needed columns into the query table
WHERE status = 'paid' on any columnA table keyed by status (with a bucket) or an SAI index
Normalised lookup tableA second table with the other key, kept in sync by the app
ORDER BY created_at DESC LIMIT 20Clustering column created_at DESC
Auto-increment iduuid, timeuuid, or an application-generated id (see ID Generation at Scale)

Partition size limits Must-know ​

In plain words: one partition lives wholly on its replicas, so a huge partition makes those three nodes work harder than the others and slows everything that touches it.

Common misunderstanding: "Cassandra can store 2 billion cells per partition, so that is the limit." That is a hard ceiling, not a design target. The practical guidance is to keep a partition under about 100 MB and roughly 100,000 rows; past that, reads, compaction, repair, streaming and (on Cassandra) garbage collection all degrade.

Definition: estimate the size before you ship: rows per partition x bytes per row. If it is unbounded (time series, a chat room, an audit log per tenant), add a bucket to the partition key (a day, a month, a hash modulo N). nodetool tablehistograms and nodetool tablestats show partition size percentiles and the largest compacted partition; compaction logs warn when it writes a large partition (the guardrail partition_size_warn_threshold, which replaces the deprecated compaction_large_partition_warning_threshold; both are unset in the 5.0 yaml).

sql
-- unbounded: all messages of a room in one partition
PRIMARY KEY ((room_id), sent_at)
-- bounded: one partition per room per month
PRIMARY KEY ((room_id, month), sent_at)
SymptomLikely causeFix
Writing large partition in the compaction logUnbounded partitionAdd a time or hash bucket
One node hot in nodetool tpstatsHot partition (one key gets all traffic)Salt the key: (key, salt) with salt 0..N-1 and fan out reads
Slow reads that grow over timePartition grows without boundBucket and TTL
Tombstone warnings on one partitionQueue-like delete patternSee tombstones

Static columns, collections and user-defined types Important ​

In plain words: a static column is stored once per partition instead of once per row; collections (set, list, map) hold a few values in one cell; a user-defined type bundles fields.

Common misunderstanding: "Collections are a way to store lists of children." A collection is read and written as a whole cell group, is not meant to exceed a few dozen elements, and (non-frozen) generates tombstones when you overwrite it. Child rows belong in clustering rows.

Definition: STATIC columns share one value across all rows of a partition (a customer name above the order rows). set<T>, list<T>, map<K,V>: sets and maps resolve concurrent updates per element by last-write-wins; lists are positional and have read-before-write hazards, so avoid them for anything concurrent. FROZEN<...> makes a collection or UDT one opaque value, replaced entirely. User-defined types group named, typed fields (CREATE TYPE address (...)). A tuple is an unnamed frozen group. Column types to know: text, int, bigint, varint, decimal, double, boolean, uuid, timeuuid, timestamp, date, time, duration, inet, blob, counter, and from 5.0 vector<float, N>.

sql
CREATE TYPE shop.address (street text, city text, zip text);
CREATE TABLE shop.customer_profile (
  customer_id uuid PRIMARY KEY,
  emails      set<text>,
  prefs       map<text, text>,
  home        FROZEN<address>
);
UPDATE shop.customer_profile SET emails = emails + {'ada@example.com'} WHERE customer_id = ?;
UPDATE shop.customer_profile SET prefs['theme'] = 'dark' WHERE customer_id = ?;
-- overwriting a whole non-frozen collection writes a range tombstone first:
UPDATE shop.customer_profile SET emails = {'new@example.com'} WHERE customer_id = ?;

Materialized views and why to be careful Important ​

In plain words: a materialized view is a table Cassandra keeps in sync with another table for you, with a different primary key.

Common misunderstanding: "A materialized view is the supported way to avoid writing several tables by hand." The syntax is there, but Cassandra 5.0 ships with materialized_views_enabled: false in cassandra.yaml (confirmed in the lab image), the project documents restrictions (the view may only select base columns, no static columns, and every view key column must be IS NOT NULL), and views have a history of going out of sync under failure and costing a read-before-write on every base update. Most teams that tried them write the extra tables themselves or use SAI instead.

Definition: CREATE MATERIALIZED VIEW name AS SELECT ... FROM base WHERE col IS NOT NULL AND ... PRIMARY KEY (...). Updates to the base table generate view updates; the view cannot be written directly; the initial build is single-threaded unless concurrent_materialized_view_builders is raised. ScyllaDB supports materialized views and uses them for global secondary indexes, but still requires care with tablets: the docs say a tablets keyspace containing a materialized view or secondary index has limitations (read the current limitations list before enabling).

OptionWhenRisk
Hand-written second table plus logged batchDefault; you control keys and failuresMore application code
SAI index (Cassandra 5.0)Filtering on a few columns inside a tableNot a substitute for modeling
Materialized viewYou accept the documented restrictions and test failure recoveryDivergence, repair cost, disabled by default in 5.0
ScyllaDB global secondary indexYou are on ScyllaDB and need lookup by non-key columnBacked by an MV; adds write and read cost

Deletes and tombstones ​

Tombstones, TTL and gc_grace_seconds Must-know ​

In plain words: you cannot erase a value from a file that never changes, so a delete writes a marker saying "everything older than this is gone". The marker stays for ten days by default, then compaction drops it.

Common misunderstanding: "DELETE frees space and makes reads faster." The opposite, at first: the delete adds data (a tombstone), and each read must scan past the tombstones in its range. The docs' own rule: Cassandra "treats a deletion as an insertion". Space comes back only when compaction merges the tombstone with the data it covers after the grace period.

Definition: tombstone kinds: cell tombstone (one column), row tombstone, range tombstone (a clustering range, also produced by overwriting a non-frozen collection), partition tombstone. A TTL (USING TTL n, or table default_time_to_live) turns an expired cell into a tombstone at expiry. gc_grace_seconds (default 864000, ten days) is how long a tombstone is kept so that a replica that missed it can still receive it through repair. Drop conditions: older than the grace period and, in the compaction, every SSTable that might hold older data for that partition is included (otherwise the old data would be resurrected). tombstone_warn_threshold: 1000 logs a warning and tombstone_failure_threshold: 100000 aborts the query.

text
Zombie data: a delete that is repaired away
1  RF=3, value A on N1 N2 N3
2  N3 is down; DELETE A at QUORUM -> tombstone on N1 and N2  (N3 still has A)
3  gc_grace_seconds (10 days) passes; compaction drops the tombstone on N1 and N2
4  N3 comes back and was never repaired: it still holds A, nobody holds the tombstone
5  repair (or a QUORUM read) copies A from N3 to N1 and N2 -> the deleted row is back
Fix: repair every node at least once per gc_grace_seconds, so N3 receives the tombstone first.
Cause of tombstonesWhy it hurtsWhat to do
Using a table as a queue (insert, read, delete)Reads scan the dead range at the head of the partitionDo not use Cassandra as a queue; use a broker (see Message Acknowledgment)
Explicit NULL insertsEach null writes a cell tombstoneOmit the column, or use unset values in the driver
Overwriting a non-frozen collectionRange tombstone per overwriteUse FROZEN, or add and remove single elements
Lots of short TTLs in a normal tableTombstones until compaction and gc_grace_seconds passUse TWCS and time buckets so whole SSTables expire
Deleting a whole partition row by rowOne tombstone per rowDELETE FROM t WHERE pk = ? writes a single partition tombstone
sql
-- good: one partition tombstone
DELETE FROM lab.events WHERE stream = 'q';
-- tombstone-heavy: one per row
DELETE FROM lab.events WHERE stream = 'q' AND seq = 7;
-- per-row TTL
INSERT INTO lab.events (stream, seq, body) VALUES ('q', 1, 'x') USING TTL 3600;
-- table default
ALTER TABLE lab.events WITH default_time_to_live = 86400;

Fully expired SSTables (all tombstones, shadowing nothing) are dropped whole; sstableexpiredblockers lists the SSTables that block this, and with TWCS unsafe_aggressive_sstable_expiration removes the check. The lab produces the warning Read 1 live rows and 1500 tombstone cells for query ... (see tombstone_warn_threshold).

Concurrency and atomicity ​

Lightweight transactions: Paxos, IF, SERIAL Important ​

In plain words: an IF NOT EXISTS or IF col = x statement makes Cassandra run a mini consensus among the replicas of that one partition, so only one competing writer wins.

Common misunderstanding: "LWT gives me transactions." It is a compare-and-set on a single partition. There is no multi-row, cross-partition atomicity, and it costs about four round trips, so keep it for the few operations that need uniqueness or a version check. The docs: Cassandra supports "single partition compare and swap functionality via the lightweight transaction CQL API".

Definition: a conditional statement runs the Paxos phases (prepare/promise, read, propose/accept, commit) among the partition's replicas. SERIAL (or LOCAL_SERIAL) is the serial consistency level for the Paxos part and for linearizable reads; the statement's ordinary consistency level applies to the commit. Result: an [applied] boolean and, when not applied, the current row. A timeout returns an unknown outcome (the proposal may still have been accepted), so read back at SERIAL before retrying. Concurrent LWTs on the same partition contend and can fail with CasWriteTimeout or be slow (cas_contention_timeout: 1000ms). cassandra.yaml offers paxos_variant: v2 (a faster Paxos implementation; the 5.0 file ships v1 and documents a migration procedure to v2 with rolling restarts).

sql
INSERT INTO shop.username_claims (username, owner_id) VALUES ('ada', 5f1d...) IF NOT EXISTS;
-- [applied] = True  (or False plus the existing row)
UPDATE shop.profile_by_id SET name = 'Ada L.', version = 2 WHERE id = ? IF version = 1;
SERIAL CONSISTENCY LOCAL_SERIAL;   -- cqlsh command; drivers set it per statement
text
Two sign-ups for the same username, RF=3
T1  INSERT ... IF NOT EXISTS (ada, user A)         T2  INSERT ... IF NOT EXISTS (ada, user B)
1   prepare ballot b1 -> majority promises
2                                                  prepare ballot b2 > b1 -> majority promises
3   propose b1 -> rejected (promised b2)
4                                                  read current value: none; propose b2 -> accepted; commit
5   retries with b3: reads (ada, B): [applied]=false, returns owner B

Product behaviour. ScyllaDB implements LWT too (the compatibility page footnotes SERIAL/LOCAL_SERIAL as "See ScyllaDB LWT") and its Alternator layer uses LWT for every write by default (tunable with alternator_write_isolation). Cross-partition transactions come with Accord (next section). PostgreSQL, MySQL/InnoDB, SQL Server and CockroachDB give you interactive multi-statement transactions; MongoDB has multi-document transactions; Redis has MULTI/EXEC and Lua; none of that exists in Cassandra 5.0.

Accord and transactional Cassandra Good to know ​

In plain words: Accord is a newer consensus protocol that lets Cassandra run transactions across several partitions (and tables), with serializable isolation.

Common misunderstanding: "Cassandra 5.0 has multi-partition transactions." It does not. Accord (CEP-15) first appears in the 6.0-alpha1 section of the project's CHANGES.txt as "General Purpose Transactions (Accord) [CEP-15] (CASSANDRA-17092)", and a later entry reads "Add support for BEGIN TRANSACTION to allow mutations that touch multiple partitions"; the 5.0 branch CHANGES.txt has no Accord entry and the 5.0 docs describe only single-partition LWT. Some descriptions say "Accord in 5.x"; the sources read here place it in 6.0. Check the release notes of the version you run before designing around it.

Definition: with Accord, tables opt in to a transactional mode and a BEGIN TRANSACTION block groups reads and conditional writes that may touch several partitions; the exact syntax is defined by the release that ships it, so read that release's CQL reference. It replaces Paxos for those tables; non-transactional tables behave as before. Until you run it, keep one rule: if a business invariant spans two partitions, redesign so it lives in one, or use a saga (see Saga Pattern).

NeedCassandra 5.0ScyllaDBAlternative
Unique key claimLWT IF NOT EXISTSLWTUnique index in PostgreSQL
Compare-and-set on one rowLWT IF col = xLWTVersion column in any SQL database (see Optimistic vs Pessimistic Locking)
Transfer between two accountsNot availableNot availableSaga, outbox, or a SQL database for the ledger
Many rows in one partition atomicallySingle-partition batchSameSame

Batches: logged, unlogged and their misuse Must-know ​

In plain words: a batch is a way to keep several writes together, not a way to make writes faster.

Common misunderstanding: "I will batch 1,000 inserts for speed like in SQL." A multi-partition batch makes one coordinator carry all 1,000 writes and wait for every replica set, so it is slower, creates hot coordinators and trips the size limits. The driver README and the docs agree on the right tool for speed: many independent async writes, token aware.

Definition: a LOGGED batch (the default BEGIN BATCH) first writes the batch to the batchlog on two other nodes, so if the coordinator dies the remaining statements are still applied; it guarantees "all or none eventually", but not isolation, and costs roughly double the writes. UNLOGGED skips the batchlog: no atomicity across partitions, but fine and efficient when every statement hits the same partition (then it is one mutation). COUNTER batches update counters. Size limits: batch_size_warn_threshold: 5KiB, batch_size_fail_threshold: 50KiB in the 5.0 config; the guarantees page promises that "Batched writes across multiple tables are guaranteed to succeed completely or not at all".

Batch shapeAtomicFasterUse
Logged, several tables, same logical entityYes (eventually all)NoKeep denormalised copies in sync
Unlogged, one partitionYes (single mutation)YesInsert many rows of one partition (time-series bucket)
Unlogged, many partitionsNoNo, slowerNever; send separate async writes
Conditional (with IF)Yes, one partition onlyNoRare
go
// Package main contrasts the two honest uses of a batch with the misuse.
package main

import (
	"context"
	"fmt"
	"os"
	"strings"

	"github.com/gocql/gocql"
)

// CreateUser writes the same user into two query tables atomically.
// A LOGGED batch goes through the batchlog on two other nodes first, so if the
// coordinator dies the remaining statements are still applied. It is atomic,
// not isolated, and slower than two separate writes: use it for denormalised
// copies that must not diverge, never for throughput.
func CreateUser(ctx context.Context, s *gocql.Session, id gocql.UUID, email, name string) error {
	b := s.NewBatch(gocql.LoggedBatch).WithContext(ctx)
	b.Query(`INSERT INTO shop.user_by_id (id, email, name) VALUES (?, ?, ?)`, id, email, name)
	b.Query(`INSERT INTO shop.user_by_email (email, id, name) VALUES (?, ?, ?)`, email, id, name)
	return s.ExecuteBatch(b)
}

// BadBulkLoad is the classic misuse: thousands of rows in different partitions
// in one batch make the coordinator a bottleneck. The server warns at
// batch_size_warn_threshold (5 KiB by default) and rejects at batch_size_fail_threshold (50 KiB).
func BadBulkLoad(ctx context.Context, s *gocql.Session, ids []gocql.UUID) error {
	b := s.NewBatch(gocql.UnloggedBatch).WithContext(ctx)
	for _, id := range ids {
		b.Query(`INSERT INTO shop.user_by_id (id, email, name) VALUES (?, ?, ?)`, id, "x@example.com", "x")
	}
	return s.ExecuteBatch(b)
}

// GoodBulkLoad sends independent prepared statements concurrently; the
// token-aware driver sends each one straight to a replica of its own partition.
func GoodBulkLoad(ctx context.Context, s *gocql.Session, ids []gocql.UUID, workers int) error {
	sem := make(chan struct{}, workers)
	errc := make(chan error, len(ids))
	for _, id := range ids {
		sem <- struct{}{}
		go func(id gocql.UUID) {
			defer func() { <-sem }()
			errc <- s.Query(`INSERT INTO shop.user_by_id (id, email, name) VALUES (?, ?, ?)`,
				id, "x@example.com", "x").WithContext(ctx).Idempotent(true).Exec()
		}(id)
	}
	var first error
	for range ids {
		if err := <-errc; err != nil && first == nil {
			first = err
		}
	}
	return first
}

func main() {
	raw := os.Getenv("CASSANDRA_HOSTS")
	if raw == "" {
		fmt.Println("set CASSANDRA_HOSTS=127.0.0.1 to run the batch examples")
		return
	}
	cluster := gocql.NewCluster(strings.Split(raw, ",")...)
	session, err := cluster.CreateSession()
	if err != nil {
		fmt.Fprintln(os.Stderr, "connect:", err)
		os.Exit(1)
	}
	defer session.Close()

	ctx := context.Background()
	fmt.Println("logged batch:", CreateUser(ctx, session, gocql.TimeUUID(), "ada@example.com", "Ada"))
	ids := make([]gocql.UUID, 100)
	for i := range ids {
		ids[i] = gocql.TimeUUID()
	}
	fmt.Println("bulk load:", GoodBulkLoad(ctx, session, ids, 16))
}

Counters Good to know ​

In plain words: a counter column is a number you can only add to or subtract from, safely from many clients at once.

Common misunderstanding: "Counters are exact." They are not idempotent: a timed-out increment may or may not have been applied, and a retry can double-count. They also live in their own tables, cannot have TTL, and cannot be mixed with other column types.

Definition: UPDATE page_views SET views = views + 1 WHERE page = ?. Use counters for approximate metrics; for money or inventory use an append-only table of events and sum it, or LWT.

sql
CREATE TABLE shop.page_views (page text PRIMARY KEY, views counter);
UPDATE shop.page_views SET views = views + 1 WHERE page = '/home';

Compaction strategies ​

What compaction does and the four strategies Must-know ​

In plain words: because SSTables never change, every update and delete makes a new small file. Compaction is the background job that merges files, throws away overwritten values and expired tombstones, and keeps reads from touching dozens of files.

Common misunderstanding: "Compaction is a cleanup I can postpone." Without it, SSTable count grows, reads slow down, disk fills up with dead data and tombstones never go away. It also needs free disk: size-tiered compaction can need up to half the disk free for a big merge (ScyllaDB's docs say "in the worst case up to half the disk space needs to be empty").

Definition: compaction takes one or more SSTables, merges rows by timestamp (all inputs are sorted by token, so it uses sequential IO), and writes new SSTables. Kinds: minor (automatic), major (nodetool compact), user-defined, scrub, upgradesstables, cleanup (remove ranges the node no longer owns), anticompaction (after incremental repair), and subrange. The strategy is a table property.

Cassandra 5.0 and no constraint?TTL'd, append-only time series?Read heavy, many updates/deletes?UCS (T4 or L10)TWCS (1 window = 1 day)LCS (or UCS L10)Write heavy, IO budget tight?STCS (default)Else: re-check the modelwide or hot partitions?yesnoyesnoyesnoyesno
StrategyHow it worksStrengthsWeaknessesChoose it for
STCS (SizeTiered, default)Merges SSTables of similar size; min_threshold 4, max_threshold 32Cheap writes, low write amplificationNeeds up to 2x temporary space; rows spread across many SSTables; old data lingers in huge tablesWrite-heavy general tables, fallback
LCS (Leveled)Fixed-size SSTables (160 MB default) in levels with disjoint rangesBounded read amplification, about 10% space wasteAbout twice the write IO; poor for time series or heavy ingestRead-heavy tables with many updates and deletes
TWCS (TimeWindow)One window per time bucket; each window compacted once with STCS, then left aloneWhole SSTables expire with TTL; tombstones vanish cheaplyBad if you update or delete old data or mix TTLsTTL'd, append-only time series
UCS (Unified, 5.0)One framework: scaling parameter Tn (tiered), Ln (leveled), N (middle); sharded by token; default T4, target SSTable 1 GiBSwitch behaviour with one parameter; parallel compactions; handles SSD and spinning disks; "recommended for new workloads"Newer; tune scaling_parameters and target_sstable_sizeNew tables on Cassandra 5.0
ICS (Incremental, ScyllaDB; check your edition)STCS using runs of fragments, releasing space as it goesRemoves STCS's 2x temporary spaceSame read profile as STCSScyllaDB tables that are large and write heavy
sql
-- STCS (default)
ALTER TABLE shop.orders_by_customer WITH compaction =
  {'class': 'SizeTieredCompactionStrategy', 'min_threshold': 4, 'max_threshold': 32};
-- LCS
ALTER TABLE shop.profile_by_id WITH compaction =
  {'class': 'LeveledCompactionStrategy', 'sstable_size_in_mb': 160};
-- TWCS, one-day windows, 30-day TTL
ALTER TABLE shop.readings_by_sensor_day WITH compaction =
  {'class': 'TimeWindowCompactionStrategy', 'compaction_window_unit': 'DAYS', 'compaction_window_size': 1}
  AND default_time_to_live = 2592000;
-- UCS: same behaviour as STCS (T4) or as LCS (L10) by changing one parameter
ALTER TABLE shop.orders_by_customer WITH compaction =
  {'class': 'UnifiedCompactionStrategy', 'scaling_parameters': 'T4'};
OperationCommandEffect
See pending compactionsnodetool compactionstatsRunning and pending tasks
Throttlenodetool setcompactionthroughput 64MiB/s (config compaction_throughput: 64MiB/s)
Force a major compactionnodetool compact keyspace tableAvoid on STCS for big tables; it creates one huge SSTable
Disable / enablenodetool disableautocompaction / enableautocompactionFor maintenance windows only
Remove ranges no longer ownednodetool cleanupAfter adding nodes, on the old owners
Why tombstones are not droppedsstableexpiredblockers keyspace tableLists blocking SSTables
Rewrite SSTables after upgradenodetool upgradesstablesAfter a major version

Indexes and time series ​

Secondary indexes, SAI and vector search Important ​

In plain words: a secondary index lets you filter on a column that is not part of the primary key. The old built-in version scales badly; Cassandra 5.0's Storage-Attached Index (SAI) is the one to use.

Common misunderstanding: "SAI turns Cassandra into a relational database." The docs call SAI "a filtering engine" that "simplifies data modeling", but queries still need a restricted partition or accept a fan-out to nodes; a low-cardinality or unrestricted query is still expensive and ALLOW FILTERING is still a scan.

Definition: SAI is built into the storage engine: it indexes memtables and SSTables as they are written and resolves differences at read time; index data streams with the SSTables (zero copy streaming) and shares data across indexes of a table. It supports equality, numeric range, AND/OR combinations, IN, CONTAINS on collections, tokenized text with options (case sensitivity, Unicode normalization) and vector similarity. Each indexed column increases memtable pressure, so flushes are smaller and more frequent. The legacy "2i" secondary index stores a hidden table per node and is only reasonable for low-cardinality, partition-restricted queries; SASI is disabled by default (sasi_indexes_enabled: false in the 5.0 config).

cql
USE shop;

-- Storage-Attached Index (Cassandra 5.0): filter on non-key columns without a new table.
CREATE TABLE IF NOT EXISTS products (
  sku      text PRIMARY KEY,
  title    text,
  brand    text,
  price    decimal,
  tags     set<text>,
  embedding vector<float, 3>
);
CREATE INDEX IF NOT EXISTS products_brand_idx ON products (brand) USING 'sai';
CREATE INDEX IF NOT EXISTS products_price_idx ON products (price) USING 'sai';
CREATE INDEX IF NOT EXISTS products_tags_idx  ON products (tags)  USING 'sai';
CREATE INDEX IF NOT EXISTS products_ann_idx   ON products (embedding) USING 'sai';

-- SELECT sku, title FROM products WHERE brand = 'Acme' AND price < 20;
-- SELECT sku FROM products WHERE tags CONTAINS 'sale';
-- SELECT sku FROM products ORDER BY embedding ANN OF [0.1, 0.2, 0.3] LIMIT 5;

The vector<float, N> type and ORDER BY embedding ANN OF [...] LIMIT k give approximate nearest-neighbour search inside Cassandra 5.0. In the 5.0.9 lab image, creating the ANN index prints a warning that "SAI ANN indexes on vector columns are experimental and are not recommended for production use" and lists limits (consistency level up to ONE or LOCAL_ONE, no paging, a LIMIT is required), so read the release notes of your version. For embeddings in a relational stack see Vector Search & pgvector; for text search see Full-Text Search. ScyllaDB offers vector search through its own native vector index; the compatibility page notes that the SAI class name on vector columns is rewritten to the native vector_index.

NeedCassandra 5.0ScyllaDBOther
Filter on a non-key columnSAIGlobal or local secondary index (MV based)Any index in PostgreSQL/MySQL
Numeric range on non-key columnSAIModel a table, or secondary indexB-tree index
Full-textSAI tokenized (basic)External searchPostgreSQL FTS, Elasticsearch
Vector ANNSAI vector indexNative vector indexpgvector, dedicated engines
Unique constraintLWTLWTUnique index

Time-series modeling and bucketing Must-know ​

In plain words: a sensor writes forever, so you cut its timeline into daily (or hourly) partitions that each end, and you let old partitions expire as whole files.

Common misunderstanding: "Partition by sensor and cluster by time is enough." After a year that is one gigantic partition on three nodes. The bucket (a date, or a month) must be part of the partition key.

Definition: PRIMARY KEY ((sensor_id, day), ts) with CLUSTERING ORDER BY (ts DESC), default_time_to_live per table, and TWCS windows aligned with the bucket so that one day's data sits in one SSTable that expires as a unit. Reads of "the last 5 minutes" touch one partition; "the last 7 days" is seven queries issued in parallel. Writers add rows with a TTL; nobody issues DELETE, so gc_grace_seconds can be lowered (here to one hour) because tombstones are not used for data removal. The default gc_grace_seconds stays at ten days whenever you delete explicitly.

cql
USE shop;

-- Time series with bucketing: (sensor_id, day) bounds every partition to one day.
-- TWCS puts each day into its own SSTable window; default_time_to_live drops it whole.
CREATE TABLE IF NOT EXISTS readings_by_sensor_day (
  sensor_id text,
  day       text,
  ts        timestamp,
  value     double,
  PRIMARY KEY ((sensor_id, day), ts)
) WITH CLUSTERING ORDER BY (ts DESC)
  AND compaction = {
    'class': 'TimeWindowCompactionStrategy',
    'compaction_window_unit': 'DAYS',
    'compaction_window_size': 1
  }
  AND default_time_to_live = 2592000   -- 30 days
  AND gc_grace_seconds = 3600;         -- safe only because rows are never deleted by hand

-- Same table on Cassandra 5.0 with the Unified Compaction Strategy:
-- ALTER TABLE readings_by_sensor_day WITH compaction =
--   {'class': 'UnifiedCompactionStrategy', 'scaling_parameters': 'T4'};
go
// Package main writes and reads a bucketed time series: the partition key is
// (sensor_id, day) so no partition grows forever, and every row carries a TTL.
package main

import (
	"context"
	"fmt"
	"os"
	"strings"
	"time"

	"github.com/gocql/gocql"
)

// Bucket returns the day bucket for a timestamp; it becomes part of the partition key.
func Bucket(t time.Time) string {
	return t.UTC().Format("2006-01-02")
}

// Reading is one measurement.
type Reading struct {
	At    time.Time
	Value float64
}

// WriteBatch stores readings that share one (sensor, day) partition in a single
// UNLOGGED batch. That is the only batch shape that is a performance tool:
// one partition, one replica set, one mutation.
func WriteBatch(ctx context.Context, s *gocql.Session, sensor string, rs []Reading) error {
	if len(rs) == 0 {
		return nil
	}
	day := Bucket(rs[0].At)
	b := s.NewBatch(gocql.UnloggedBatch).WithContext(ctx)
	for _, r := range rs {
		if Bucket(r.At) != day {
			return fmt.Errorf("reading at %s belongs to another bucket than %s", r.At, day)
		}
		b.Query(`INSERT INTO shop.readings_by_sensor_day (sensor_id, day, ts, value)
			VALUES (?, ?, ?, ?) USING TTL 2592000`, sensor, day, r.At, r.Value)
	}
	return s.ExecuteBatch(b)
}

// LastN returns the newest n readings of one bucket. The table is declared with
// CLUSTERING ORDER BY (ts DESC), so this is a sequential read from the start of the partition.
func LastN(ctx context.Context, s *gocql.Session, sensor string, day string, n int) ([]Reading, error) {
	iter := s.Query(`SELECT ts, value FROM shop.readings_by_sensor_day
		WHERE sensor_id = ? AND day = ? LIMIT ?`, sensor, day, n).
		WithContext(ctx).
		PageSize(200).
		Iter()
	var out []Reading
	var r Reading
	for iter.Scan(&r.At, &r.Value) {
		out = append(out, r)
	}
	return out, iter.Close()
}

func main() {
	raw := os.Getenv("CASSANDRA_HOSTS")
	if raw == "" {
		fmt.Println("set CASSANDRA_HOSTS=127.0.0.1 to write and read a bucketed series")
		return
	}
	cluster := gocql.NewCluster(strings.Split(raw, ",")...)
	cluster.Consistency = gocql.LocalQuorum
	session, err := cluster.CreateSession()
	if err != nil {
		fmt.Fprintln(os.Stderr, "connect:", err)
		os.Exit(1)
	}
	defer session.Close()

	ctx := context.Background()
	now := time.Now().UTC()
	var rs []Reading
	for i := 0; i < 5; i++ {
		rs = append(rs, Reading{At: now.Add(time.Duration(i) * time.Second), Value: 20 + float64(i)})
	}
	if err := WriteBatch(ctx, session, "s-42", rs); err != nil {
		fmt.Fprintln(os.Stderr, "write:", err)
		os.Exit(1)
	}
	got, err := LastN(ctx, session, "s-42", Bucket(now), 3)
	if err != nil {
		fmt.Fprintln(os.Stderr, "read:", err)
		os.Exit(1)
	}
	for _, r := range got {
		fmt.Println(r.At.Format(time.RFC3339), r.Value)
	}
}
Bucket sizeRows per partition at 1 reading per secondSuits
Hour3,600High-frequency data (100 Hz = 360,000 rows: shorten the bucket)
Day86,4001 Hz sensors, below the 100,000-row guidance
Month2,592,000Too large for 1 Hz; fine for hourly aggregates
Hash bucket (hash(id) mod 16)spread evenlyHot keys where time is not the access path

Per-product behaviour ​

Cassandra, ScyllaDB and the rest Must-know ​

CapabilityCassandra 5.0ScyllaDBDynamoDBPostgreSQLMySQL / InnoDBMongoDBCockroachDBRedis
ArchitectureMasterless ring (Java)Masterless ring (C++, shard-per-core)Managed, hidden partitionsSingle primarySingle primaryReplica set, shardedRaft ranges, SQLPrimary/replica, cluster slots
Write scaleAdd nodesAdd nodes (and cores)AutomaticVertical, then shardVertical, then shardAdd shardsAdd nodesAdd shards
JoinsNoNoNoYesYes$lookupYesNo
Multi-row transactionsNo (Accord in 6.0 line)NoLimited (TransactWriteItems)YesYesYesYesMULTI/Lua
Consistency knobPer statementPer statementPer read (eventual or strong)Isolation levelIsolation levelRead/write concernSerializable defaultWAIT, none by default
Query languageCQLCQL, DynamoDB API (Alternator)PartiQL, APISQLSQLMQLSQLCommands
Secondary accessSAI, 2i, MVMV-based indexesGSI, LSIAny indexAny indexAny indexAny indexSets, sorted sets
Best atWrite-heavy, multi-DC, time seriesSame, with lower latency and fewer nodesZero-ops key-valueGeneral OLTPGeneral OLTPDocumentsDistributed SQLCache, queues

For the DynamoDB side of the comparison and how single-table design relates to Cassandra's query tables, see Wide-Column & Key-Value at Scale. For the same CAP-and-consistency framing across products, see Eventual Consistency in Database Systems. SQL Server, Oracle and SQLite have no distributed masterless mode at all; SQLite is a single file (see SQLite in Depth).

ScyllaDB differences ​

App (Go service)scylladb/gocql forkTokenAwareHostPolicyAnother clientnot shard awarelands on any shardOne ScyllaDB node (C++, Seastar, no JVM, no GC pauses)Shard 0 (core 0)one thread, no locksmemtable + row cachecommit log segmentSSTables for its tokensShard 1 (core 1)one thread, no locksmemtable + row cachecommit log segmentSSTables for its tokensShard N (core N)one thread, no locksmemtable + row cachecommit log segmentSSTables for its tokensown slice of RAMown slice of RAMown slice of RAMSeastar scheduler: shares per service levelOLTP 1000 shares, OLAP 100 shares: CPU and IO split by weightLocal disk (NVMe, XFS) and NICeach shard does its own async IO (io_uring or AIO), with a per-shard queuecross-shard work uses smp::submit_to (explicit message), never a shared mutex

ScyllaDB is a rewrite of the Cassandra design in C++ that keeps CQL, the native protocol, the ring, gossip, consistency levels and SSTable formats, and changes the engine underneath. Its compatibility page says CQL is "fully compatible with version 3.3.1, with additional features from later CQL versions", the native protocol "fully compatible with protocol v4, with additional features from v5", SSTable formats mc/md/me, Thrift gone since 6.0, and tools based on Cassandra 3.11 (nodetool, cqlsh, cassandra-stress, sstableloader).

Shard-per-core and Seastar Must-know ​

In plain words: ScyllaDB gives each CPU core its own slice of data, memory and disk queue, and the cores do not share locks. Cassandra instead runs thread pools that share memory inside a JVM.

Common misunderstanding: "ScyllaDB is just a faster Cassandra, drop it in." The wire protocol is compatible, but behaviour differs: nodetool tools and metrics differ, a node is 'many shards' and should be sized by cores, some Cassandra features (SAI, the 5.0 UCS) have different equivalents, and a non-shard-aware client works but loses part of the benefit.

Definition: ScyllaDB is built on Seastar, a shared-nothing framework with "one application thread per core" and "explicit message passing, not shared memory between threads", so it avoids slow lock primitives and cache bounces. Cross-core work is done with explicit messages (smp::submit_to). Each shard owns its memtables, cache and a range of the node's tokens. Being C++ with its own memory allocator there is no JVM garbage collector, so there are no GC pauses; it also does its own IO scheduling and caching instead of relying on the OS page cache. A shard-aware driver (the scylladb/gocql fork's TokenAwareHostPolicy) opens one connection per shard and routes each request to the right core; the shard-aware port (native_shard_aware_transport_port) lets the driver pick which shard a connection lands on.

AspectCassandra 5.0ScyllaDB
Language and runtimeJava, JVM (G1/ZGC tuning, GC pauses)C++, Seastar, no GC
Concurrency modelStaged thread pools, shared memoryShard-per-core, shared-nothing
CacheOS page cache plus key/row cachesOwn row cache per shard, bypasses page cache
CompactionSTCS, LCS, TWCS, UCSSTCS, LCS, TWCS, ICS, with IO scheduler isolation
Cluster metadataGossip, schema pullsGossip plus Raft for schema and topology
Data distributionvnodes (default 16 tokens)Tablets by default for new keyspaces, vnodes optional
Node operationsStreamingRepair-based node operations (RBNO)
ClientAny CQL driverAny CQL driver; shard-aware forks for best latency
Multi-tenant isolationLimitedWorkload prioritization (service levels)
Other APIsCQL onlyCQL plus Alternator (DynamoDB API)

Tablets versus vnodes Important ​

In plain words: with vnodes the ring is fixed by token ranges and moving data means streaming whole ranges one node at a time. Tablets are small movable pieces of a table; a load balancer moves them in the background.

Common misunderstanding: "Tablets are a tuning option I can switch on later." You cannot ALTER a keyspace to enable or disable tablets; the only way is to drop and recreate it, and tablets are the default for new keyspaces in recent releases (tablets_mode_for_new_keyspaces). Check feature limits for materialized views, secondary indexes and other features before choosing.

Definition: a tablet is a range of a table's partitions, replicated like a vnode range; each partition maps deterministically to one tablet. The tablet load balancer moves tablets across nodes and across shards to equalise disk usage; as a table grows a tablet splits in two and small ones merge. With Raft-managed topology several nodes can be added at once, data moves by file-based streaming of whole SSTables, and cleanup happens per tablet, with no manual nodetool cleanup. The tablet count follows options such as initial (keyspace), min_tablet_count, max_tablet_count, expected_data_size_in_gb and the config tablets_initial_scale_factor.

sql
-- ScyllaDB
CREATE KEYSPACE shop
  WITH replication = {'class': 'NetworkTopologyStrategy', 'replication_factor': 3}
  AND tablets = {'enabled': true};
-- Opt out per keyspace (cannot be changed later):
-- ... AND tablets = {'enabled': false};

Workload prioritization Important ​

In plain words: you give each kind of work (online queries, analytics, batch jobs) a weight, and the database divides CPU and IO by those weights so a big report cannot starve the checkout path.

Common misunderstanding: "Shares are limits." Shares only matter under contention; an idle cluster lets any workload use everything. They divide capacity in proportion, not cap it.

Definition: service levels created with CREATE SERVICE_LEVEL name WITH SHARES = n (1 to 1000, default 1000) and attached to roles. Percentage = shares / total shares. Two exist from the start: default (everything unassigned) and driver (driver metadata operations and connection setup before authentication).

sql
CREATE SERVICE_LEVEL IF NOT EXISTS OLAP WITH SHARES = 100;
CREATE SERVICE_LEVEL IF NOT EXISTS OLTP WITH SHARES = 1000;
LIST ALL SERVICE_LEVELS;
ATTACH SERVICE_LEVEL OLTP TO web;   -- web is the role the application logs in with

With OLAP 100, OLTP 1000, driver 200 and default 1000, the documentation's table gives shares of about 4%, 44%, 8% and 44% when all are busy. Cassandra 5.0 has no equivalent; you isolate workloads with separate datacenters or clusters instead.

Alternator: the DynamoDB API on ScyllaDB Good to know ​

In plain words: Alternator makes a ScyllaDB cluster answer DynamoDB requests, so an application written for DynamoDB can run against ScyllaDB (on-premises, or another cloud).

Common misunderstanding: "It is a translation layer onto CQL." The docs say "there is no CQL generation or parsing involved"; requests are served by internal C++ functions. Also compatibility is "fairly complete", not total, so test the features you use.

Definition: disabled by default; enable with alternator_port: 8000 (and optionally alternator_https_port) plus alternator_write_isolation (only_rmw_uses_lwt, always, forbid or unsafe; a port without isolation configured is an error). Each Alternator table becomes a ScyllaDB table in its own keyspace with RF=3 on clusters of three or more nodes. Consistency: writes at LOCAL_QUORUM, strongly consistent reads at LOCAL_QUORUM, eventually consistent reads at LOCAL_ONE. Read-modify-write requests (conditional updates, increments, returning old values) are isolated with LWT by default. Clients are the stock AWS SDKs pointed at a node endpoint; the PHP client below uses aws/aws-sdk-php.

Repair-based node operations (RBNO) and Raft topology Good to know ​

ScyllaDB reuses its row-level repair for bootstrap, decommission, rebuild, removenode and replace ("RBNO"). The documentation says a failed operation "can resume from the point it stopped" and that with RBNO you "don't need to run repair before or after node operations". Control it with enable_repair_based_node_ops and allowed_repair_based_node_ops. Topology and schema changes go through Raft, so adding or removing nodes needs a healthy majority of the cluster.

Mechanics ​

nodetool and cqlsh operations Must-know ​

TaskCommandWhen
Cluster healthnodetool status, nodetool describecluster, nodetool gossipinfoEvery incident
Thread pools (backlog, dropped)nodetool tpstatsLatency or drops (MutationStage, ReadStage, Repair-Task)
Table healthnodetool tablestats ks.table, nodetool tablehistograms ks tableSSTable count, partition sizes, tombstones per slice
Where is this key?nodetool getendpoints ks table keyDebugging placement
Flush memtablesnodetool flush [ks table]Before a snapshot or a restart
Safe stopnodetool drainFlush and stop accepting writes before shutdown
Add / remove a nodestart with auto_bootstrap, nodetool decommission, nodetool removenode <host-id>, -Dcassandra.replace_address_first_boot=<ip>Topology changes (one at a time on vnode clusters)
After adding nodesnodetool cleanupOn the old owners
Add a datacenterALTER KEYSPACE, then nodetool rebuild -- <source-dc> on each new nodeMulti-DC growth
Repairnodetool repair -pr, --full, -prv, -vdSchedule with Reaper
Snapshotsnodetool snapshot -t name ks, nodetool clearsnapshotBackups; auto_snapshot: true also snapshots on DROP/TRUNCATE
Hintsnodetool statushandoff, disablehandoff, sethintedhandoffthrottlekb, truncatehintsRestarts and maintenance
Compactionnodetool compactionstats, setcompactionthroughput, compactSee compaction
Tracing one requestTRACING ON; in cqlshWhich replicas answered and how long
Dump SSTable contentsstabledump, sstablemetadata (tools directory)Inspect tombstones, timestamps

cassandra.yaml knobs seen in the 5.0 image Important ​

SettingValue in the lab imageMeaning
num_tokens16vnodes per node
allocate_tokens_for_local_replication_factor3Deterministic allocator target RF
endpoint_snitchGossipingPropertyFileSnitch set by envTopology source
authenticator / authorizerAllowAllAuthenticator / AllowAllAuthorizerNo auth by default; switch to PasswordAuthenticator and CassandraAuthorizer before exposing the node
read_request_timeout / write_request_timeout5000ms / 2000msCoordinator waits
range_request_timeout10000msRange scans
cas_contention_timeout1000msLWT retry budget
max_hint_window3hHow long hints are collected
tombstone_warn_threshold / tombstone_failure_threshold1000 / 100000Tombstones per read
batch_size_warn_threshold / batch_size_fail_threshold5KiB / 50KiBBatch size
compaction_throughput64MiB/sCompaction IO cap
auto_snapshottrueSnapshot before DROP and TRUNCATE; disk grows after drops
materialized_views_enabledfalseMVs need explicit enabling
sasi_indexes_enabledfalseLegacy SASI off
storage_compatibility_modeCASSANDRA_4Stay on until all nodes are 5.0, then move to UPGRADING and NONE per the upgrade guide
storage_port / native_transport_port7000 / 9042Internode and client ports

Error codes and exceptions you will catch Must-know ​

Error (native protocol code)Typical textMeaningRetry?
Unavailable (0x1000)Cannot achieve consistency level QUORUM with required_replicas, alive_replicasThe coordinator knows too few replicas are alive; nothing was attemptedOnly after a node returns, or at a lower CL
Write timeout (0x1100)Operation timed out - received only 1 responses with write type SIMPLE, BATCH, BATCH_LOG, CAS, COUNTERReplicas did not answer in time; the write may have been appliedIf idempotent; a CAS timeout needs a SERIAL read first
Read timeout (0x1200)received only 0 responses with data_present flagNot enough replicas answered; often slow disk, tombstones or a huge partitionYes, with backoff; fix the cause
Read failure (0x1300) / Write failure (0x1500)Replica(s) failed to execute readA replica returned an error (for example the tombstone failure threshold)Fix the query
Overloaded (0x1001)Server is overloadedNode is shedding loadBack off
Is bootstrapping (0x1002)Node is joiningChoose another node
Syntax (0x2000) / Invalid (0x2200)InvalidRequest: Cannot execute this query as it might involve data filteringBad CQL or a query that needs a scanNo; fix the model or add SAI
Unprepared (0x2500)Prepared statement is not known by that nodeDrivers re-prepare automatically
TombstoneOverwhelmingException (server log)Scanned over N tombstones during queryQuery aborted at tombstone_failure_thresholdFix the delete pattern
Batch too largeBatch exceeds batch_size_fail_thresholdSplit; do not batch across partitions

Solving the classic problems ​

Unique values: usernames and e-mail addresses ​

SolutionHowAdvantageCost or limit
LWT IF NOT EXISTS on a claim tableOne row per username, key is the usernameReal uniquenessAbout four round trips; keep it off the hot path
Deterministic keyUse the e-mail hash as the partition key of the main tableNo LWTOnly unique if you never need a second unique field
External uniquenessPostgreSQL unique index, then write to CassandraFamiliarTwo systems to keep consistent
go
// Package main claims a unique username with a lightweight transaction
// (IF NOT EXISTS) and shows the compare-and-set read of the current owner.
package main

import (
	"context"
	"errors"
	"fmt"
	"os"
	"strings"
	"time"

	"github.com/gocql/gocql"
)

// ErrTaken is returned when another user already owns the name.
var ErrTaken = errors.New("username already taken")

// ClaimUsername runs one Paxos round. applied=false means the row existed;
// Cassandra then returns the existing row so the caller can see who owns it.
func ClaimUsername(ctx context.Context, s *gocql.Session, name string, owner gocql.UUID) error {
	var existingName string
	var existingOwner gocql.UUID
	applied, err := s.Query(
		`INSERT INTO shop.username_claims (username, owner_id) VALUES (?, ?) IF NOT EXISTS`,
		name, owner).
		WithContext(ctx).
		SerialConsistency(gocql.Serial). // Paxos phase; commit phase uses the query's own consistency
		ScanCAS(&existingName, &existingOwner)
	if err != nil {
		// A timeout here is UNKNOWN, not "not applied": read back at SERIAL before retrying.
		return fmt.Errorf("claim %q: %w", name, err)
	}
	if !applied {
		return fmt.Errorf("%w (owner %s)", ErrTaken, existingOwner)
	}
	return nil
}

// Rename uses a conditional UPDATE: it only applies if the version still matches.
func Rename(ctx context.Context, s *gocql.Session, id gocql.UUID, oldVersion int, newName string) (bool, error) {
	var currentVersion int
	return s.Query(
		`UPDATE shop.profile_by_id SET name = ?, version = ? WHERE id = ? IF version = ?`,
		newName, oldVersion+1, id, oldVersion).
		WithContext(ctx).
		ScanCAS(&currentVersion)
}

func main() {
	raw := os.Getenv("CASSANDRA_HOSTS")
	if raw == "" {
		fmt.Println("set CASSANDRA_HOSTS=127.0.0.1 to run the lightweight transaction")
		return
	}
	cluster := gocql.NewCluster(strings.Split(raw, ",")...)
	cluster.Timeout = 5 * time.Second // a LWT is four round trips, give it room
	session, err := cluster.CreateSession()
	if err != nil {
		fmt.Fprintln(os.Stderr, "connect:", err)
		os.Exit(1)
	}
	defer session.Close()

	ctx := context.Background()
	me := gocql.TimeUUID()
	fmt.Println("first claim :", ClaimUsername(ctx, session, "ada", me))
	fmt.Println("second claim:", ClaimUsername(ctx, session, "ada", gocql.TimeUUID()))
}

On timeout the outcome is unknown; read the claim at SERIAL and compare the owner before you retry.

Lookup by two keys: two tables and a logged batch ​

Store the user by id and by e-mail. Write both with one logged batch so a coordinator crash cannot leave only one copy (see the batch code above). Reads go to whichever table matches the key. If the two tables ever diverge (a bug, a failed partial migration), repair the cheaper way: rebuild one from the other with a scan job.

Queues and delete-heavy workloads ​

Do not build a queue on Cassandra. Each consumed message is a delete, the oldest rows become a growing tombstone range at the head of the partition, and each poll must read through it until gc_grace_seconds and compaction clear it. The lab reproduces the warning. For queues use RabbitMQ, Kafka or Redis Streams (see Messaging Fundamentals). If you must expire, use TTL with TWCS and a time bucket so whole files drop, and keep reads on the live end of the bucket.

Hot and wide partitions ​

ProblemFixCost
One tenant produces 80% of trafficAdd a salt: partition key (tenant, salt) with salt 0 to 15, write to a random salt, read all 16 in parallel16 reads for one logical read
Unbounded time seriesAdd a time bucketReads across buckets are N queries
Large rowsStore big blobs in object storage, keep a pointerAnother system
Counters on a hot keyShard the counter into N rows and sum on readMore reads

Counters and approximate metrics ​

Use a counter table for dashboards, and an append-only event table plus a periodic roll-up for anything that must be exact. A retried increment can double count; an event with a unique id cannot.

Paging large results ​

CQL pages by a paging state, not by OFFSET (there is none). Drivers fetch PageSize rows at a time and give you an opaque token to continue; this is the equivalent of keyset pagination (see Pagination: Offset vs Keyset) and of cursors (see Cursors & Streaming Results). In Go, set Query.PageSize(n) and iterate; hand iter.PageState() back to the client for "next page", and pass it with Query.PageState(state).

Bulk loading ​

Prepared statements, token-aware routing, many concurrent async writes (16 to 128 in flight per client), no batches across partitions. For data files, sstableloader streams ready-made SSTables, and the Spark Cassandra Connector writes in parallel from a Spark job. The Go bulk loader above shows the shape.

Go and PHP clients ​

Go: gocql and the ScyllaDB fork Must-know ​

The Go driver is gocql. The Apache project's repository README ("Apache Cassandra GoCQL Driver") lists support for the native protocol versions 3, 4 and 5, logged, unlogged and counter batches, automatic reconnect with exponential backoff, a token-aware policy, TLS, tracing, paging, automatic query preparation and, from Cassandra 5.0, vector types. The 2.x module is github.com/apache/cassandra-gocql-driver/v2 and contains breaking changes versus 1.x. The snippets here use the long-standing github.com/gocql/gocql v1 API, which compiles against a real 5.0.9 cluster in the lab. The README tips apply: use the token-aware policy, issue many concurrent queries from goroutines, tune the page size, close iterators and tune GOGC. gocqlx adds struct binding and query building.

For ScyllaDB use the shard-aware fork, which the project README describes as extending tokenAwareHostPolicy so the driver "select[s] a connection to a particular shard on a host based on the token". Swap the module with a replace and keep using TokenAwareHostPolicy:

text
// go.mod
require github.com/gocql/gocql v1.7.0
replace github.com/gocql/gocql => github.com/scylladb/gocql <tag from the fork's releases>   // see its README, section 2

With ScyllaDB the driver opens one connection per shard and ignores NumConns; the shard-aware port (native_shard_aware_transport_port) speeds up connecting to every shard. Use Idempotent(true) only on statements that are safe to repeat, so the retry policy and speculative execution may resend them. See the three snippets above (connect, consistency, batch) for the working code.

PHP and Laravel: there is no first-class driver Important ​

Laravel 13's built-in database drivers are MariaDB, MySQL, PostgreSQL, SQLite and SQL Server (the version list on its database page); Cassandra and ScyllaDB are not among them, so there is no DB::connection('cassandra'), no Eloquent model and no migration class for CQL out of the box. You have three realistic options, and you should say which one you chose in the design document.

OptionHowStatus and caveats
DataStax PHP driver (pecl install cassandra)PHP extension wrapping the DataStax C/C++ driverIts README says it is in maintenance mode and lists PHP 5.6 to 7.1 and Cassandra up to 3.0+, so on PHP 8.3 and Laravel 13 expect to compile and patch it yourself
Alternator (ScyllaDB only)aws/aws-sdk-php DynamoDbClient with endpoint set to a ScyllaDB node on alternator_portMaintained client, DynamoDB data model (partition and sort key), no CQL
HTTP through Stargate (Cassandra) or a small internal Go/Java serviceLaravel Http facade against a REST or gRPC APIOne extra hop and a service to run; Stargate paths below are from the project's REST v2 docs and could not be re-fetched while writing this page

A fourth, pragmatic choice is a thin service in Go (or any language with a maintained driver) that owns the Cassandra tables and exposes the few queries your Laravel app needs over HTTP or a queue. This also keeps modeling rules (partition size, consistency levels, idempotent retries) in one place.

php
<?php

declare(strict_types=1);

namespace App\Infrastructure\Cassandra;

use Cassandra;
use Cassandra\ExecutionOptions;
use Cassandra\Session;
use Cassandra\SimpleStatement;
use Cassandra\Uuid;

/**
 * Uses the DataStax PHP driver (PECL "cassandra" extension).
 * Its README says it is in maintenance mode and lists PHP up to 7.1, so treat
 * this as a legacy-only option on a PHP 8.3 / Laravel 13 stack: the extension
 * may not build there. Prefer the Alternator or HTTP options below.
 */
final class DataStaxProfileRepository
{
    private Session $session;

    public function __construct(string $contactPoints, string $localDc, string $keyspace = 'shop')
    {
        $cluster = Cassandra::cluster()
            ->withContactPoints(...explode(',', $contactPoints))
            ->withDatacenterAwareRoundRobinLoadBalancingPolicy($localDc, 0, false)
            ->withTokenAwareRouting(true)
            ->withDefaultConsistency(Cassandra::CONSISTENCY_LOCAL_QUORUM)
            ->withDefaultTimeout(2)
            ->build();

        $this->session = $cluster->connect($keyspace);
    }

    public function save(string $id, string $name): void
    {
        $this->session->execute(
            new SimpleStatement('INSERT INTO profile_by_id (id, name, updated_at) VALUES (?, ?, toTimestamp(now()))'),
            new ExecutionOptions([
                'arguments' => [new Uuid($id), $name],
                'consistency' => Cassandra::CONSISTENCY_QUORUM,
            ]),
        );
    }

    public function find(string $id): ?string
    {
        $rows = $this->session->execute(
            new SimpleStatement('SELECT name FROM profile_by_id WHERE id = ?'),
            new ExecutionOptions(['arguments' => [new Uuid($id)]]),
        );

        foreach ($rows as $row) {
            return $row['name'];
        }

        return null;
    }
}
php
<?php

declare(strict_types=1);

namespace App\Infrastructure\Scylla;

use Aws\DynamoDb\DynamoDbClient;
use Aws\DynamoDb\Marshaler;

/**
 * ScyllaDB only: Alternator speaks the DynamoDB wire API, so the stock AWS SDK
 * for PHP (composer require aws/aws-sdk-php) is the client. Nothing here is
 * Cassandra-specific; each Alternator table is stored as a ScyllaDB table in its own keyspace.
 */
final class AlternatorProfileRepository
{
    private Marshaler $marshaler;

    public function __construct(private readonly DynamoDbClient $client, private readonly string $table = 'profiles')
    {
        $this->marshaler = new Marshaler();
    }

    public static function make(string $endpoint, string $key, string $secret): self
    {
        return new self(new DynamoDbClient([
            'region' => 'us-east-1',          // required by the SDK, ignored by Alternator routing
            'version' => 'latest',
            'endpoint' => $endpoint,          // e.g. http://scylla-node-1:8000 (alternator_port)
            'credentials' => ['key' => $key, 'secret' => $secret],
        ]));
    }

    public function save(string $id, string $name): void
    {
        $this->client->putItem([
            'TableName' => $this->table,
            'Item' => $this->marshaler->marshalItem(['id' => $id, 'name' => $name]),
        ]);
    }

    public function find(string $id, bool $strong = true): ?string
    {
        $result = $this->client->getItem([
            'TableName' => $this->table,
            'Key' => $this->marshaler->marshalItem(['id' => $id]),
            // true -> LOCAL_QUORUM read, false -> LOCAL_ONE read (see the Alternator docs)
            'ConsistentRead' => $strong,
        ]);

        if (!isset($result['Item'])) {
            return null;
        }

        return $this->marshaler->unmarshalItem($result['Item'])['name'];
    }
}
php
<?php

declare(strict_types=1);

namespace App\Infrastructure\Cassandra;

use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;

/**
 * Cassandra over HTTP through a Stargate REST API node. The Laravel side is the
 * stock Http facade. The URL shapes below follow the Stargate REST v2 API
 * (POST /v1/auth, then /v2/keyspaces/{keyspace}/{table}); this page could not
 * re-fetch the Stargate docs site, so check the paths against the Stargate
 * version you run before relying on them.
 */
final class StargateProfileRepository
{
    public function __construct(
        private readonly string $authUrl,   // e.g. http://stargate:8081
        private readonly string $restUrl,   // e.g. http://stargate:8082
        private readonly string $username,
        private readonly string $password,
        private readonly string $keyspace = 'shop',
    ) {
    }

    private function http(): PendingRequest
    {
        $token = Http::post($this->authUrl.'/v1/auth', [
            'username' => $this->username,
            'password' => $this->password,
        ])->throw()->json('authToken');

        return Http::withHeaders(['X-Cassandra-Token' => $token])
            ->acceptJson()
            ->timeout(3)
            ->retry(2, 100, throw: false);
    }

    public function save(string $id, string $name): void
    {
        $this->http()
            ->post("{$this->restUrl}/v2/keyspaces/{$this->keyspace}/profile_by_id", [
                'id' => $id,
                'name' => $name,
            ])
            ->throw();
    }

    public function find(string $id): ?string
    {
        $response = $this->http()->get("{$this->restUrl}/v2/keyspaces/{$this->keyspace}/profile_by_id/{$id}");

        return $response->successful() ? ($response->json('data.0.name')) : null;
    }
}

In Laravel register the repository you chose as a singleton in a service provider, read the endpoints from config/services.php, and keep the Cassandra code behind an interface so a feature test can swap in an in-memory fake. Do not call Cassandra from a database transaction callback (DB::transaction); the callback's rollback does not touch it (see ACID & Transactions).

Retries and failure handling ​

ErrorRetry?How
UnavailableNo immediate retryFail fast, or retry at a lower CL only if you accept stale reads
ReadTimeoutYesExponential backoff with jitter; fix tombstones or partition size
WriteTimeout (SIMPLE, BATCH)Yes if idempotentSame timestamp is not reused unless you set USING TIMESTAMP; plain inserts are idempotent
WriteTimeout (CAS)Read firstRead at SERIAL, then decide
WriteTimeout (COUNTER)NoIncrements are not idempotent
OverloadedYes, slowlyBack off, reduce concurrency
NoHostAvailableYesDriver reconnects; check DC name in the policy

Rules: mark only idempotent statements retryable; set the client timeout above the server timeouts (read_request_timeout 5000ms, write_request_timeout 2000ms); use speculative execution only for idempotent reads; keep one Session per process and reuse it (a session holds the connection pool and metadata). A Laravel job that talks to Cassandra should be idempotent too (the queue may deliver twice): key the write by a deterministic id.

Choosing ​

SituationChooseExtra techniqueReason
Very high write rate, time series, events, IoTCassandra or ScyllaDB, TWCS, bucketed partitionsTTL, LOCAL_QUORUMLinear scale-out, cheap appends
Multi-datacenter active-active writesCassandra or ScyllaDB, NetworkTopologyStrategyLOCAL_QUORUM, per-DC RF=3No primary to fail over
Need joins, ad-hoc queries, transactionsPostgreSQL (see PostgreSQL & Database Fundamentals)Read replicas, partitioningWrong fit for a ring
Small data (GBs), a relational shapePostgreSQL or MySQLNoneA ring adds cost and cognitive load
Key-value with zero operationsDynamoDB (see Wide-Column & Key-Value)On-demand capacityManaged, but vendor-bound
DynamoDB application you want to host yourselfScyllaDB with AlternatorCheck feature coverageSame API
Mixed OLTP plus batch analytics on one clusterScyllaDB with workload prioritizationService levelsIsolation by shares
Lowest latency per node, smallest fleetScyllaDBShard-aware driverNo GC, shard-per-core
Strong, cross-row invariants (ledger)A SQL databaseUse Cassandra for derived viewsNot partition-local
Vector or text search as the main workloadSee Vector Search, Full-Text SearchSAI vector is young
PickWhen
Cassandra 5.0You need the open Apache project, SAI, UCS, and a JVM stack your team already runs
ScyllaDBYou want fewer, larger nodes, predictable tail latency, tablets and Alternator
Managed (Astra DB, Amazon Keyspaces, Azure Managed Instance for Apache Cassandra)You will not run repair and upgrades; check compatibility limits per service

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

A monolith with one PostgreSQL does not need Cassandra. The typical first use is one extra use case that does not fit: a high-volume append stream (audit events, telemetry, activity feed) written by the monolith through a small repository class, with LOCAL_QUORUM and a three-node ring. Example: a Laravel shop that writes order_events to a events_by_order_day table (bucketed) so the PostgreSQL primary does not store billions of rows (see Working with Billion-Row Tables). Orders stay in PostgreSQL; Cassandra holds the stream.

Modular monolith and multiple databases ​

Each module owns its keyspace (never share a keyspace between modules; permissions and RF are per keyspace). Reference data flows one way: the module that owns the entity publishes changes, and the read-side module writes its own query tables. Keep the query tables rebuildable from the source of truth, because a denormalised copy is a cache you can lose.

Microservices: sagas, outbox and no cross-partition transactions ​

text
Order service -> Inventory service -> Notification service
1  order-service: INSERT order (PostgreSQL) + outbox row in one transaction
2  relay publishes OrderPlaced to the broker (Kafka)
3  activity-service consumes it (idempotently, by event id) and writes three query tables:
   events_by_order, events_by_customer_day, events_by_day_bucket   (logged batch, one logical event)
4  if the write times out, the consumer retries with the same key; the INSERT is idempotent

Cassandra has no distributed transaction across services or partitions, so use the outbox (see Outbox Pattern) and idempotent consumers (see Idempotent Consumers & Inbox) in front of it, and use sagas (see Saga Pattern) for multi-step business flows.

Distributed data: replicas, multi-region and consistency ​

TopologySettingsRead-your-writesFailure behaviour
One DC, RF=3LOCAL_QUORUM read and writeYesSurvives one node (or one rack, if racks are real)
Two DCs, RF=3 each, active-activeLOCAL_QUORUM both sidesWithin a DC; cross-DC after replication (typically sub-second)A DC can fail; the other keeps serving
Two DCs, cross-DC strongQUORUM or EACH_QUORUM writesYesLatency of the slowest DC; DC outage blocks writes at EACH_QUORUM
Three DCsLOCAL_QUORUM, QUORUM for rare global readsYesMajority of DCs can serve global quorum

Read-after-write across regions needs the client to stay in one region ("sticky" routing) or to use QUORUM; otherwise a user may read stale data from the other DC for a moment (see Eventual Consistency in Database Systems and Replication, Read Replicas & Failover for the single-primary contrast). When a datacenter returns after an outage longer than max_hint_window, repair it (nodetool rebuild for a new one or repair for an old one).

Scaling path: 1x, 10x, 100x ​

ScaleDesignWhat changes
1x (thousands of writes/s)Three nodes, RF=3, one DC, LOCAL_QUORUM, UCS or STCSNothing special; schedule repair from day one
10xSix to twelve nodes, add racks, token-aware drivers, TWCS for series, SAI for filtersWatch partition sizes and tombstones; separate commit log disk if batch sync
100xMany nodes, several DCs, workload isolation (ScyllaDB service levels or separate DCs for analytics), automated repair (Reaper or ScyllaDB Manager), Prometheus metricsCapacity planning by shard or core; careful topology changes; dedicated tooling

Pitfalls ​

PitfallWhat happensPrevention
SimpleStrategy in productionRacks and DCs ignored; painful to add a DCNetworkTopologyStrategy always
RF=2QUORUM = 2, no failure toleratedRF=3
ALLOW FILTERING in application codeFull scan; timeouts at scaleModel a table or add SAI
Unbounded partitionsSlow, hot, repair failuresBucket; watch tablehistograms
Tombstone pile-ups (queue pattern)ReadTimeout, tombstone warnings, then failuresDo not delete in a loop; TTL + TWCS
No repair for longer than gc_grace_secondsZombies, divergenceSchedule repair; Reaper
Multi-partition logged batches for speedCoordinator overloadAsync single statements
Reading at ONE and expecting fresh dataStale readsLOCAL_QUORUM
Clock skewA node writes "future" cells that cannot be overwrittenNTP or chrony on every node
Disk full during compactionSTCS needs temporary space (up to half the disk)Keep 50% free for STCS, or use LCS/UCS, or ICS (ScyllaDB)
Starting several nodes at onceToken collision, bootstrap failuresOne node at a time (ScyllaDB tablets with Raft topology allow parallel adds)
Dropping a keyspace and wondering where the disk wentauto_snapshot: true keeps a snapshotnodetool clearsnapshot
Unauthenticated clusterAllowAllAuthenticator defaultEnable PasswordAuthenticator, TLS, and firewalls
Using lists for concurrent writesPositional updates conflict, read-before-writeUse sets, maps, or clustering rows

Lab ​

You need Docker with about 4 GB of free memory. The compose file starts a three-node Cassandra 5.0 ring, one node at a time (each waits for the previous one to be healthy); all commands below were run against cassandra:5.0 (release 5.0.9).

Setup.

yml
# Three-node Apache Cassandra 5.0 ring for the lab. Start order matters:
# only one node may bootstrap at a time, so each node waits for the previous one.
x-cassandra: &cassandra
  image: cassandra:5.0
  environment:
    CASSANDRA_CLUSTER_NAME: academy
    CASSANDRA_DC: dc1
    CASSANDRA_RACK: rack1
    CASSANDRA_ENDPOINT_SNITCH: GossipingPropertyFileSnitch
    CASSANDRA_SEEDS: cass1
    MAX_HEAP_SIZE: 512M
    HEAP_NEWSIZE: 128M
  networks: [ring]

services:
  cass1:
    <<: *cassandra
    container_name: cass1
    ports: ["9042:9042"]
    healthcheck:
      test: ["CMD-SHELL", "nodetool status 2>/dev/null | grep -q '^UN'"]
      interval: 15s
      timeout: 10s
      retries: 20
  cass2:
    <<: *cassandra
    container_name: cass2
    depends_on:
      cass1: {condition: service_healthy}
    healthcheck:
      test: ["CMD-SHELL", "[ $$(nodetool status 2>/dev/null | grep -c '^UN') -ge 2 ]"]
      interval: 15s
      timeout: 10s
      retries: 20
  cass3:
    <<: *cassandra
    container_name: cass3
    depends_on:
      cass2: {condition: service_healthy}

networks:
  ring: {}
bash
docker compose -p cassab up -d             # takes 2 to 4 minutes
docker exec cass1 nodetool status
# Datacenter: dc1
# UN  172.21.0.4  114.62 KiB  16  76.0%  ...  rack1
# UN  172.21.0.3   85.1 KiB   16  59.3%  ...  rack1
# UN  172.21.0.2  119.81 KiB  16  64.7%  ...  rack1      (three lines starting with UN)
docker exec -i cass1 cqlsh < docs/snippets/database/cassandra-scylladb/cql/05-lab.cql
sql
-- the lab keyspace: RF=3 in dc1
CREATE KEYSPACE IF NOT EXISTS lab WITH replication = {'class': 'NetworkTopologyStrategy', 'dc1': 3};
CREATE TABLE IF NOT EXISTS lab.kv (k text PRIMARY KEY, v text);
CREATE TABLE IF NOT EXISTS lab.events (stream text, seq int, body text, PRIMARY KEY ((stream), seq));

Experiment 1: where does a key live?

text
1  docker exec cass1 cqlsh -e "INSERT INTO lab.kv (k, v) VALUES ('user:1', 'v1')"
2  docker exec cass1 nodetool getendpoints lab kv user:1
   # 172.21.0.2
   # 172.21.0.4
   # 172.21.0.3      -> all three nodes (RF=3 on a three-node ring)
3  docker exec cass1 cqlsh -e "SELECT token(k), k FROM lab.kv"
   # 6120565781388772718 | user:1

Experiment 2: consistency levels against dead nodes.

text
1  docker stop cass3        # one replica down; wait about 20 s
2  CONSISTENCY ALL;   INSERT INTO lab.kv (k,v) VALUES ('a','1');
   # NoHostAvailable ... Unavailable('... Cannot achieve consistency level ALL'
   #   info={'consistency': 'ALL', 'required_replicas': 3, 'alive_replicas': 2})
3  CONSISTENCY QUORUM; INSERT INTO lab.kv (k,v) VALUES ('a','1');   -- succeeds
4  docker stop cass2        # two replicas down
5  CONSISTENCY QUORUM; SELECT * FROM lab.kv WHERE k='a';
   # Unavailable: Cannot achieve consistency level QUORUM  required_replicas: 2, alive_replicas: 1
6  CONSISTENCY ONE;    SELECT * FROM lab.kv WHERE k='a';        -- returns the row
7  docker start cass2 cass3

Experiment 3: a stale read, then read repair. Disable hints first so only repair can fix the replica.

text
1  docker exec cass1 nodetool disablehandoff ; docker exec cass2 nodetool disablehandoff
2  docker stop cass3
3  on cass1:  CONSISTENCY QUORUM; INSERT INTO lab.kv (k,v) VALUES ('stale','v2');
4  docker start cass3         # wait until it is UN
5  on cass3:  CONSISTENCY ONE;    SELECT * FROM lab.kv WHERE k='stale';   -- (0 rows): the stale replica answers alone
6  on cass3:  CONSISTENCY QUORUM; SELECT * FROM lab.kv WHERE k='stale';   -- stale | v2   (digest mismatch, blocking read repair)
7  on cass3:  CONSISTENCY ONE;    SELECT * FROM lab.kv WHERE k='stale';   -- stale | v2   (cass3 now has the row)
8  docker exec cass1 nodetool enablehandoff ; docker exec cass2 nodetool enablehandoff

Experiment 4: the tombstone warning. One partition, 1,500 rows inserted and then deleted one by one, plus one live row.

text
1  generate the script (shell, on the host):
   python3 -c "print('USE lab;'); [print(f\"INSERT INTO events (stream, seq, body) VALUES ('q', {i}, 'job-{i}');\") for i in range(1,1501)]; [print(f\"DELETE FROM events WHERE stream='q' AND seq={i};\") for i in range(1,1501)]; print(\"INSERT INTO events (stream, seq, body) VALUES ('q', 9999, 'live');\")" > /tmp/ts.cql
   docker exec -i cass1 cqlsh < /tmp/ts.cql      # 1,500 inserts, 1,500 deletes, 1 live row
2  CONSISTENCY ONE; SELECT * FROM lab.events WHERE stream='q' LIMIT 1;
   #  stream | seq  | body
   #  q      | 9999 | live
   #  Warnings :
   #  Read 1 live rows and 1500 tombstone cells for query SELECT * FROM lab.events WHERE stream = 'q' LIMIT 1 ALLOW FILTERING; token -4882450986412430415 (see tombstone_warn_threshold)
3  docker exec cass1 grep -i tombstone /var/log/cassandra/system.log
   # WARN [ReadStage-5] ... ReadCommand.java:644 - Read 1 live rows and 1500 tombstone cells ...
4  docker exec cass1 nodetool tablestats lab.events
   #  Average tombstones per slice (last five minutes): 1597.0
5  one partition delete would have been a single tombstone: DELETE FROM lab.events WHERE stream='q';

Experiment 5: look at the SSTable.

text
1  docker exec cass1 nodetool flush lab
2  docker exec cass1 sh -c 'ls /var/lib/cassandra/data/lab/events-*/'
   # nb-1-big-CompressionInfo.db  nb-1-big-Data.db  nb-1-big-Digest.crc32  nb-1-big-Filter.db
   # nb-1-big-Index.db  nb-1-big-Statistics.db  nb-1-big-Summary.db  nb-1-big-TOC.txt
3  docker exec cass1 nodetool tablestats lab.events   # SSTable count: 1, Bloom filter false positives: 0

Experiment 6: run the Go snippets.

bash
cd docs/snippets/database/cassandra-scylladb/go
docker exec -i cass1 cqlsh < ../cql/01-keyspace.cql ; docker exec -i cass1 cqlsh < ../cql/02-tables.cql
docker exec -i cass1 cqlsh < ../cql/03-timeseries.cql
CASSANDRA_HOSTS=127.0.0.1 go run ./connect       # connected to Cassandra 5.0.9
CASSANDRA_HOSTS=127.0.0.1 go run ./consistency   # write QUORUM: ok / read QUORUM: Ada ok / ...
CASSANDRA_HOSTS=127.0.0.1 go run ./lwt           # first claim: <nil> ; second claim: username already taken (owner ...)

Clean up with docker compose -p cassab down -v.

Common misconceptions ​

BeliefReality
Cassandra has no schemaCQL has a strict schema; the primary key is fixed at creation
It loses writes because it is eventually consistentQUORUM writes and reads give read-your-writes; loss comes from ONE/ANY plus no repair
QUORUM writes only go to two nodesThey go to all replicas; the coordinator waits for two
Adding an index lets me query anythingIndexes filter; the key still defines cheap queries
DELETE frees disk immediatelyIt writes a tombstone; space returns after gc_grace_seconds and compaction
Hinted handoff replaces repairHints are best effort for 3 hours; only repair guarantees convergence
Batches are fasterMulti-partition batches are slower; use them for atomic denormalisation
Lightweight transactions are general transactionsSingle-partition compare-and-set; cross-partition needs Accord (6.0 line) or a saga
More vnodes is betterHigher num_tokens increases neighbours and failure combinations; 16 with the allocator is the modern default
ScyllaDB is a drop-in, identical replacementSame CQL and protocol, but different engine, tooling, metrics, features (SAI, UCS) and Raft/tablets behaviour
SimpleStrategy is fine for one DCUse NetworkTopologyStrategy from the start
Counters are exactThey are not idempotent; retries can double count
Cassandra is a good queueQueue deletes create tombstone ranges that slow reads
Laravel can use Cassandra through EloquentThere is no first-party driver; use Alternator, HTTP, or a Go service

Cheat sheet ​

TopicWhat to remember
Quorum mathQUORUM = floor(RF/2)+1; RF=3 gives 2; W + R > RF means read-your-writes
Default writeSent to all replicas, coordinator waits for CL answers
ReplicationNetworkTopologyStrategy, RF=3 per DC; raising RF needs repair -full
Partition sizeUnder about 100 MB and 100,000 rows; bucket unbounded keys
Query designOne table per query; denormalise; no joins; no OFFSET
TombstonesWarn at 1000, fail at 100000; gc_grace_seconds 864000; repair within it
Hints3 hour window; best effort; replay throttled to 1024 KiB/s by default
RepairIncremental default; -pr per node; full every 1 to 3 weeks; use Reaper
LWTIF NOT EXISTS / IF col = x; Paxos; about 4 round trips; single partition
BatchesLogged for atomic multi-table; unlogged only for one partition; 5 KiB warn, 50 KiB fail
CompactionUCS for new tables on 5.0; TWCS for TTL time series; LCS for read-heavy; STCS default
ClientsToken-aware, DC-aware, prepared statements, idempotent flags; Go gocql; PHP has no first-class driver
ScyllaDBShard-per-core, Seastar, no GC, tablets default, service levels, Alternator, shard-aware driver
Operationsnodetool status, tpstats, tablestats, getendpoints, drain, repair -pr, cleanup, rebuild

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — With RF=3, how many replicas must answer a QUORUM read, and how many nodes may be down? Must-know ​

Answer

Answer: Two (floor(3/2)+1), so one replica may be down. With two down the coordinator returns Unavailable.

2 — Why do QUORUM writes plus QUORUM reads give you read-your-writes? Important ​

Answer

Answer: W + R = 4 > RF = 3, so every write set of two nodes intersects every read set of two nodes in at least one replica holding the newest timestamp.

3 — A write at ONE succeeded but a read at ONE a moment later returned nothing. Which three mechanisms can fix the stale replica later? Important ​

Answer

Answer: A hint replayed by the coordinator (if it was within the 3 hour window), read repair on a later digest mismatch, and anti-entropy repair with Merkle trees.

4 — What defines a partition, and what orders rows inside it? Must-know ​

Answer

Answer: The partition key columns (hashed to a token) define the partition; the clustering columns, with CLUSTERING ORDER BY, order rows inside it.

5 — You need to look up a user by id and by e-mail. What do you do? Must-know ​

Answer

Answer: Keep two tables with the other key (user_by_id, user_by_email) and write both with a logged batch.

6 — Why can a delete bring back deleted data? Important ​

Answer

Answer: If a replica missed the tombstone and the tombstone was purged after gc_grace_seconds, repair copies the old value back (a zombie). Repair every node within gc_grace_seconds.

7 — Why is a 1,000-row unlogged batch across many partitions a bad idea? Important ​

Answer

Answer: One coordinator has to carry every write and wait on every replica set; use token-aware async single writes. Batches are for atomic denormalisation or for one partition.

8 — Which compaction strategy fits TTL'd append-only time series, and why? Important ​

Answer

Answer: TWCS (or UCS tuned for it): each time window forms its own SSTable that expires as a whole, so tombstones are cheap and no rewrite happens.

9 — Name three differences between ScyllaDB and Cassandra that matter for operations. Good to know ​

Answer

Answer: Shard-per-core C++ without GC pauses, tablets with a load balancer and Raft topology (default for new keyspaces), workload prioritization with service levels; also Alternator and repair-based node operations.

10 — How would a Laravel 13 app talk to Cassandra? Good to know ​

Answer

Answer: There is no built-in driver. Options: the maintenance-mode DataStax PHP extension (old PHP versions), Alternator through aws/aws-sdk-php on ScyllaDB, HTTP through Stargate, or a small Go service in front.

11 — When is an LWT the right tool, and what does a timeout mean? Important ​

Answer

Answer: Uniqueness or compare-and-set on one partition. A timeout means the outcome is unknown; read at SERIAL before deciding to retry.

12 — Why use NetworkTopologyStrategy even with one datacenter? Important ​

Answer

Answer: It is rack aware and lets you add a datacenter later by changing the keyspace; SimpleStrategy ignores topology.

Glossary ​

TermMeaning
AccordConsensus protocol (CEP-15) for multi-partition transactions, in the Cassandra 6.0 line
AlternatorScyllaDB's DynamoDB-compatible API
Anti-entropy repairMerkle-tree comparison and streaming that makes replicas converge
AnticompactionCompaction after incremental repair that separates repaired and unrepaired data
BatchlogLog on other nodes that makes logged batches atomic eventually
Bloom filterIn-memory structure that says a key is definitely not in an SSTable
BucketingAdding a time or hash value to the partition key to bound partition size
Clustering columnPrimary key column that orders rows inside a partition
Commit logAppend-only log of mutations for crash recovery
CompactionMerging SSTables and dropping obsolete data
Consistency level (CL)Number of replicas that must answer a statement
CoordinatorThe node that handles one client request
CQLCassandra Query Language
Datacenter / rackTopology labels reported by the snitch
Digest requestA hash-only read used to compare replicas
GossipPeer-to-peer exchange of cluster state every second
gc_grace_secondsHow long tombstones are kept (default 864000)
Hinted handoffCoordinator stores a missed write and replays it later
ICSIncremental Compaction Strategy (ScyllaDB)
LCS / STCS / TWCS / UCSLeveled, Size-Tiered, Time-Window, Unified compaction strategies
LWTLightweight transaction (IF ...), Paxos based
Materialized viewServer-maintained table with another key; disabled by default in 5.0
MemtableIn-memory sorted write buffer per table
Murmur3PartitionerDefault hash function mapping keys to tokens
NetworkTopologyStrategyReplication strategy with per-DC RF and rack awareness
Partition keyPrimary key columns that are hashed to pick the replicas
Phi accrual failure detectorSuspicion-based failure detection used with gossip
QuorumMajority of replicas: floor(RF/2)+1
RBNORepair-based node operations in ScyllaDB
Read repairFixing stale replicas found during a read
Replication factor (RF)Number of copies of each partition
ReaperOpen-source scheduler for Cassandra repairs
SAIStorage-Attached Index (Cassandra 5.0)
SeastarC++ shared-nothing framework under ScyllaDB
Seed nodeBootstrap contact for gossip, not a leader
ShardOne CPU core's slice of a ScyllaDB node
SnitchComponent that maps nodes to datacenter and rack
SSTableImmutable sorted file written by a memtable flush
Static columnColumn stored once per partition
TabletMovable range of a table in ScyllaDB's tablet architecture
TokenPosition on the hash ring
TombstoneDeletion marker with a timestamp
TTLTime to live of a cell or row
UDTUser-defined type
vnodeA token owned by a physical node; several per node
Workload prioritizationScyllaDB service levels with shares of CPU and IO
ZombieDeleted data resurrected by repair after a tombstone was purged

References ​

Built by Morteza Negahi