LearnThatStack Ace your next interview

Cassandra Database.
Interview cheat sheet.

Quick reference for Cassandra Database - sectioned for fast scanning. Skim the part you're shaky on, walk in confident.

Database Technologies 13-section reference ~8 min read

Summary

Apache Cassandra is a distributed NoSQL database designed for high availability and linear scalability. It follows the AP principle in CAP theorem (Availability + Partition tolerance) with eventual consistency. Key strengths include peer-to-peer architecture with no single point of failure, excellent write performance, and ability to handle massive datasets across multiple nodes. Essential for time-series data, high-throughput applications, and globally distributed systems. Data modeling follows a query-first approach with denormalization and uses CQL (Cassandra Query Language) for operations.

1. Core Concepts

What is Cassandra?

  • Distributed NoSQL database designed for handling large amounts of data across many commodity servers
  • AP system in CAP theorem (Availability + Partition tolerance)
  • Eventually consistent by default
  • Column-family data model
  • Peer-to-peer architecture (no master-slave)

Key Features

  • Linear scalability - Add nodes to increase capacity
  • No single point of failure - Every node is identical
  • High availability - Data replicated across nodes
  • Tunable consistency - Choose consistency level per operation
  • Write-optimized - Extremely fast writes

2. Architecture

Core Components

Node

  • Single instance of Cassandra
  • Contains data and participates in the cluster

Cluster (Ring)

  • Collection of nodes
  • Data distributed using consistent hashing

Datacenter

  • Logical grouping of nodes
  • Can be physical or cloud regions

Keyspace

  • Top-level namespace (like database in RDBMS)
  • Defines replication strategy and factor

Table (Column Family)

  • Collection of ordered columns
  • Schema-based since CQL3

Data Distribution

Partitioner

  • Determines how data is distributed across nodes
  • Murmur3Partitioner (default) - Uses MurmurHash

Token Ring

  • Each node assigned token ranges
  • Data placed based on partition key hash
-- Example: How partition key determines node
CREATE TABLE users (
    user_id UUID PRIMARY KEY,  -- Partition key
    name TEXT,
    email TEXT
);
-- user_id is hashed to determine which node stores this row

Storage Architecture

Write Path

  1. Commit Log - Durability (append-only)
  2. Memtable - In-memory structure
  3. SSTable - Immutable disk storage
Client Write → Commit Log → Memtable → (Flush) → SSTable

Read Path

  1. Check Memtable (memory)
  2. Check Row Cache (if enabled)
  3. Check Bloom Filters (probabilistic)
  4. Check Key Cache
  5. Read from SSTables

3. Data Modeling

Primary Key Components

Partition Key

  • Determines data distribution
  • First part of primary key

Clustering Key

  • Determines sort order within partition
  • Optional, follows partition key
-- Single partition key
CREATE TABLE users (
    user_id UUID PRIMARY KEY
);

-- Composite partition key
CREATE TABLE user_activities (
    user_id UUID,
    activity_date DATE,
    activity_id TIMEUUID,
    activity_type TEXT,
    PRIMARY KEY ((user_id, activity_date), activity_id)
);
-- Partition key: (user_id, activity_date)
-- Clustering key: activity_id

Data Types

Basic Types

-- Numeric
INT, BIGINT, FLOAT, DOUBLE, DECIMAL, VARINT

-- Text
TEXT, VARCHAR, ASCII

-- Time
TIMESTAMP, DATE, TIME, TIMEUUID

-- Other
UUID, BOOLEAN, BLOB, INET

Collection Types

-- Set (unique values)
CREATE TABLE users (
    user_id UUID PRIMARY KEY,
    emails SET<TEXT>
);

-- List (ordered, allows duplicates)
CREATE TABLE posts (
    post_id UUID PRIMARY KEY,
    tags LIST<TEXT>
);

-- Map (key-value pairs)
CREATE TABLE user_profiles (
    user_id UUID PRIMARY KEY,
    attributes MAP<TEXT, TEXT>
);

Modeling Patterns

Query-First Design

  • Model based on queries, not entities
  • Denormalization is normal
  • Data duplication is acceptable

Time Series Data

CREATE TABLE sensor_data (
    sensor_id UUID,
    date DATE,
    timestamp TIMESTAMP,
    value DOUBLE,
    PRIMARY KEY ((sensor_id, date), timestamp)
) WITH CLUSTERING ORDER BY (timestamp DESC);

Wide Rows

CREATE TABLE user_timeline (
    user_id UUID,
    posted_at TIMESTAMP,
    post_id UUID,
    content TEXT,
    PRIMARY KEY (user_id, posted_at)
) WITH CLUSTERING ORDER BY (posted_at DESC);

4. CQL (Cassandra Query Language)

DDL Operations

-- Create Keyspace
CREATE KEYSPACE myapp
WITH REPLICATION = {
    'class': 'SimpleStrategy',
    'replication_factor': 3
};

-- NetworkTopologyStrategy (Production)
CREATE KEYSPACE myapp
WITH REPLICATION = {
    'class': 'NetworkTopologyStrategy',
    'dc1': 3,
    'dc2': 2
};

