Cassandra Real-World Use Cases

Apache Cassandra powers some of the world's largest and most demanding data systems. Its unique combination of always-on availability, linear horizontal scalability, and fast writes at any volume makes it the right choice for specific categories of problems. This topic walks through the most common real-world use cases with concrete data models and the reasons Cassandra excels in each scenario.

Use Case 1: IoT Time-Series Data

Problem

A smart home platform collects temperature, humidity, and energy readings from 10 million devices every 30 seconds — roughly 20 million writes per minute. The data must be queryable by device and time range for dashboards and anomaly detection.

Why Cassandra

Cassandra's write path is sequential and non-blocking, handling millions of writes per second across a cluster. Time-bucketed partition keys keep partitions bounded, and TWCS compaction efficiently expires old data.

Data Model

CREATE TABLE device_readings (
  device_id  TEXT,
  day        DATE,
  read_time  TIMESTAMP,
  metric     TEXT,
  value      DOUBLE,
  PRIMARY KEY ((device_id, day), read_time, metric)
) WITH CLUSTERING ORDER BY (read_time DESC, metric ASC)
  AND default_time_to_live = 7776000   -- 90 days
  AND compaction = {
    'class': 'TimeWindowCompactionStrategy',
    'compaction_window_unit': 'DAYS',
    'compaction_window_size': 1
  };

-- Query last 24 hours for a device:
SELECT read_time, metric, value FROM device_readings
WHERE device_id = 'sensor-8472'
  AND day IN ('2024-06-15', '2024-06-14')
  AND read_time >= '2024-06-14 12:00:00'
ORDER BY read_time DESC;

Use Case 2: Messaging and Chat

Problem

A messaging platform needs to store billions of chat messages, serve conversation history with the newest messages first, and remain available 24/7 globally with no data loss.

Why Cassandra

Wide rows let an entire conversation live in one partition for fast sequential reads. Multi-DC replication ensures messages are never lost. The reverse-chronological sort order is native to the clustering column definition.

Data Model

CREATE TABLE messages (
  conversation_id UUID,
  bucket          TEXT,        -- e.g., '2024-06'
  message_id      TIMEUUID,
  sender_id       UUID,
  body            TEXT,
  media_url       TEXT,
  PRIMARY KEY ((conversation_id, bucket), message_id)
) WITH CLUSTERING ORDER BY (message_id DESC);

-- Last 50 messages in a conversation (current month):
SELECT sender_id, body, toTimestamp(message_id) AS sent_at
FROM messages
WHERE conversation_id = [uuid]
  AND bucket = '2024-06'
LIMIT 50;

Use Case 3: User Activity and Event Tracking

Problem

An e-commerce platform tracks every page view, product click, cart event, and purchase for 50 million daily active users to power personalization and analytics.

Why Cassandra

Each user's event stream lives in its own partition. High write throughput handles millions of events per second. TTL automatically purges events older than 90 days.

Data Model

CREATE TABLE user_events (
  user_id    UUID,
  event_week TEXT,            -- e.g., '2024-W24'
  event_time TIMEUUID,
  event_type TEXT,
  page       TEXT,
  product_id UUID,
  PRIMARY KEY ((user_id, event_week), event_time)
) WITH CLUSTERING ORDER BY (event_time DESC)
  AND default_time_to_live = 7776000;

-- All events for a user in the current week:
SELECT event_type, page, toTimestamp(event_time) FROM user_events
WHERE user_id = [uuid] AND event_week = '2024-W24'
LIMIT 100;

Use Case 4: Fraud Detection and Risk Scoring

Problem

A payment processor must check whether a card or account shows suspicious activity in real time (within 50 ms) before approving each transaction.

Why Cassandra

LOW-latency reads by account ID, always-on availability, and the ability to store recent transaction summaries per account make Cassandra the right operational store for the fraud-detection scoring engine.

Data Model

-- Recent transactions per card (last 30 days):
CREATE TABLE card_transactions (
  card_id    TEXT,
  tx_time    TIMESTAMP,
  tx_id      UUID,
  amount     DECIMAL,
  merchant   TEXT,
  country    TEXT,
  approved   BOOLEAN,
  PRIMARY KEY (card_id, tx_time, tx_id)
) WITH CLUSTERING ORDER BY (tx_time DESC)
  AND default_time_to_live = 2592000;  -- 30 days

-- Aggregated risk signals (updated on each transaction):
CREATE TABLE card_risk_profile (
  card_id         TEXT PRIMARY KEY,
  tx_count_24h    COUNTER,
  unique_countries SET<TEXT>,
  last_seen       TIMESTAMP,
  avg_amount      DECIMAL
);

-- Real-time lookup before approving:
SELECT tx_count_24h, last_seen FROM card_risk_profile
WHERE card_id = '4111-xxxx-xxxx-1111';

Use Case 5: Product Catalog and Recommendation Store

Problem

A retail platform needs to serve product details, category listings sorted by price, and personalized recommendations — all with sub-10 ms latency at millions of requests per minute.

Data Model

-- Single product lookup:
CREATE TABLE products (
  product_id UUID PRIMARY KEY,
  name TEXT, price DECIMAL, category TEXT, description TEXT
);

-- Category browse, sorted by price:
CREATE TABLE products_by_category (
  category   TEXT,
  price      DECIMAL,
  product_id UUID,
  name       TEXT,
  PRIMARY KEY (category, price, product_id)
) WITH CLUSTERING ORDER BY (price ASC, product_id ASC);

-- Personalized recommendations per user:
CREATE TABLE recommendations (
  user_id      UUID,
  score        DECIMAL,
  product_id   UUID,
  name         TEXT,
  generated_at TIMESTAMP,
  PRIMARY KEY (user_id, score, product_id)
) WITH CLUSTERING ORDER BY (score DESC, product_id ASC)
  AND default_time_to_live = 86400;   -- refresh daily

Use Case 6: Real-Time Leaderboards and Gaming

Problem

A mobile game needs to display a global leaderboard and per-level leaderboards, updated in real time as millions of players complete levels.

Data Model

-- Per-level leaderboard (top 1000 per level):
CREATE TABLE leaderboard (
  game_id   TEXT,
  level     INT,
  score     INT,
  player_id UUID,
  player_name TEXT,
  achieved_at TIMESTAMP,
  PRIMARY KEY ((game_id, level), score, player_id)
) WITH CLUSTERING ORDER BY (score DESC, player_id ASC);

-- Top 10 for level 5:
SELECT player_name, score, achieved_at FROM leaderboard
WHERE game_id = 'battle-quest' AND level = 5
LIMIT 10;

-- Player score counters:
CREATE TABLE player_stats (
  player_id UUID PRIMARY KEY,
  total_score COUNTER,
  games_played COUNTER,
  levels_cleared COUNTER
);
UPDATE player_stats SET total_score = total_score + 850
WHERE player_id = [uuid];

Use Case 7: Session Management

CREATE TABLE sessions (
  session_token UUID PRIMARY KEY,
  user_id       UUID,
  created_at    TIMESTAMP,
  last_activity TIMESTAMP,
  metadata      MAP<TEXT, TEXT>
) WITH default_time_to_live = 86400;  -- 24 hours

-- Refresh TTL on each request:
UPDATE sessions USING TTL 86400
SET last_activity = toTimestamp(now())
WHERE session_token = [uuid];

Cassandra's Sweet Spot — Summary Table

Use Case                  Write Volume   Key Requirement
──────────────────────────────────────────────────────────────
IoT / sensor data         Very High      Time-series; TTL expiry
Messaging / chat          High           Wide rows; newest-first
Event / activity tracking Very High      Per-user time streams
Fraud / risk scoring      High reads     Low-latency lookups
Product catalog           Medium         Category browse; recs
Gaming leaderboards       High           Sorted score ranges
Session management        High           TTL; fast token lookup
Ad tech (impressions)     Extreme        Sub-ms writes at scale
Content metadata          Medium         Tag/category lookups

When NOT to Choose Cassandra

Not a Good Fit                Reason
──────────────────────────────────────────────────────────────
Complex multi-table JOINs     Cassandra has no native join support
ACID transactions             Only single-partition atomicity
Ad-hoc analytics queries      Use Spark, BigQuery, or Redshift
Small datasets (< 1 GB)       Overhead not justified; use PostgreSQL
Frequent global aggregations  COUNT(*), AVG across all partitions
                              is expensive without Spark
Strict write ordering         Cassandra is eventually consistent

Summary

Cassandra excels at storing and serving high-volume time-series data, event streams, messaging histories, real-time leaderboards, session tokens, and product catalogs — any workload that writes and reads at massive scale, requires always-on availability, and can be modeled around a well-defined set of queries. The data models above demonstrate the practical application of partition keys, clustering columns, TTL, counters, and wide rows in production systems used by millions of users every day. This course has equipped you with everything you need to design, build, operate, and scale Cassandra-powered systems with confidence.

Leave a Comment

Your email address will not be published. Required fields are marked *