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
| Task | Command | Notes |
|---|---|---|
| Connect | cqlsh host 9042 -u cassandra -p secret | Default port 9042; ScyllaDB uses the same CQL port |
| TLS | cqlsh --ssl host | Configure ~/.cassandra/cqlshrc |
| Run statement | cqlsh -e "SELECT * FROM app.users LIMIT 5" | |
| Run file | cqlsh -f schema.cql | Idempotent DDL with IF NOT EXISTS |
| Keyspace on start | cqlsh -k app | Same as USE app; |
| Consistency | CONSISTENCY QUORUM; | Shell-level setting; CONSISTENCY; shows it |
| Serial consistency | SERIAL CONSISTENCY LOCAL_SERIAL; | For lightweight transactions |
| Tracing | TRACING ON; | Per-query trace of replicas and timings |
| Expand output | EXPAND ON; | One field per line |
| Paging | PAGING 100; / PAGING OFF; | Page size in the shell |
| Describe | DESCRIBE KEYSPACES; DESCRIBE TABLE app.users; DESCRIBE CLUSTER; | DESCRIBE KEYSPACE app prints full schema |
| Copy in/out | COPY 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=60 | Default 10 s |
| Version | cqlsh --version / SELECT release_version FROM system.local; |
References: cqlsh.
Keyspaces and replication
| Task | Command | Notes |
|---|---|---|
| SimpleStrategy | CREATE KEYSPACE dev WITH replication = {'class':'SimpleStrategy','replication_factor':1}; | Single data center only; dev and test |
| NetworkTopologyStrategy | CREATE 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 RF | ALTER KEYSPACE app WITH replication = {...}; then nodetool repair -full app | Raising RF requires repair to populate new replicas |
| Drop | DROP KEYSPACE app; | Takes a snapshot first if auto_snapshot is true |
| Rule of thumb | RF = 3 per data center | Allows LOCAL_QUORUM with one node down |
| Snitch | GossipingPropertyFileSnitch (cassandra-rackdc.properties) | Cloud snitches exist for EC2 and GCE |
| System keyspaces | system, system_schema, system_auth, system_distributed, system_traces | Names 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
| Task | Command | Notes |
|---|---|---|
| Create table | CREATE 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 key | PRIMARY KEY ((tenant, day), ts) | Splits large partitions; bucket by time |
| Clustering order | WITH CLUSTERING ORDER BY (ts DESC) | Latest first without sorting at read time |
| Static column | team text STATIC | One value per partition |
| Default TTL | WITH default_time_to_live = 86400 | Seconds; applies to new writes |
| Compaction option | WITH compaction = {'class':'TimeWindowCompactionStrategy','compaction_window_unit':'DAYS','compaction_window_size':1} | See compaction table |
| Compression | WITH compression = {'class':'LZ4Compressor','chunk_length_in_kb':16} | ZstdCompressor is among the 5.0 compressors; default chunk length is 64 KiB |
| gc_grace | WITH gc_grace_seconds = 864000 | Default 10 days; repair within this window |
| Caching | WITH caching = {'keys':'ALL','rows_per_partition':'NONE'} | |
| Speculative retry | WITH speculative_retry = '99PERCENTILE' | |
| Alter | ALTER TABLE t ADD col int; / DROP col; / WITH ... | Cannot change the primary key or column types freely |
| Drop / truncate | DROP TABLE t; / TRUNCATE t; | Truncate permanently removes all data but keeps the table |
| Types | text int bigint uuid timeuuid timestamp date time boolean decimal double float blob inet counter varint duration | timeuuid has time ordering |
| Counter table | CREATE 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 view | CREATE MATERIALIZED VIEW v AS SELECT ... PRIMARY KEY (a, b); | Experimental in Cassandra; supported in ScyllaDB |
| Primary key rule | Query-first design: one table per query | No joins; denormalize |
References: CQL DDL, Types, Materialized views, cassandra.yaml.
DML
| Task | Command | Notes |
|---|---|---|
| Insert | INSERT INTO users (id, name) VALUES (uuid(), 'Ana'); | INSERT is an upsert |
| Insert if absent | INSERT ... IF NOT EXISTS; | Lightweight transaction (Paxos) |
| With TTL | INSERT ... USING TTL 3600; | Seconds; cell expires into a tombstone |
| With timestamp | INSERT ... USING TIMESTAMP 1700000000000000; | Microseconds; last write wins |
| Update | UPDATE users SET name='Bo' WHERE id=?; | Also an upsert |
| Conditional update | UPDATE users SET name='Bo' WHERE id=? IF name='Ana'; | Returns [applied] |
| Update with exists | UPDATE ... IF EXISTS; | LWT |
| Delete row | DELETE FROM users WHERE id=?; | Writes a tombstone |
| Delete column | DELETE email FROM users WHERE id=?; | Cell tombstone |
| Range delete | DELETE FROM events WHERE user_id=? AND ts < ?; | Range tombstone; cheaper than many row deletes |
| Delete conditional | DELETE FROM users WHERE id=? IF EXISTS; | LWT |
| Unlogged batch | BEGIN UNLOGGED BATCH ... APPLY BATCH; | Use for one partition only |
| Logged batch | BEGIN BATCH ... APPLY BATCH; | Atomicity across partitions, not isolation; slower |
| Counter batch | BEGIN COUNTER BATCH ... APPLY BATCH; | Counter updates only |
| Batch limits | batch_size_warn_threshold 5 KiB, batch_size_fail_threshold 50 KiB | Defaults in cassandra.yaml for multiple-partition batches; large batches overload the coordinator |
| Prepared statements | PREPARE through the driver, ? markers | Always use for repeated queries |
| LWT cost | Paxos: several round trips per conditional write | Avoid on hot keys; Accord is not in the 5.0 docs |
References: CQL DML, cassandra.yaml.
Consistency levels
| Level | Replicas needed | Notes |
|---|---|---|
ANY | any node incl. hinted handoff | Writes only; weakest |
ONE / TWO / THREE | 1 / 2 / 3 replicas | Fast, weak |
QUORUM | RF/2 + 1 across all DCs | Strong when reads and writes use QUORUM |
LOCAL_QUORUM | Quorum in the local DC | Default choice for multi-DC |
EACH_QUORUM | Quorum in every DC | Writes only; high latency |
ALL | Every replica | One node down means failure |
LOCAL_ONE | One replica in the local DC | Fast reads |
SERIAL / LOCAL_SERIAL | Paxos quorum | Reads that see committed LWT; set via serial consistency |
| Strong consistency formula | R + W > RF | RF=3: QUORUM + QUORUM = 4 > 3 |
| Read repair | Chance per read mismatch | Blocking read repair on mismatch at QUORUM |
| Hinted handoff | Stored up to max_hint_window (3 h) | Not a substitute for repair |
References: Dynamo architecture, Hints, Read repair.
SELECT restrictions
| Task | Command | Notes |
|---|---|---|
| By partition key | SELECT * FROM events WHERE user_id=?; | Required for efficient queries |
| Clustering range | WHERE user_id=? AND ts > ? AND ts <= ? | Restrict clustering columns in order |
| Order | ORDER BY ts DESC | Only within one partition and in the table order or its reverse |
| Limit | LIMIT 100 / PER PARTITION LIMIT 1 | |
| IN | WHERE user_id IN (?,?) | Hits many coordinators; prefer parallel queries |
| ALLOW FILTERING | SELECT * 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 |
| Paging | Driver PageSize and PageState | Never OFFSET (not supported) |
| Aggregates | count(*), min, max, sum, avg | Single partition is cheap; cluster-wide count is a scan |
| writetime / ttl | SELECT writetime(col), ttl(col) FROM t WHERE ... | Inspect cell metadata |
| JSON | SELECT JSON * FROM t; / INSERT INTO t JSON '{...}'; | |
| BYPASS CACHE | SELECT ... BYPASS CACHE; | ScyllaDB scan hint to skip the row cache |
| Prefix pitfall | Skipping a clustering column is rejected | Need the earlier columns first |
References: CQL DML SELECT, ScyllaDB SELECT, ScyllaDB CQL extensions.
Collections and UDTs
| Type | Example | Notes |
|---|---|---|
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'] |
| Frozen | frozen<list<int>> | Stored as one blob; usable in primary keys; replaced as a whole |
| Non-frozen | default for collections | Per-element cells; overwrite creates a range tombstone |
| UDT | CREATE TYPE addr (street text, city text); then home frozen<addr> | Alter with ALTER TYPE addr ADD zip text; |
| Tuple | pair tuple<int, text> | Always frozen |
| Size guidance | Keep collections under a few hundred items | Collections are read whole |
| Vector (Cassandra 5) | embedding vector<float, 768> with an ANN SAI index | ORDER BY embedding ANN OF [..] LIMIT 10 |
References: CQL types, Vector search.
Indexes (SAI and secondary)
| Task | Command | Notes |
|---|---|---|
| SAI index | CREATE INDEX ON app.users (country) USING 'sai'; | Storage-attached index, Cassandra 5.0 |
| Named SAI | CREATE CUSTOM INDEX idx ON t (col) USING 'StorageAttachedIndex'; | Works on collections with VALUES, KEYS, ENTRIES |
| Text analysis | WITH OPTIONS = {'case_sensitive': 'false', 'normalize': 'true'} | SAI string options |
| SAI queries | =, range on numerics, CONTAINS, AND across indexed columns | Still scoped by partition key when possible |
| Legacy secondary | CREATE INDEX ON t (col); | Local to node; avoid at high cardinality |
| Drop index | DROP INDEX idx; | |
| Cassandra rule | Query a single partition or use SAI | Never rely on indexes for hot paths |
| ScyllaDB global index | CREATE INDEX ON t (col); | Global secondary index; also local index CREATE INDEX ON t ((pk), col) |
| Materialized view | alternative to indexes | Denormalized copy with another partition key |
References: SAI working with, CREATE CUSTOM INDEX, ScyllaDB secondary indexes.
nodetool essentials
| Task | Command | Notes |
|---|---|---|
| Cluster state | nodetool status | UN up normal, DN down, UJ joining, UL leaving, UM moving |
| Node info | nodetool info | Load, uptime, heap, tokens |
| Ring | nodetool ring / nodetool describecluster | Schema versions should agree |
| Repair | nodetool repair -full app users | -pr primary range only; incremental is the default repair type, -full forces a full repair |
| Repair scheduling | Run within gc_grace_seconds | Repair more often than gc_grace_seconds; the 5.0 docs describe an Auto Repair scheduler, disabled by default |
| Compaction stats | nodetool compactionstats -H | Pending tasks and progress |
| Compact manually | nodetool compact app users | Avoid with STCS in production |
| Table stats | nodetool tablestats app.users | Read and write latency, SSTable count, tombstones per read, partition sizes |
| Histograms | nodetool tablehistograms app users | Latency percentiles and partition size |
| Thread pools | nodetool tpstats | Look for Pending and Blocked |
| Proxy latency | nodetool proxyhistograms | Coordinator-level latency |
| Flush | nodetool flush app users | Memtable to SSTable |
| Snapshot | nodetool snapshot -t pre_upgrade app / clearsnapshot / listsnapshots | Hard links; cheap |
| Cleanup | nodetool cleanup | Run on existing nodes after adding capacity |
| Decommission | nodetool decommission | Streams data away, then leaves |
| Remove dead node | nodetool removenode <host-id> | When the node cannot return; assassinate as a last resort |
| Drain | nodetool drain | Before a stop or upgrade |
| Stream state | nodetool netstats | Streaming progress |
| Gossip | nodetool gossipinfo | |
| Throttle | nodetool setcompactionthroughput 64 / setstreamthroughput | MiB per second; 0 disables compaction throttling |
| Log level | nodetool setlogginglevel org.apache.cassandra DEBUG | |
| Rebuild | nodetool rebuild dc1 | Populate a new DC from an existing one |
References: nodetool, Repair, Auto Repair.
Compaction
| Strategy | Use for | Notes |
|---|---|---|
SizeTieredCompactionStrategy | Write-heavy, default | Default class in the CQL docs; buckets SSTables of similar size; large SSTables need much temporary disk space |
LeveledCompactionStrategy | Read-heavy, small rows | Low read amplification, high write amplification |
TimeWindowCompactionStrategy | Time series with TTL | Avoid updates and deletes in old windows |
UnifiedCompactionStrategy | Cassandra 5.0 | Recommended for new tables since 5.0; scaling_parameters replaces STCS and LCS tuning |
| Change | ALTER TABLE t WITH compaction = {'class':'LeveledCompactionStrategy'}; | Triggers rewrites over time |
| Tombstone tuning | tombstone_threshold, unchecked_tombstone_compaction | Compact SSTables dominated by tombstones |
| ScyllaDB extra | IncrementalCompactionStrategy, ICS | Same amplification as STCS but avoids its 2x temporary space; edition not verified |
References: Compaction overview, UCS, ScyllaDB compaction strategies.
Monitoring
| Task | Command | Notes |
|---|---|---|
| Tombstone warning | tombstone_warn_threshold (1000), tombstone_failure_threshold (100000) | Logged as Read X live rows and Y tombstone cells; a query aborts above failure |
| Fix tombstones | Lower TTL churn, avoid queue patterns, smaller partitions, TWCS | Check with nodetool tablestats |
| Large partitions | partition_size_warn_threshold | Guardrail in cassandra.yaml (replaces the deprecated compaction_large_partition_warning_threshold); ScyllaDB has system.large_partitions |
| Slow queries | slow_query_log_timeout (500 ms) | Logged in debug.log |
| Latency | nodetool tablestats, proxyhistograms | Compare local read latency with coordinator latency |
| Dropped messages | nodetool tpstats bottom section | MUTATION, READ drops mean overload |
| Pending compactions | nodetool compactionstats | Sustained growth means falling behind |
| Hints | nodetool statushandoff / listpendinghints | |
| Virtual tables | SELECT * FROM system_views.thread_pools; | The 5.0 docs also list clients, sstable_tasks, settings |
| Metrics export | JMX, virtual tables, external reporters | Cassandra metrics use Dropwizard Metrics; ScyllaDB exposes Prometheus on port 9180 |
| Audit | audit_logging_options, Full Query Logging via fqltool |
References: cassandra.yaml, Virtual tables, Metrics, Full query logging.
ScyllaDB specifics
| Topic | Detail | Notes |
|---|---|---|
| Architecture | Shard-per-core (Seastar), no JVM | Each CPU core owns a shard of data |
| nodetool | Calls the REST API; many commands match Cassandra | nodetool status, repair, cleanup, compact, drain, snapshot, tablestats work |
| Not supported | JMX-based tooling | ScyllaDB exposes a REST API on port 10000 |
| Repair | Scylla Manager schedules repairs | Row-level repair is the default engine |
| Tablets | Per-table data distribution units, elastic scaling | Used by default for new keyspaces; opt out with tablets = {'enabled': false} |
| Workload prioritization | CREATE SERVICE_LEVEL | Isolates OLTP and analytics; edition not verified |
| Alternator | DynamoDB-compatible API, example alternator_port: 8000 | Enable with alternator_port and alternator_write_isolation |
| Alternator isolation | only_rmw_uses_lwt, always, forbid, unsafe | Values of alternator_write_isolation; controls LWT use for writes |
| CDC | ALTER TABLE t WITH cdc = {'enabled': true}; | Creates a CDC log table (its name was not verified) |
| Per-partition rate limit | WITH per_partition_rate_limit = {'max_writes_per_second': 100} | Overload protection, not a precise limit; also max_reads_per_second |
| Tools | scylla-server, Scylla Monitoring Stack, Scylla Manager | scyllatop and Grafana bundle not verified |
| Tuning | perftune.py | scylla_setup and scylla_io_setup not verified |
| Driver | Use 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)
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)
}| Task | Command | Notes |
|---|---|---|
| Install | go get github.com/gocql/gocql | ScyllaDB users: add a replace directive pointing github.com/gocql/gocql at github.com/scylladb/gocql |
| Batch | b := session.NewBatch(gocql.UnloggedBatch); b.Query(...); session.ExecuteBatch(b) | Same partition only |
| Idempotent | .Idempotent(true) | Allows retries and speculative execution |
| Speculative | cluster.SpeculativeExecutionPolicy = &gocql.SimpleSpeculativeExecution{NumAttempts: 1, TimeoutDelay: 50*time.Millisecond} | Needs idempotent queries |
| Per-query CL | .Consistency(gocql.One) / .SerialConsistency(gocql.LocalSerial) | |
| Unset values | gocql.UnsetValue | Avoids writing tombstones for nil fields |
| Page state | iter.PageState() and .PageState(state) | Stateless paging for APIs |
References: gocql package, scylladb/gocql.
PHP note
| Topic | Detail | Notes |
|---|---|---|
| DataStax PHP driver | datastax/php-driver (C/C++ extension, archived) | Wrapper around the DataStax C/C++ driver; repository archived, no active development |
| Recommended approach | HTTP API in front of Cassandra | Stargate details not verified; call over HTTP with the Laravel Http client |
| Astra DB | Data API over HTTP with JSON | Documented by DataStax for Astra DB Serverless |
| ScyllaDB Alternator | DynamoDB-compatible API on alternator_port | Using the AWS SDK for PHP against it was not verified |
| Laravel | No first-party driver | Wrap HTTP clients in a repository class |
References: DataStax PHP driver, Astra DB Data API.
References
- Cassandra 5.0 docs: https://cassandra.apache.org/doc/5.0/
- CQL reference: https://cassandra.apache.org/doc/5.0/cassandra/developing/cql/
- cqlsh: https://cassandra.apache.org/doc/5.0/cassandra/tools/cqlsh.html
- nodetool: https://cassandra.apache.org/doc/5.0/cassandra/tools/nodetool/nodetool.html
- Compaction: https://cassandra.apache.org/doc/5.0/cassandra/managing/operating/compaction/overview.html
- ScyllaDB docs: https://docs.scylladb.com/
- ScyllaDB Alternator: https://docs.scylladb.com/manual/stable/alternator/alternator.html
- gocql: https://github.com/gocql/gocql