-- Create Table
CREATE TABLE users (
    user_id UUID,
    email TEXT,
    created_at TIMESTAMP,
    PRIMARY KEY (user_id)
);

-- Alter Table
ALTER TABLE users ADD phone TEXT;

-- Create Index
CREATE INDEX ON users (email);

-- Create Materialized View
CREATE MATERIALIZED VIEW users_by_email AS
    SELECT * FROM users
    WHERE email IS NOT NULL
    PRIMARY KEY (email, user_id);

DML Operations

-- Insert
INSERT INTO users (user_id, email, created_at)
VALUES (uuid(), 'user@email.com', toTimestamp(now()));

-- Update
UPDATE users 
SET email = 'newemail@email.com' 
WHERE user_id = 550e8400-e29b-41d4-a716-446655440000;

-- Select
SELECT * FROM users WHERE user_id = 550e8400-e29b-41d4-a716-446655440000;

-- Delete
DELETE FROM users WHERE user_id = 550e8400-e29b-41d4-a716-446655440000;

-- Batch
BEGIN BATCH
    INSERT INTO users (user_id, email) VALUES (uuid(), 'user1@email.com');
    INSERT INTO users (user_id, email) VALUES (uuid(), 'user2@email.com');
APPLY BATCH;

TTL (Time To Live)

-- Insert with TTL (seconds)
INSERT INTO sessions (session_id, user_id, created_at)
VALUES (uuid(), uuid(), toTimestamp(now()))
USING TTL 3600;  -- Expires in 1 hour

-- Update with TTL
UPDATE users USING TTL 86400
SET temp_token = 'abc123'
WHERE user_id = uuid();

5. Consistency & Replication

Consistency Levels

Write Consistency Levels

  • ANY - At least one node (including hinted handoff)
  • ONE - At least one replica node
  • TWO - At least two replica nodes
  • THREE - At least three replica nodes
  • QUORUM - Majority of replicas (RF/2 + 1)
  • LOCAL_QUORUM - Quorum within local DC
  • EACH_QUORUM - Quorum in each DC
  • ALL - All replica nodes

Read Consistency Levels

  • Same as write (except ANY)
  • LOCAL_ONE - At least one replica in local DC
-- Set consistency level
CONSISTENCY QUORUM;

-- Per-query consistency
SELECT * FROM users USING CONSISTENCY LOCAL_QUORUM;

Replication Strategies

SimpleStrategy

  • Use for single datacenter
  • Replicas placed on consecutive nodes

NetworkTopologyStrategy

  • Use for multi-datacenter
  • Specify replicas per datacenter

Consistency Formula

For Strong Consistency:
W + R > RF

Where:
W = Write Consistency Level
R = Read Consistency Level
RF = Replication Factor

Example: QUORUM read + QUORUM write with RF=3
W=2 + R=2 > RF=3 ✓ (Strong consistency)

6. Performance & Optimization

Compaction Strategies

SizeTieredCompactionStrategy (STCS)

  • Default strategy
  • Good for write-heavy workloads
  • Combines SSTables of similar size

LeveledCompactionStrategy (LCS)

  • Good for read-heavy workloads
  • Maintains levels of SSTables
  • More predictable performance

TimeWindowCompactionStrategy (TWCS)

  • Best for time-series data
  • Compacts data within time windows
CREATE TABLE metrics (
    sensor_id UUID,
    timestamp TIMESTAMP,
    value DOUBLE,
    PRIMARY KEY (sensor_id, timestamp)
) WITH compaction = {
    'class': 'TimeWindowCompactionStrategy',
    'compaction_window_size': '1',
    'compaction_window_unit': 'DAYS'
};

Performance Tips

Partition Size

  • Keep partitions under 100MB
  • Avoid hot partitions
  • Monitor with nodetool cfstats

Tombstones

  • Deleted data creates tombstones
  • Too many tombstones slow reads
  • Set appropriate gc_grace_seconds

Secondary Indexes

  • Avoid high-cardinality columns
  • Local to each node
  • Use materialized views instead
-- Good index (low cardinality)
CREATE INDEX ON users (status);  -- status: 'active', 'inactive'

-- Bad index (high cardinality)
CREATE INDEX ON users (email);   -- Unique values

7. Operations & Monitoring

nodetool Commands

# Cluster Information
nodetool status          # Cluster status
nodetool info           # Node information
nodetool ring           # Token ring information

# Maintenance
nodetool repair         # Repair inconsistencies
nodetool cleanup        # Remove unnecessary data
nodetool compact        # Force compaction
nodetool flush          # Flush memtables

# Monitoring
nodetool cfstats        # Table statistics
nodetool tpstats        # Thread pool stats
nodetool compactionstats # Compaction progress

# Cache
nodetool invalidatekeycache
nodetool invalidaterowcache

JMX Metrics

  • Monitor heap usage
  • Track read/write latencies
  • Watch pending compactions
  • Check dropped messages

8. Best Practices

Data Modeling

  1. Model for queries - Don't normalize
  2. Denormalize data - Storage is cheap
  3. Avoid large partitions - Max 100MB
  4. Use appropriate data types - UUID for unique IDs
  5. Design for even distribution - Avoid hotspots

