Apache Cassandra Setup & Query-First Data Modeling for High-Write Workloads

Database tutorial - IT technology blog
Database tutorial - IT technology blog

Context & Why: Moving Beyond Relational Boundaries

Relational engines like PostgreSQL and MySQL are workhorses for transactional systems. MongoDB handles nested documents with ease. But when an IoT pipeline started throwing 85,000 sensor payloads per second at our PostgreSQL cluster, the infrastructure buckled.

Disk I/O pegged at 100%, row-level locks cascaded into query timeouts, and replication lag drifted past 40 seconds. Scaling up to a monster AWS r5.8xlarge instance cost thousands each month without solving the underlying architectural bottleneck. Manual sharding would have added months of application-level maintenance we could not justify.

That wall pushed us toward Apache Cassandra. Cassandra is a masterless, distributed NoSQL database built on peer-to-peer ring topology. Every node performs the same role. There is no primary node directing traffic, which eliminates single points of failure. The cluster distributes partitions across nodes using consistent hashing on token rings.

Write throughput is where Cassandra shines. When an incoming write hits a node, Cassandra immediately appends the record sequentially to an on-disk commit log. At the exact same time, it writes the data into an in-memory buffer called a Memtable.

Once both operations succeed, Cassandra returns an acknowledgment to the client—frequently in under 2 milliseconds. Later, background threads flush full Memtables to disk as immutable SSTables (Sorted String Tables). Because writes avoid random in-place disk overwrites, write throughput scales almost linearly as you add nodes.

That speed comes with a strict trade-off: you must adopt a Query-First Data Model. Traditional relational design normalizes data into isolated entities and relies on foreign keys with JOIN operations. Cassandra does not support joins across distributed partitions.

Instead, you design dedicated tables around every specific read query your application runs. Duplicating records across three or four tables feels counterintuitive at first. Yet that intentional denormalization ensures your queries pull from a single partition on a single node.

Installation: Deploying Cassandra on Ubuntu Linux

For production workloads, deploy Cassandra on dedicated bare-metal servers or compute-optimized cloud VMs (minimum 8 vCPUs, 32 GB RAM, and direct-attached NVMe storage) running Ubuntu 22.04 LTS. Cassandra 4.1 runs on OpenJDK 11.

1. System Prep and Java Runtime

Update package repositories and install the OpenJDK 11 headless runtime along with prerequisite transport utilities:

sudo apt update && sudo apt install -y openjdk-11-jdk-headless apt-transport-https gnupg curl
java -version

2. Configure Official Apache Repositories

Download the official Apache Cassandra signing key, store it in your apt keyring, and add the Cassandra 4.1.x Debian repository:

curl -fsSL https://downloads.apache.org/cassandra/KEYS | sudo gpg --dearmor -o /etc/apt/trusted.gpg.d/cassandra.gpg
echo "deb [signed-by=/etc/apt/trusted.gpg.d/cassandra.gpg] https://debian.cassandra.apache.org 41x main" | sudo tee /etc/apt/sources.list.d/cassandra.list

3. Install and Start the Cassandra Daemon

Pull the package index, install the daemon, and enable the systemd service:

sudo apt update
sudo apt install -y cassandra
sudo systemctl enable cassandra
sudo systemctl start cassandra

Verify that the process started cleanly:

sudo systemctl status cassandra

Configuration: Production Tuning & Query-First Schema Design

Out of the box, Cassandra boots with single-node loopback defaults. Transitioning to a production-ready node requires updating network bindings, tuning OS limits, and designing query-specific CQL tables.

1. Core Storage and Network Configuration

The main configuration file is located at /etc/cassandra/cassandra.yaml. Open it in your editor:

sudo nano /etc/cassandra/cassandra.yaml

Set the cluster identity, bind interfaces, and configure seed nodes:

cluster_name: 'ProductionTelemetryCluster'

# Private IP for internal gossip communication between nodes
listen_address: 192.168.1.50

# Private IP for CQL client traffic from application microservices
rpc_address: 192.168.1.50

# Seed nodes help joining members discover cluster topology
seed_provider:
    - class_name: org.apache.cassandra.locator.SimpleSeedProvider
      parameters:
          - seeds: "192.168.1.50,192.168.1.51"

# Production snitch for rack and datacenter awareness
endpoint_snitch: GossipingPropertyFileSnitch

# Commit logs should point to dedicated fast NVMe storage
commitlog_directory: /var/lib/cassandra/commitlog
data_file_directories:
    - /var/lib/cassandra/data

Save your changes and restart the daemon:

sudo systemctl restart cassandra

2. Query-First Data Modeling in CQL

Connect to your node using the CQL interactive shell (cqlsh):

