Skip to content

Cassandra & ScyllaDB Cheatsheet ​

Dense quick reference for cqlsh, CQL DDL and DML, consistency levels, nodetool, compaction, repair, monitoring, ScyllaDB specifics, and the gocql and PHP drivers (Cassandra 5.0 and ScyllaDB docs).

cqlsh ​

TaskCommandNotes
Connectcqlsh host 9042 -u cassandra -p secretDefault port 9042; ScyllaDB uses the same CQL port
TLScqlsh --ssl hostConfigure ~/.cassandra/cqlshrc
Run statementcqlsh -e "SELECT * FROM app.users LIMIT 5"
Run filecqlsh -f schema.cqlIdempotent DDL with IF NOT EXISTS
Keyspace on startcqlsh -k appSame as USE app;
ConsistencyCONSISTENCY QUORUM;Shell-level setting; CONSISTENCY; shows it
Serial consistencySERIAL CONSISTENCY LOCAL_SERIAL;For lightweight transactions
TracingTRACING ON;Per-query trace of replicas and timings
Expand outputEXPAND ON;One field per line
PagingPAGING 100; / PAGING OFF;Page size in the shell
DescribeDESCRIBE KEYSPACES; DESCRIBE TABLE app.users; DESCRIBE CLUSTER;DESCRIBE KEYSPACE app prints full schema
Copy in/outCOPY app.users (id,name) TO 'u.csv' WITH HEADER=true;Fine for small data; use DSBulk or the Spark connector for large
Timeouts--request-timeout=60Default 10 s
Versioncqlsh --version / SELECT release_version FROM system.local;

References: cqlsh.

Keyspaces and replication ​

TaskCommandNotes
SimpleStrategyCREATE KEYSPACE dev WITH replication = {'class':'SimpleStrategy','replication_factor':1};Single data center only; dev and test
NetworkTopologyStrategyCREATE KEYSPACE app WITH replication = {'class':'NetworkTopologyStrategy','dc1':3,'dc2':3};Production; names must match the snitch
Durable writes... AND durable_writes = true;false skips the commit log (risky)
Alter RFALTER KEYSPACE app WITH replication = {...}; then nodetool repair -full appRaising RF requires repair to populate new replicas
DropDROP KEYSPACE app;Takes a snapshot first if auto_snapshot is true
Rule of thumbRF = 3 per data centerAllows LOCAL_QUORUM with one node down
SnitchGossipingPropertyFileSnitch (cassandra-rackdc.properties)Cloud snitches exist for EC2 and GCE
System keyspacessystem, system_schema, system_auth, system_distributed, system_tracesNames and the system_auth RF advice not verified in the 5.0 pages
Tablets (ScyllaDB)... AND tablets = {'enabled': true}Newer ScyllaDB defaults to tablets for new keyspaces

References: CQL DDL, Snitches, Tablets (ScyllaDB).

DDL ​

TaskCommandNotes
Create tableCREATE TABLE app.events (user_id uuid, ts timeuuid, kind text, payload text, PRIMARY KEY ((user_id), ts));(user_id) partition key, ts clustering column
Composite partition keyPRIMARY KEY ((tenant, day), ts)Splits large partitions; bucket by time
Clustering orderWITH CLUSTERING ORDER BY (ts DESC)Latest first without sorting at read time
Static columnteam text STATICOne value per partition
Default TTLWITH default_time_to_live = 86400Seconds; applies to new writes
Compaction optionWITH compaction = {'class':'TimeWindowCompactionStrategy','compaction_window_unit':'DAYS','compaction_window_size':1}See compaction table
CompressionWITH compression = {'class':'LZ4Compressor','chunk_length_in_kb':16}ZstdCompressor is among the 5.0 compressors; default chunk length is 64 KiB
gc_graceWITH gc_grace_seconds = 864000Default 10 days; repair within this window
CachingWITH caching = {'keys':'ALL','rows_per_partition':'NONE'}
Speculative retryWITH speculative_retry = '99PERCENTILE'
AlterALTER TABLE t ADD col int; / DROP col; / WITH ...Cannot change the primary key or column types freely
Drop / truncateDROP TABLE t; / TRUNCATE t;Truncate permanently removes all data but keeps the table
Typestext int bigint uuid timeuuid timestamp date time boolean decimal double float blob inet counter varint durationtimeuuid has time ordering
Counter tableCREATE TABLE c (id text PRIMARY KEY, n counter);UPDATE c SET n = n + 1 WHERE id='x'; Counters cannot be mixed with other columns
Materialized viewCREATE MATERIALIZED VIEW v AS SELECT ... PRIMARY KEY (a, b);Experimental in Cassandra; supported in ScyllaDB
Primary key ruleQuery-first design: one table per queryNo joins; denormalize

