# Apache Cassandra: A Practical Guide to Query-First Design

Imagine a database with no primary server. Every node can take a write. You can unplug one machine, or lose a whole data centre, and the applications keep reading and writing as if nothing happened. Adding capacity means adding machines, with no downtime.

Now the price: you may not join tables, you may not filter by any column you fancy, and you must know your queries before you create your first table.

That trade is Apache Cassandra. Teams that accept it get a database that stays up and absorbs enormous write volumes. Teams that expect a relational database with extra servers have a bad year. This guide is about being in the first group.

## What Cassandra is

Apache Cassandra is an open-source, distributed database, originally built at Facebook and now a project of the Apache Software Foundation under the Apache 2.0 licence. It is usually described as a wide-column store.

Data lives in tables with rows and columns, and you query it with **CQL** (Cassandra Query Language), which looks a lot like SQL. The resemblance is only skin deep. Underneath, Cassandra is a giant partitioned key-value system:

| Term | Meaning |
|---|---|
| Node | One Cassandra server |
| Cluster | All the nodes working together. They are peers; none is in charge |
| Keyspace | A namespace for tables, like a database. Replication is set here |
| Partition key | The part of the primary key that decides which nodes hold a row |
| Partition | All rows that share a partition key value, stored together |
| Clustering columns | The rest of the primary key, which sorts rows inside a partition |
| Replication factor | How many nodes keep a copy of each partition |
| Consistency level | How many of those copies must answer before a read or write succeeds |

Cassandra hashes the partition key to pick the nodes. A query that names the partition key goes straight to the right machines. A query that does not would have to ask every node, so Cassandra refuses it by default.

## Why teams choose it

### It stays available

With no primary node there is no failover to wait for. If a node is down, the others serve its data and hand it the missed writes when it returns. Replication across data centres and cloud regions is a built-in setting, not an add-on.

### Writes are cheap

A write is appended to a log and to memory, then acknowledged. Files on disk are never updated in place. This makes Cassandra very good at taking in data continuously: sensor readings, events, messages, activity histories.

### It grows in a straight line

Need more capacity? Add nodes. The cluster rebalances while it stays online, and capacity grows roughly in proportion to the number of nodes.

### Consistency is a dial

For each query you choose how many replicas must respond. Fewer means faster and more available. More means stronger guarantees. You can choose differently for different operations.

## Where Cassandra fits, and where it does not

**A strong choice for:**

- Time-series and sensor data
- Messaging, feeds and activity logs
- Very write-heavy workloads
- Services that must stay up across several regions
- Large data sets with a small number of known access patterns

**Look elsewhere when:**

- **Your data fits on one server.** PostgreSQL or MySQL will be far simpler, and they give you joins and transactions.
- **You need ad hoc queries.** Analysts cannot explore a Cassandra table by filtering on arbitrary columns. Use a relational database or an analytics store such as ClickHouse.
- **You need multi-row transactions or strict relational integrity.** There are no foreign keys and no joins.
- **Your access patterns are still unknown.** Changing how you query usually means building a new table and copying the data.
- **Nobody on the team will operate it.** A cluster needs monitoring, repairs and capacity planning. A managed service, or ScyllaDB (a compatible alternative that speaks the same protocol), may suit a small team better.

## Using it the right way

Try it locally with Docker, then open `cqlsh`, the CQL shell:

```bash
docker run --name cassandra -d -p 9042:9042 cassandra
docker exec -it cassandra cqlsh
```

### Create the keyspace with a real replication setting

```sql
CREATE KEYSPACE shop
  WITH replication = {'class': 'NetworkTopologyStrategy', 'datacenter1': 3};
```

`NetworkTopologyStrategy` with a count per data centre is the right choice for production. Three copies is the usual number: it lets you lose one node and still reach a majority. On a single-node test container, use a count of 1.

### Design one table per query

This is the rule that matters most. Start from the question the application asks, then build a table that answers it from one partition.

Question: "Show a customer's most recent orders."

```sql
CREATE TABLE shop.orders_by_customer (
  customer_id uuid,
  order_time  timestamp,
  order_id    uuid,
  total       decimal,
  status      text,
  PRIMARY KEY ((customer_id), order_time, order_id)
) WITH CLUSTERING ORDER BY (order_time DESC, order_id ASC);
```

Read the primary key in two parts. `(customer_id)` in the inner brackets is the partition key: all of one customer's orders live together. `order_time, order_id` are clustering columns: inside the partition, rows are stored sorted by time, newest first.

The query is now a single, fast read:

```sql
SELECT order_id, order_time, total, status
FROM shop.orders_by_customer
WHERE customer_id = 5b6962dd-3f90-4c93-8f61-eabfa4a803e2
LIMIT 20;
```

If you also need "find an order by its id", create a second table, `orders_by_id`, and write to both. Duplicating data is normal in Cassandra. Disk is cheaper than a query that touches every node.

### Keep partitions bounded

A partition that grows forever becomes slow to read and hard for the cluster to maintain. A common guideline is to keep a partition under roughly 100 MB.

For data that keeps arriving, add a time bucket to the partition key:

```sql
CREATE TABLE shop.readings_by_sensor_day (
  sensor_id    uuid,
  day          date,
  reading_time timestamp,
  value        double,
  PRIMARY KEY ((sensor_id, day), reading_time)
) WITH CLUSTERING ORDER BY (reading_time DESC);
```

Each sensor now gets a new partition every day.

### Choose a consistency level

With three replicas, `QUORUM` means two must respond. If you write at `QUORUM` and read at `QUORUM`, every read overlaps with the latest write, so you see current data while still tolerating one node being down. In a multi-region cluster, `LOCAL_QUORUM` does the same within the local data centre and avoids waiting on a distant one.

```sql
CONSISTENCY LOCAL_QUORUM;
```

That command sets the level in `cqlsh`. Applications set it in the driver.

### Let data expire

```sql
INSERT INTO shop.readings_by_sensor_day (sensor_id, day, reading_time, value)
VALUES (uuid(), '2026-03-01', toTimestamp(now()), 21.5)
USING TTL 2592000;
```

The row disappears after 30 days (2,592,000 seconds). For time-series tables this is far kinder to the cluster than running deletes.

### Understand deletes

Cassandra cannot remove data in place, so a delete writes a marker called a **tombstone**. The data and its tombstone are cleaned up later by compaction. Reads must skip over tombstones, so a partition full of them is slow, and a query that scans too many will fail outright. Avoid designs that delete constantly, such as using a table as a queue.

### Run repairs

Nodes can miss writes while they are down. **Repair** compares replicas and fixes differences:

```bash
nodetool repair shop
```

Every node should be repaired within the table's `gc_grace_seconds` (ten days by default). Otherwise a node that missed a delete can bring the deleted data back. Schedule repairs; do not wait for a problem.

## Common mistakes

- **Modelling it like a relational database.** Normalised tables and plans for joins do not work. Model the queries.
- **Reaching for `ALLOW FILTERING`.** It tells Cassandra to scan and discard rows, possibly across the whole cluster. If a query needs it in production, the table is wrong for that query.
- **Unbounded partitions.** One partition per user for all time, or one partition for a whole event type, will eventually hurt.
- **Queue-like tables.** Insert, read, delete, repeat creates a wall of tombstones.
- **Overusing lightweight transactions.** `INSERT ... IF NOT EXISTS` is useful for things like unique usernames, but each one needs several round trips between replicas. Keep them rare.
- **Secondary indexes on high-cardinality columns.** They can turn one query into a request to every node. A second table is usually better.
- **`SimpleStrategy` in production.** It ignores racks and data centres. Use `NetworkTopologyStrategy`.
- **Skipping repair.** Replicas drift apart, and deleted data can reappear.
- **Reading at `ALL`.** One slow or dead node then fails every read.

## Quick reference

| Task | Command |
|---|---|
| Open the shell | `cqlsh host 9042 -u user` |
| List keyspaces | `DESCRIBE KEYSPACES;` |
| Show a table definition | `DESCRIBE TABLE shop.orders_by_customer;` |
| Set consistency in the shell | `CONSISTENCY LOCAL_QUORUM;` |
| Trace a query | `TRACING ON;` |
| Cluster and node state | `nodetool status` |
| Table statistics, including partition sizes | `nodetool tablestats shop.orders_by_customer` |
| Repair a keyspace | `nodetool repair shop` |
| Flush memory to disk | `nodetool flush` |
| Take a snapshot backup | `nodetool snapshot shop` |

Cassandra is strict about one thing: know your queries first. Design a table for each, keep partitions bounded, repair on schedule, and it delivers exactly what it promises.

## Exploring Cassandra with CreamDB

`cqlsh` is the standard tool. When you want to look around a cluster from a browser, [CreamDB](https://www.creamdb.com) connects to Cassandra with nothing to install. ScyllaDB works through the same connection type, since it speaks the same protocol.

What you get today:

- Keyspaces listed in a tree, your own first and the system ones last, with their tables and materialized views.
- Columns, indexes and the table definition for each table.
- An editor for CQL with history, and results in a grid you can export.
- An assistant you can ask in plain English, which writes the CQL and shows the result.

The assistant only reads on its own. Any change waits as an approval card that you answer, and read-only mode on the server blocks writes.

Two honest limits. The Status panel and the Users and roles page are not available for Cassandra yet. And because CreamDB is hosted, the cluster's CQL port has to be reachable from the internet, with authentication switched on.

It is free to start.