Query Patterns

  1. Always provide partition key in WHERE clause
  2. Limit use of ALLOW FILTERING
  3. Use prepared statements - Better performance
  4. Batch similar partitions - Not for performance

Operations

  1. Regular repairs - Maintain consistency
  2. Monitor partition sizes - Prevent large partitions
  3. Set appropriate timeouts - Avoid cascading failures
  4. Use LOCAL_QUORUM - For multi-DC setups

9. Cassandra vs Other Databases

vs Relational Databases (RDBMS)

  • ACID: Cassandra doesn't guarantee ACID properties
  • Joins: No support for complex joins or foreign keys
  • Schema: Flexible schema vs rigid structure
  • Scaling: Horizontal vs vertical scaling
  • Consistency: Eventual vs strong consistency

vs MongoDB

  • Data Model: Column-family vs Document store
  • Query Language: CQL vs MongoDB Query Language
  • Consistency: Tunable vs strong consistency options
  • Sharding: Automatic vs manual configuration

vs HBase

  • Architecture: Peer-to-peer vs master-slave
  • Query Interface: CQL support vs Java/REST APIs
  • Single Point of Failure: None vs HMaster dependency
  • Deployment: Simpler setup vs Hadoop ecosystem

10. Troubleshooting Common Issues

Performance Problems

  • Large Partitions: Monitor with nodetool cfstats, redesign data model
  • Tombstones: Set appropriate gc_grace_seconds, avoid excessive deletes
  • Hot Partitions: Use bucketing strategies, composite partition keys
  • Slow Reads: Check bloom filter false positives, row cache hit rate

Operational Issues

  • Write Timeouts: Increase write timeout, check disk I/O
  • Read Timeouts: Lower consistency level, add more replicas
  • Schema Disagreements: Run nodetool describecluster
  • Compaction Lag: Tune compaction settings, add more nodes

11. Advanced Topics

Lightweight Transactions (LWT)

-- Compare and Set
UPDATE users 
SET email = 'new@email.com' 
WHERE user_id = uuid()
IF email = 'old@email.com';

-- Insert if not exists
INSERT INTO users (user_id, email)
VALUES (uuid(), 'user@email.com')
IF NOT EXISTS;

User-Defined Types (UDT)

CREATE TYPE address (
    street TEXT,
    city TEXT,
    zip_code TEXT
);

CREATE TABLE users (
    user_id UUID PRIMARY KEY,
    name TEXT,
    addresses MAP<TEXT, FROZEN<address>>
);

SASI Indexes

CREATE CUSTOM INDEX ON users (email)
USING 'org.apache.cassandra.index.sasi.SASIIndex'
WITH OPTIONS = {'mode': 'CONTAINS'};

-- Allows: WHERE email LIKE '%@gmail.com'

Common Design Patterns

Chat/Messaging System

-- Messages by conversation
CREATE TABLE messages (
    conversation_id UUID,
    message_time TIMESTAMP,
    message_id TIMEUUID,
    sender_id UUID,
    content TEXT,
    PRIMARY KEY (conversation_id, message_time, message_id)
) WITH CLUSTERING ORDER BY (message_time DESC);

IoT Time Series Data

-- IoT sensor readings
CREATE TABLE sensor_readings (
    sensor_id UUID,
    date DATE,
    timestamp TIMESTAMP,
    temperature DOUBLE,
    humidity DOUBLE,
    PRIMARY KEY ((sensor_id, date), timestamp)
) WITH CLUSTERING ORDER BY (timestamp DESC);

Social Media Feed

-- User activity feed
CREATE TABLE user_feed (
    user_id UUID,
    activity_time TIMESTAMP,
    activity_id TIMEUUID,
    activity_type TEXT,
    details TEXT,
    PRIMARY KEY (user_id, activity_time, activity_id)
) WITH CLUSTERING ORDER BY (activity_time DESC);

Hot Partition Solution

-- Distribute hot data across buckets
CREATE TABLE page_views (
    page_id UUID,
    time_bucket INT,    -- 0-23 (hour of day)
    view_count COUNTER,
    PRIMARY KEY ((page_id, time_bucket))
);

12. Quick Reference

When to Use Cassandra

✅ High write throughput
✅ Linear scalability needed
✅ Geographic distribution
✅ No complex queries/JOINs
✅ Time-series data

When NOT to Use Cassandra

❌ ACID transactions required
❌ Complex queries with JOINs
❌ Small datasets
❌ Frequently changing schemas
❌ Strong consistency critical

Performance Checklist

  • Partition key well-distributed
  • Partitions under 100MB
  • Appropriate compaction strategy
  • Proper consistency levels
  • Regular repairs scheduled
  • Monitoring in place
  • Tombstone ratio acceptable
Found this useful? Pass it on.
Pro · $10/mo

The sheet is free. Pro goes deeper.

Pro opens the full question library behind every sheet, every refresher and a monthly AI allowance. One subscription, all formats.

Full question library All refreshers Cancel anytime