References: CQL DDL, Types, Materialized views, cassandra.yaml.

DML ​

TaskCommandNotes
InsertINSERT INTO users (id, name) VALUES (uuid(), 'Ana');INSERT is an upsert
Insert if absentINSERT ... IF NOT EXISTS;Lightweight transaction (Paxos)
With TTLINSERT ... USING TTL 3600;Seconds; cell expires into a tombstone
With timestampINSERT ... USING TIMESTAMP 1700000000000000;Microseconds; last write wins
UpdateUPDATE users SET name='Bo' WHERE id=?;Also an upsert
Conditional updateUPDATE users SET name='Bo' WHERE id=? IF name='Ana';Returns [applied]
Update with existsUPDATE ... IF EXISTS;LWT
Delete rowDELETE FROM users WHERE id=?;Writes a tombstone
Delete columnDELETE email FROM users WHERE id=?;Cell tombstone
Range deleteDELETE FROM events WHERE user_id=? AND ts < ?;Range tombstone; cheaper than many row deletes
Delete conditionalDELETE FROM users WHERE id=? IF EXISTS;LWT
Unlogged batchBEGIN UNLOGGED BATCH ... APPLY BATCH;Use for one partition only
Logged batchBEGIN BATCH ... APPLY BATCH;Atomicity across partitions, not isolation; slower
Counter batchBEGIN COUNTER BATCH ... APPLY BATCH;Counter updates only
Batch limitsbatch_size_warn_threshold 5 KiB, batch_size_fail_threshold 50 KiBDefaults in cassandra.yaml for multiple-partition batches; large batches overload the coordinator
Prepared statementsPREPARE through the driver, ? markersAlways use for repeated queries
LWT costPaxos: several round trips per conditional writeAvoid on hot keys; Accord is not in the 5.0 docs

References: CQL DML, cassandra.yaml.

Consistency levels ​

LevelReplicas neededNotes
ANYany node incl. hinted handoffWrites only; weakest
ONE / TWO / THREE1 / 2 / 3 replicasFast, weak
QUORUMRF/2 + 1 across all DCsStrong when reads and writes use QUORUM
LOCAL_QUORUMQuorum in the local DCDefault choice for multi-DC
EACH_QUORUMQuorum in every DCWrites only; high latency
ALLEvery replicaOne node down means failure
LOCAL_ONEOne replica in the local DCFast reads
SERIAL / LOCAL_SERIALPaxos quorumReads that see committed LWT; set via serial consistency
Strong consistency formulaR + W > RFRF=3: QUORUM + QUORUM = 4 > 3
Read repairChance per read mismatchBlocking read repair on mismatch at QUORUM
Hinted handoffStored up to max_hint_window (3 h)Not a substitute for repair

References: Dynamo architecture, Hints, Read repair.

SELECT restrictions ​

TaskCommandNotes
By partition keySELECT * FROM events WHERE user_id=?;Required for efficient queries
Clustering rangeWHERE user_id=? AND ts > ? AND ts <= ?Restrict clustering columns in order
OrderORDER BY ts DESCOnly within one partition and in the table order or its reverse
LimitLIMIT 100 / PER PARTITION LIMIT 1
INWHERE user_id IN (?,?)Hits many coordinators; prefer parallel queries
ALLOW FILTERINGSELECT * FROM t WHERE col=? ALLOW FILTERING;Full scan cost; never on large tables
token()WHERE token(user_id) > ? AND token(user_id) <= ?Full-table scans by token range
PagingDriver PageSize and PageStateNever OFFSET (not supported)
Aggregatescount(*), min, max, sum, avgSingle partition is cheap; cluster-wide count is a scan
writetime / ttlSELECT writetime(col), ttl(col) FROM t WHERE ...Inspect cell metadata
JSONSELECT JSON * FROM t; / INSERT INTO t JSON '{...}';
BYPASS CACHESELECT ... BYPASS CACHE;ScyllaDB scan hint to skip the row cache
Prefix pitfallSkipping a clustering column is rejectedNeed the earlier columns first

References: CQL DML SELECT, ScyllaDB SELECT, ScyllaDB CQL extensions.

Collections and UDTs ​

TypeExampleNotes
list<T>tags list<text>; SET tags = tags + ['a']Ordered, append and prepend; element update by index reads before write
set<T>emails set<text>; SET emails = emails + {'x'}Sorted, unique
map<K,V>attrs map<text,text>; SET attrs['k'] = 'v'DELETE attrs['k']
Frozenfrozen<list<int>>Stored as one blob; usable in primary keys; replaced as a whole
Non-frozendefault for collectionsPer-element cells; overwrite creates a range tombstone
UDTCREATE TYPE addr (street text, city text); then home frozen<addr>Alter with ALTER TYPE addr ADD zip text;
Tuplepair tuple<int, text>Always frozen
Size guidanceKeep collections under a few hundred itemsCollections are read whole
Vector (Cassandra 5)embedding vector<float, 768> with an ANN SAI indexORDER BY embedding ANN OF [..] LIMIT 10

References: CQL types, Vector search.

Indexes (SAI and secondary) ​

TaskCommandNotes
SAI indexCREATE INDEX ON app.users (country) USING 'sai';Storage-attached index, Cassandra 5.0
Named SAICREATE CUSTOM INDEX idx ON t (col) USING 'StorageAttachedIndex';Works on collections with VALUES, KEYS, ENTRIES
Text analysisWITH OPTIONS = {'case_sensitive': 'false', 'normalize': 'true'}SAI string options
SAI queries=, range on numerics, CONTAINS, AND across indexed columnsStill scoped by partition key when possible
Legacy secondaryCREATE INDEX ON t (col);Local to node; avoid at high cardinality
Drop indexDROP INDEX idx;
Cassandra ruleQuery a single partition or use SAINever rely on indexes for hot paths
ScyllaDB global indexCREATE INDEX ON t (col);Global secondary index; also local index CREATE INDEX ON t ((pk), col)
Materialized viewalternative to indexesDenormalized copy with another partition key

References: SAI working with, CREATE CUSTOM INDEX, ScyllaDB secondary indexes.

nodetool essentials ​

TaskCommandNotes
Cluster statenodetool statusUN up normal, DN down, UJ joining, UL leaving, UM moving
Node infonodetool infoLoad, uptime, heap, tokens
Ringnodetool ring / nodetool describeclusterSchema versions should agree
Repairnodetool repair -full app users-pr primary range only; incremental is the default repair type, -full forces a full repair
Repair schedulingRun within gc_grace_secondsRepair more often than gc_grace_seconds; the 5.0 docs describe an Auto Repair scheduler, disabled by default
Compaction statsnodetool compactionstats -HPending tasks and progress
Compact manuallynodetool compact app usersAvoid with STCS in production
Table statsnodetool tablestats app.usersRead and write latency, SSTable count, tombstones per read, partition sizes
Histogramsnodetool tablehistograms app usersLatency percentiles and partition size
Thread poolsnodetool tpstatsLook for Pending and Blocked
Proxy latencynodetool proxyhistogramsCoordinator-level latency
Flushnodetool flush app usersMemtable to SSTable
Snapshotnodetool snapshot -t pre_upgrade app / clearsnapshot / listsnapshotsHard links; cheap
Cleanupnodetool cleanupRun on existing nodes after adding capacity
Decommissionnodetool decommissionStreams data away, then leaves
Remove dead nodenodetool removenode <host-id>When the node cannot return; assassinate as a last resort
Drainnodetool drainBefore a stop or upgrade
Stream statenodetool netstatsStreaming progress
Gossipnodetool gossipinfo
Throttlenodetool setcompactionthroughput 64 / setstreamthroughputMiB per second; 0 disables compaction throttling
Log levelnodetool setlogginglevel org.apache.cassandra DEBUG
Rebuildnodetool rebuild dc1Populate a new DC from an existing one

References: nodetool, Repair, Auto Repair.

Compaction ​

StrategyUse forNotes
SizeTieredCompactionStrategyWrite-heavy, defaultDefault class in the CQL docs; buckets SSTables of similar size; large SSTables need much temporary disk space
LeveledCompactionStrategyRead-heavy, small rowsLow read amplification, high write amplification
TimeWindowCompactionStrategyTime series with TTLAvoid updates and deletes in old windows
UnifiedCompactionStrategyCassandra 5.0Recommended for new tables since 5.0; scaling_parameters replaces STCS and LCS tuning
ChangeALTER TABLE t WITH compaction = {'class':'LeveledCompactionStrategy'};Triggers rewrites over time
Tombstone tuningtombstone_threshold, unchecked_tombstone_compactionCompact SSTables dominated by tombstones
ScyllaDB extraIncrementalCompactionStrategy, ICSSame amplification as STCS but avoids its 2x temporary space; edition not verified

References: Compaction overview, UCS, ScyllaDB compaction strategies.

Monitoring ​

TaskCommandNotes
Tombstone warningtombstone_warn_threshold (1000), tombstone_failure_threshold (100000)Logged as Read X live rows and Y tombstone cells; a query aborts above failure
Fix tombstonesLower TTL churn, avoid queue patterns, smaller partitions, TWCSCheck with nodetool tablestats
Large partitionspartition_size_warn_thresholdGuardrail in cassandra.yaml (replaces the deprecated compaction_large_partition_warning_threshold); ScyllaDB has system.large_partitions
Slow queriesslow_query_log_timeout (500 ms)Logged in debug.log
Latencynodetool tablestats, proxyhistogramsCompare local read latency with coordinator latency
Dropped messagesnodetool tpstats bottom sectionMUTATION, READ drops mean overload
Pending compactionsnodetool compactionstatsSustained growth means falling behind
Hintsnodetool statushandoff / listpendinghints
Virtual tablesSELECT * FROM system_views.thread_pools;The 5.0 docs also list clients, sstable_tasks, settings
Metrics exportJMX, virtual tables, external reportersCassandra metrics use Dropwizard Metrics; ScyllaDB exposes Prometheus on port 9180
Auditaudit_logging_options, Full Query Logging via fqltool

References: cassandra.yaml, Virtual tables, Metrics, Full query logging.

ScyllaDB specifics ​

TopicDetailNotes
ArchitectureShard-per-core (Seastar), no JVMEach CPU core owns a shard of data
nodetoolCalls the REST API; many commands match Cassandranodetool status, repair, cleanup, compact, drain, snapshot, tablestats work
Not supportedJMX-based toolingScyllaDB exposes a REST API on port 10000
RepairScylla Manager schedules repairsRow-level repair is the default engine
TabletsPer-table data distribution units, elastic scalingUsed by default for new keyspaces; opt out with tablets = {'enabled': false}
Workload prioritizationCREATE SERVICE_LEVELIsolates OLTP and analytics; edition not verified
AlternatorDynamoDB-compatible API, example alternator_port: 8000Enable with alternator_port and alternator_write_isolation
Alternator isolationonly_rmw_uses_lwt, always, forbid, unsafeValues of alternator_write_isolation; controls LWT use for writes
CDCALTER TABLE t WITH cdc = {'enabled': true};Creates a CDC log table (its name was not verified)
Per-partition rate limitWITH per_partition_rate_limit = {'max_writes_per_second': 100}Overload protection, not a precise limit; also max_reads_per_second
Toolsscylla-server, Scylla Monitoring Stack, Scylla Managerscyllatop and Grafana bundle not verified
Tuningperftune.pyscylla_setup and scylla_io_setup not verified
DriverUse shard-aware drivers (scylladb/gocql fork)Shard-aware transport port 19042 (19142 with TLS)

References: ScyllaDB Alternator, ScyllaDB nodetool, ScyllaDB admin and ports, Workload prioritization, CDC.

Go (gocql) ​

go
package main

import (
	"fmt"
	"log"
	"time"

	"github.com/gocql/gocql"
)

func main() {
	cluster := gocql.NewCluster("10.0.0.1", "10.0.0.2", "10.0.0.3")
	cluster.Keyspace = "app"
	cluster.Consistency = gocql.LocalQuorum
	cluster.Timeout = 2 * time.Second
	cluster.PoolConfig.HostSelectionPolicy = gocql.TokenAwareHostPolicy(
		gocql.DCAwareRoundRobinPolicy("dc1"))
	cluster.RetryPolicy = &gocql.ExponentialBackoffRetryPolicy{NumRetries: 3}
	cluster.Authenticator = gocql.PasswordAuthenticator{Username: "app", Password: "secret"}

	session, err := cluster.CreateSession()
	if err != nil {
		log.Fatal(err)
	}
	defer session.Close()

	err = session.Query(
		`INSERT INTO events (user_id, ts, kind) VALUES (?, now(), ?) USING TTL 86400`,
		gocql.TimeUUID(), "login").Exec()
	if err != nil {
		log.Fatal(err)
	}

	var kind string
	iter := session.Query(`SELECT kind FROM events WHERE user_id = ?`, gocql.TimeUUID()).
		PageSize(100).Iter()
	for iter.Scan(&kind) {
		fmt.Println(kind)
	}
	if err := iter.Close(); err != nil {
		log.Fatal(err)
	}

	applied, err := session.Query(
		`INSERT INTO users (id, name) VALUES (?, ?) IF NOT EXISTS`,
		gocql.TimeUUID(), "Ana").ScanCAS()
	fmt.Println(applied, err)
}
TaskCommandNotes
Installgo get github.com/gocql/gocqlScyllaDB users: add a replace directive pointing github.com/gocql/gocql at github.com/scylladb/gocql
Batchb := session.NewBatch(gocql.UnloggedBatch); b.Query(...); session.ExecuteBatch(b)Same partition only
Idempotent.Idempotent(true)Allows retries and speculative execution
Speculativecluster.SpeculativeExecutionPolicy = &gocql.SimpleSpeculativeExecution{NumAttempts: 1, TimeoutDelay: 50*time.Millisecond}Needs idempotent queries
Per-query CL.Consistency(gocql.One) / .SerialConsistency(gocql.LocalSerial)
Unset valuesgocql.UnsetValueAvoids writing tombstones for nil fields
Page stateiter.PageState() and .PageState(state)Stateless paging for APIs

References: gocql package, scylladb/gocql.

PHP note ​

TopicDetailNotes
DataStax PHP driverdatastax/php-driver (C/C++ extension, archived)Wrapper around the DataStax C/C++ driver; repository archived, no active development
Recommended approachHTTP API in front of CassandraStargate details not verified; call over HTTP with the Laravel Http client
Astra DBData API over HTTP with JSONDocumented by DataStax for Astra DB Serverless
ScyllaDB AlternatorDynamoDB-compatible API on alternator_portUsing the AWS SDK for PHP against it was not verified
LaravelNo first-party driverWrap HTTP clients in a repository class

References: DataStax PHP driver, Astra DB Data API.

References ​

Built by Morteza Negahi