cqlsh 192.168.1.50 9042

Suppose our telemetry service processes metric packets and must answer two specific access patterns:

  1. Q1: Fetch the most recent temperature and battery readings for a specific device.
  2. Q2: Look up all recorded sensor alerts across devices filtered by error code.

Always provision production keyspaces using NetworkTopologyStrategy rather than SimpleStrategy. This ensures multi-rack and multi-datacenter replication remain manageable as the cluster expands:

CREATE KEYSPACE telemetry_data 
WITH replication = {'class': 'NetworkTopologyStrategy', 'datacenter1': 3};

For Q1, we make device_id the partition key. The recorded_at timestamp serves as the clustering column, sorted in descending order on disk:

USE telemetry_data;

CREATE TABLE metrics_by_device (
    device_id uuid,
    recorded_at timestamp,
    temperature float,
    battery_level int,
    status_code text,
    PRIMARY KEY ((device_id), recorded_at)
) WITH CLUSTERING ORDER BY (recorded_at DESC);

Write operations insert rows into this partition with minimal overhead:

INSERT INTO metrics_by_device (device_id, recorded_at, temperature, battery_level, status_code)
VALUES (a3f81e20-72bd-11ee-b962-0242ac120002, toTimestamp(now()), 42.5, 88, 'WARN_OVERHEAT');

Retrieving the latest readings hits exactly one partition on disk without triggering table scans:

SELECT * FROM metrics_by_device 
WHERE device_id = a3f81e20-72bd-11ee-b962-0242ac120002 
  AND recorded_at >= '2026-11-20 00:00:00'
LIMIT 50;

For Q2, avoid adding a secondary index to status_code on the first table. Secondary indexes issue scatter-gather queries across every node in the cluster, which spikes CPU usage and blows past latency SLAs. Instead, dual-write the event into a second table designed specifically for status lookups:

CREATE TABLE metrics_by_status (
    status_code text,
    recorded_at timestamp,
    device_id uuid,
    temperature float,
    PRIMARY KEY ((status_code), recorded_at, device_id)
) WITH CLUSTERING ORDER BY (recorded_at DESC, device_id ASC);

3. Tuning JVM Heap and OS Kernel Settings

High-concurrency database workloads quickly exhaust standard Linux resource quotas. Adjust process and file limits by creating a custom security profile:

sudo tee /etc/security/limits.d/cassandra.conf <<EOF
cassandra - memlock unlimited
cassandra - nofile 1048576
cassandra - nproc 32768
cassandra - as unlimited
EOF

Swap is toxic to Cassandra. When Linux swaps JVM memory pages to disk, garbage collection pauses freeze cluster heartbeats and trigger false node-death alerts. Disable swap permanently:

sudo swapoff -a
sudo sed -i '/ swap / s/^\(.*\)$/#\1/g' /etc/fstab

Verification & Monitoring

Running a distributed ring in production demands reliable visibility into node gossip states, read/write latencies, and thread queue health.

1. Inspect Ring Status via nodetool

The nodetool binary is Cassandra’s primary operations interface. Check cluster membership and data distribution with:

nodetool status

Sample output from a healthy cluster:

Datacenter: datacenter1
=======================
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
--  Address       Load        Tokens  Owns (effective)  Host ID                               Rack
UN  192.168.1.50  14.22 GiB   16      66.7%             67b3f9dc-1c19-48c2-bb52-ef11086055d2  rack1
UN  192.168.1.51  13.88 GiB   16      66.7%             a8b29cf1-5d21-4f33-8a21-9d104519bc11  rack1
UN  192.168.1.52  14.05 GiB   16      66.7%             f4c102a9-8d19-491a-ae11-7c989128aa31  rack1

Confirm the first two characters on each row read UN (Up and Normal). A state showing DN (Down/Normal) indicates an unresponsive node that has dropped out of gossip.

2. Check Table Performance and Latency Metrics

To inspect read and write response times on a target table, run:

nodetool tablestats telemetry_data.metrics_by_device

Aim for a Local write latency under 1.0 ms and a Local read latency under 5.0 ms. Watch the SSTable count metric closely. If a single table accumulates more than 15 to 20 SSTables per partition read, compacting old files behind schedule is slowing query performance.

3. Track Dropped Mutations and Thread Pools

When write volume outpaces disk controllers or saturation exhausts worker threads, Cassandra drops incoming mutations. Inspect thread activity with:

nodetool tpstats

Look directly at the MutationStage row. While Active and Pending counts will spike during traffic surges, the Dropped column must remain strictly 0. If dropped mutations begin climbing, your storage subsystems cannot keep pace. Scale out by adding new nodes to distribute write tokens across a wider pool of hardware.

Share: