Apache Cassandra
A Highly Scalable Distributed NoSQL Database for Modern Applications
What is Apache Cassandra?
Apache Cassandra is an open-source, distributed NoSQL database designed to handle large amounts of data across many commodity servers while providing high availability with no single point of failure. Originally developed at Facebook for inbox search, Cassandra combines the best of Google BigTable's data model with Amazon Dynamo's distribution design.
Key Innovation: Cassandra uses a masterless ring architecture where all nodes are equal, eliminating single points of failure and enabling linear scalability by simply adding more nodes.
Cassandra excels in these scenarios:
IoT & Metrics
Chat & Events
Product Data
User Activity
Architecture Overview
Cassandra uses a peer-to-peer distributed architecture where data is distributed across all nodes in a cluster using consistent hashing. Each node communicates with every other node through a gossip protocol.
Gossip Protocol
Node communication mechanism
- - Peer-to-peer state sharing
- - Failure detection
- - Cluster membership
Consistent Hashing
Data distribution strategy
- - Partition key hashing
- - Token ring assignment
- - Minimal redistribution
Replication
Data durability strategy
- - Configurable replication factor
- - Multi-datacenter support
- - Rack-aware placement
Data Model
Core Concepts
Cassandra's data model is based on a wide-column store design:
Top-level namespace (like a database)
Collection of rows (column family)
Determines data distribution
Sorts data within partitions
Example table structure:
-- Create keyspace with replication
CREATE KEYSPACE my_app WITH replication = {
'class': 'NetworkTopologyStrategy',
'datacenter1': 3
};
-- Create table with composite primary key
CREATE TABLE my_app.user_events (
user_id UUID,
event_time TIMESTAMP,
event_type TEXT,
event_data MAP<TEXT, TEXT>,
PRIMARY KEY ((user_id), event_time)
) WITH CLUSTERING ORDER BY (event_time DESC);
Primary Key
Composed of the partition key (determines which node stores the data) and optional clustering columns (determine sort order within the partition). Good key design is crucial for performance.
Wide Rows
A single partition can contain up to 2 billion columns and store large amounts of related data. This enables efficient time-series data storage and retrieval patterns.
CQL - Cassandra Query Language
CQL provides a SQL-like interface for interacting with Cassandra, making it familiar to developers with relational database experience while respecting Cassandra's distributed nature.
Common CQL Operations
-- Insert data
INSERT INTO user_events (user_id, event_time, event_type, event_data)
VALUES (uuid(), toTimestamp(now()), 'login', {'ip': '192.168.1.1'});
-- Query by partition key (efficient)
SELECT * FROM user_events
WHERE user_id = 123e4567-e89b-12d3-a456-426614174000
AND event_time > '2024-01-01';
-- Update with TTL (auto-expire after 30 days)
UPDATE user_events USING TTL 2592000
SET event_data = {'status': 'processed'}
WHERE user_id = 123e4567-e89b-12d3-a456-426614174000
AND event_time = '2024-01-15 10:30:00';
-- Batch operations (atomic within partition)
BEGIN BATCH
INSERT INTO user_events ...
INSERT INTO user_events ...
APPLY BATCH;
Important: Unlike SQL, CQL requires queries to include the partition key. Queries without the partition key require ALLOW FILTERING (not recommended for production) or secondary indexes.
Cassandra vs Relational Databases
| Aspect | Cassandra | Relational (SQL) |
|---|---|---|
| Architecture | Masterless, distributed | Master-replica |
| Scaling | Horizontal (add nodes) | Vertical (bigger servers) |
| Schema | Flexible, denormalized | Fixed, normalized |
| Joins | Not supported (by design) | Full support |
| Consistency | Tunable (eventual to strong) | ACID transactions |
| Best For | Write-heavy, time-series, high availability | Complex queries, transactions, relationships |
Key Features
High Availability
No single point of failure. Data is replicated across multiple nodes and datacenters. The cluster continues operating even when nodes fail.
Linear Scalability
Double your capacity by doubling the number of nodes. Cassandra scales predictably without complex resharding or downtime.
Tunable Consistency
Choose consistency level per query: ONE, QUORUM, ALL, or LOCAL_QUORUM for multi-DC. Balance between consistency and availability based on your needs.
Write Optimization
Optimized for write-heavy workloads using an append-only commit log and memtables. Can handle millions of writes per second.
TTL Support
Built-in time-to-live for automatic data expiration. Essential for time-series data, session management, and GDPR compliance.
Multi-Datacenter
Native support for geographically distributed clusters. Async replication between datacenters with configurable consistency.
Getting Started
Python Driver Example
# Install: pip install cassandra-driver
from cassandra.cluster import Cluster
from cassandra.auth import PlainTextAuthProvider
from cassandra.query import SimpleStatement, ConsistencyLevel
import uuid
# Connect to cluster
auth_provider = PlainTextAuthProvider('username', 'password')
cluster = Cluster(['node1.example.com', 'node2.example.com'],
auth_provider=auth_provider)
session = cluster.connect('my_keyspace')
# Insert data
insert_stmt = session.prepare("""
INSERT INTO user_events (user_id, event_time, event_type, event_data)
VALUES (?, toTimestamp(now()), ?, ?)
""")
session.execute(insert_stmt, [uuid.uuid4(), 'page_view', {'page': '/home'}])
# Query with consistency level
query = SimpleStatement(
"SELECT * FROM user_events WHERE user_id = %s",
consistency_level=ConsistencyLevel.LOCAL_QUORUM
)
results = session.execute(query, [user_id])
for row in results:
print(f"{row.event_time}: {row.event_type}")
Docker Quick Start
# Run single-node Cassandra
docker run --name cassandra -p 9042:9042 -d cassandra:latest
# Connect with cqlsh
docker exec -it cassandra cqlsh
# Create keyspace and table
CREATE KEYSPACE test WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};
USE test;
CREATE TABLE users (id UUID PRIMARY KEY, name TEXT, email TEXT);
INSERT INTO users (id, name, email) VALUES (uuid(), 'John', 'john@example.com');
SELECT * FROM users;
Best Practices
Data Modeling Rule: In Cassandra, you design tables around your queries, not your data relationships. Denormalization is expected and encouraged.
- Design for queries: Create tables based on access patterns, not entity relationships
- Choose partition keys wisely: Ensure even data distribution and avoid hot partitions
- Keep partitions small: Target 100MB or less per partition for optimal performance
- Use prepared statements: Improve performance and prevent CQL injection
- Set appropriate consistency: Use LOCAL_QUORUM for most production workloads
- Avoid ALLOW FILTERING: Design secondary indexes or materialized views instead
- Use TTL for time-series: Automatically expire old data to manage storage
- Monitor compaction: Keep compaction healthy to maintain read performance
Ecosystem & Integrations
Enterprise Support
Serverless DBaaS
Analytics Connector
Streaming Integration
Java Framework
K8ssandra Operator
Monitoring
Metrics Export
Use Cases
Time Series Data
Messaging Systems
IoT Data Storage
Product Catalogs
User Activity Logs
Session Storage
Performance Characteristics
Production Scale: Companies like Netflix, Apple, and Spotify run Cassandra clusters with petabytes of data and millions of operations per second.
Writes/Second
P99 Latency
Data Capacity
Learn More
Essential Resources
Related Topics
Test Your Knowledge
Score 8/10 or higher to pass
You need to be logged in to take this quiz.
Login to Continue