Setting Up Cassandra for Each Canonical Use Case
Part 1 lists six canonical examples where Cassandra is the right tool: IoT sensor data, user activity feeds, time-series metrics, messaging inboxes, recommendation counters, audit logs. Listing them isn't the same as knowing how to build one. This part walks through a concrete setup for each — cluster topology, table schema, compaction strategy, consistency levels, and the specific gotcha that bites teams who skip the reasoning. The consequence worth carrying away: the cluster baseline barely changes between use cases — the table is where every decision lives, and each of those decisions is derived from the access pattern and from what it costs the business to lose or serve stale data.
IoT Sensor Data
This is the canonical workload — covered in depth in Part 7 — data modeling and Part 10 — when to use. Summary of the setup:
CREATE KEYSPACE iot WITH replication = {
'class': 'NetworkTopologyStrategy', 'us_east': 3, 'eu_west': 3
};
CREATE TABLE sensor_readings (
device_id TEXT,
sensor_type TEXT,
event_time TIMESTAMP,
value DOUBLE,
unit TEXT,
PRIMARY KEY ((device_id, sensor_type), event_time)
) WITH CLUSTERING ORDER BY (event_time DESC)
AND COMPACTION = {'class': 'TimeWindowCompactionStrategy',
'compaction_window_unit': 'HOURS',
'compaction_window_size': 1}
AND default_time_to_live = 2592000; -- 30 days| Decision | Choice | Why |
|---|---|---|
| Partition key | (device_id, sensor_type) | Every query filters on both; keeps partitions bounded per device+sensor combo |
| Compaction | TWCS, 1-hour windows | Append-only + TTL; whole SSTables drop at expiry, zero tombstone scanning |
| Write CL | LOCAL_QUORUM | Durable, tolerates one replica failure per DC, low enough latency for 5ms p99 |
| Read CL | LOCAL_QUORUM | Dashboards reading recent data need freshness; not ONE |
| TTL | 30 days | Matches "no longer queried after 30 days" business rule |
- Guarantees: Expired data leaves as whole SSTables — no tombstones to scan, because every row in an hourly window expires together.
- Does not guarantee: Bounded partitions. TTL caps how long a row lives, not how many rows one device+sensor accumulates inside 30 days — that is the bucket's job.
User Activity Feeds
Access patterns: "give me user X's most recent N activity events" and, separately, "give me the last N events for the people user X follows" (the harder fan-out problem — see the leaderboard/social-feed synthesis in the study guide for that variant). Here we cover the simpler, own-activity case.
CREATE TABLE user_activity (
user_id UUID,
activity_day TEXT, -- 'YYYY-MM-DD' bucket
occurred_at TIMESTAMP,
activity_id TIMEUUID,
activity_type TEXT,
payload TEXT,
PRIMARY KEY ((user_id, activity_day), occurred_at, activity_id)
) WITH CLUSTERING ORDER BY (occurred_at DESC, activity_id ASC)
AND COMPACTION = {'class': 'TimeWindowCompactionStrategy',
'compaction_window_unit': 'DAYS',
'compaction_window_size': 1}
AND default_time_to_live = 7776000; -- 90 days| Decision | Choice | Why |
|---|---|---|
| Partition key | (user_id, activity_day) | Bounds partition size — a power user active every day for years would otherwise build one unbounded partition |
| Clustering | occurred_at DESC | "Most recent first" is the dominant read; no reversal needed at query time |
| Compaction | TWCS, 1-day windows | Append-only, time-ordered, TTL'd — same reasoning as IoT |
| Write CL | LOCAL_QUORUM | Activity events are user-visible; losing one silently on a replica failure is acceptable, losing the write itself is not |
| Read CL | LOCAL_ONE | Activity feeds tolerate a few seconds of staleness; optimize for latency over freshness |
| TTL | Product-dependent (90 days here) | Old activity typically isn't queried; without TTL, partitions grow forever even with day-bucketing |
- Guarantees: One partition per user per day, so a single partition's size is bounded by one day of one user's activity — however long the user has been around.
- Does not guarantee: That a
LOCAL_ONEread sees the write that just succeeded atLOCAL_QUORUM— W + R = 2 + 1 = 3 is not greater than RF = 3, so staleness of a few seconds is by design.
Time-Series Metrics (Monitoring / Observability)
Access patterns: "plot metric M for host H over the last 6 hours" (dashboards), "give me the current value of metric M" (alerting). This differs from IoT sensor data mainly in volume and tolerance for loss — a dropped metric point is a rounding error; a dropped sensor reading might be a compliance issue.
CREATE TABLE metrics_raw (
metric_name TEXT,
tags_hash TEXT, -- hash of sorted tag set (host, region, etc.)
time_bucket TEXT, -- 'YYYY-MM-DD-HH'
ts TIMESTAMP,
value DOUBLE,
PRIMARY KEY ((metric_name, tags_hash, time_bucket), ts)
) WITH CLUSTERING ORDER BY (ts DESC)
AND COMPACTION = {'class': 'TimeWindowCompactionStrategy',
'compaction_window_unit': 'HOURS',
'compaction_window_size': 1}
AND default_time_to_live = 259200; -- 3 days raw retention
-- Downsampled rollup for longer retention, cheaper storage
CREATE TABLE metrics_hourly_rollup (
metric_name TEXT,
tags_hash TEXT,
time_bucket TEXT, -- 'YYYY-MM'
hour TIMESTAMP,
avg_value DOUBLE,
max_value DOUBLE,
min_value DOUBLE,
PRIMARY KEY ((metric_name, tags_hash, time_bucket), hour)
) WITH CLUSTERING ORDER BY (hour DESC)
AND default_time_to_live = 15552000; -- 180 days| Decision | Choice | Why |
|---|---|---|
| Partition key includes hourly bucket | Bounds partition size under high-cardinality tag combos at high scrape frequency | Same wide-partition defense as above, tighter window because metrics volume is higher |
| Write CL | LOCAL_ONE or even ANY for non-critical metrics | Metrics pipelines favor throughput over durability — losing one data point out of thousands is invisible on a graph |
| Read CL | LOCAL_ONE | Dashboards don't need QUORUM-level freshness; a graph that's a few seconds stale is fine |
| Rollups | Separate table, populated by a stream job (Flink/Kafka Streams), not by Cassandra itself | Cassandra has no server-side aggregation — downsampling must happen upstream before the write, exactly like the leaderboard synthesis pattern in the main study guide |
| Raw TTL | Short (3 days) | Raw resolution is only useful for recent incident debugging |
| Rollup TTL | Long (180 days) | Trend analysis needs history but not per-second resolution |
- Guarantees: Cheap, high-throughput ingest and a fixed storage horizon: 3 days of raw points, 180 days of hourly rollups.
- Does not guarantee: That every point lands. At
LOCAL_ONE/ANYan acknowledged write may exist on a single replica — or only as a hint — and is lost if that node is.
Messaging Inboxes
Access patterns: "last 50 messages in conversation C" and "all conversations for user U, most recent first" — the two-table pattern is the canonical example in the main study guide's data modeling section (messages_by_conversation + conversations_by_user).
CREATE TABLE messages_by_conversation (
conversation_id UUID,
sent_at TIMESTAMP,
message_id TIMEUUID,
sender_id UUID,
body TEXT,
PRIMARY KEY ((conversation_id), sent_at, message_id)
) WITH CLUSTERING ORDER BY (sent_at DESC, message_id ASC)
AND COMPACTION = {'class': 'LeveledCompactionStrategy'};
CREATE TABLE conversations_by_user (
user_id UUID,
last_message_at TIMESTAMP,
conversation_id UUID,
other_user_id UUID,
last_message TEXT,
PRIMARY KEY ((user_id), last_message_at, conversation_id)
) WITH CLUSTERING ORDER BY (last_message_at DESC, conversation_id ASC)
AND COMPACTION = {'class': 'LeveledCompactionStrategy'};| Decision | Choice | Why |
|---|---|---|
| Compaction | LCS, not TWCS | Messaging inboxes are read-heavy and re-read constantly (opening a conversation), and rows are updated (last-message-preview overwritten) rather than purely append-and-expire — LCS bounds read amplification at ~3 files regardless of table size |
| Write CL | LOCAL_QUORUM | A "message sent" acknowledgment the user sees must actually be durable |
| Read CL | LOCAL_QUORUM | Users notice stale inboxes ("why isn't my message showing") much faster than they notice a stale activity feed |
| Deletes | TTL, never hard delete | Hard-deleting read messages is explicitly called out as Cassandra's most common performance failure — see the tombstone section of the main study guide. If messages must disappear (ephemeral chat), set TTL at insert time |
| Write amplification | 3 writes per message (1 to messages_by_conversation, 2 to conversations_by_user for each participant) | Accepted cost of denormalizing for two incompatible partition keys — not a bug |
Why Cassandra Beats a Relational DB for This Specific Access Pattern
The query is always "known key → range of related rows" — conversation_id is known before the query is issued, and the read is always "recent messages in this one conversation." That's the one shape Cassandra's whole architecture is optimized for:
- Routing is O(1), not a query plan. The partitioner hashes
conversation_idand the coordinator already knows which replicas own that token range — one hop, no scatter-gather. A relational DB with a secondary index onconversation_idstill walks a B-tree index, then does random heap-page fetches for the matching rows. - Data is pre-sorted on disk for the read you'll actually do.
sent_at DESCclustering means the memtable and every SSTable are already sorted in the order the client wants — "last 50 messages" is a sequential read, not an index-then-sort. Unless a relational table has a clustered index on exactly(conversation_id, sent_at), it's sorting at query time. - Writes are sequential (LSM), not random (B-tree). Chat is write-dominated — every message is a write, and it's bursty across millions of conversations concurrently. Commit log append → memtable → SSTable flush is sequential I/O throughout (Part 4). A B-tree engine (InnoDB, WiredTiger) does random-page writes and page splits per insert — that profile degrades faster under high concurrent insert load.
- Horizontal scaling needs no re-sharding. Add a node, it takes over a slice of the token ring — done. Sharding a relational table by
conversation_id(e.g. via Vitess) means application-level shard-routing logic and a real data migration every time you add capacity.
Comparison: Azure Cosmos DB for the Same Access Pattern
Cosmos DB shares the same core idea — hash-partition on a key, route directly to the physical partition that owns it — and even ships a wire-compatible Cassandra API, so the messages_by_conversation schema above could point at Cosmos DB and behave identically from the client's perspective. Where it diverges:
| Dimension | Cassandra | Cosmos DB |
|---|---|---|
| Replication model | Leaderless, gossip-based, tunable CL per request (ONE/QUORUM/ALL) | Leader-based replica sets per partition, 5 named consistency levels (Strong, Bounded Staleness, Session, Consistent Prefix, Eventual) with SLA-backed staleness bounds |
| Partition growth | Manual — you bucket the key yourself (the day-bucket pattern in section 2) or a hot conversation grows one wide partition forever | Automatic — physical partitions auto-split around ~20GB and rebalance online with no operator involvement |
| Secondary indexing | None by default; ad-hoc queries off the partition key need a second denormalized table or an external search system (see the Mistake pattern in Part 10) | Indexes every field by default, so "find messages containing X" works out of the box — softens Cassandra's biggest weakness, at the cost of extra RU/storage per write |
| Storage engine internals | LSM tree you tune yourself — compaction strategy, tombstone GC, repair schedules (Parts 4–6) | Proprietary, fully managed — no compaction strategy choice, no manual repair |
| Multi-region writes | Supported (Cassandra pioneered multi-DC), but NetworkTopologyStrategy + CL reasoning is yours | Turnkey multi-master with a declared conflict-resolution policy (LWW or custom merge procedure) |
| Ops model / pricing | You run and tune the cluster (or pay DataStax Astra) — capacity planning is yours | Fully managed PaaS, RU-based autoscale pricing — no ops, but cost scales with request volume in a way that's easy to underestimate at chat-message throughput |
- Guarantees: A known-key read of a conversation's recent messages is one hop to the owning replicas and a sequential slice of pre-sorted data — with
LOCAL_QUORUMon both sides, an acknowledged message is visible to the next in-DC read. - Does not guarantee: Anything for queries that don't start from
conversation_idoruser_id— search and cross-conversation lookups need another table or another system.
Recommendation / Engagement Counters
Access patterns: "how many likes/views/purchases does item X have" — a single, frequently-updated number per item, incremented from high fan-in traffic (every view, every like).
CREATE TABLE item_counters (
item_id UUID,
view_count COUNTER,
like_count COUNTER,
share_count COUNTER,
PRIMARY KEY (item_id)
);
UPDATE item_counters SET view_count = view_count + 1 WHERE item_id = ?;| Decision | Choice | Why |
|---|---|---|
| Column type | Cassandra COUNTER | Purpose-built distributed increment type — avoids read-modify-write races that a plain INT column would have under concurrent updates |
| Write CL | LOCAL_ONE for view counts, LOCAL_QUORUM for anything user-facing/financial (e.g. purchase counts feeding revenue reporting) | View counts tolerate undercounting; anything downstream of billing or leaderboard ranking needs the stronger guarantee |
| Compaction | LCS | Counters are updated (not appended) at high frequency on the same small set of rows — read amplification matters more than write amplification here |
| Hot partitions | Shard the counter across N buckets (item_id, shard_id) for very hot items, sum at read time | A single wildly popular item (viral post) can create a write hotspot on one partition/coordinator; sharding spreads the increments across nodes |
Idempotent — regular write
"Set position = 1:42:07." Applied once or twice, the row ends in the same state. A timeout-and-retry is harmless.
Not idempotent — counter increment
"view_count = view_count + 1." Applied twice, the count is off by one. A timeout tells you nothing about whether the first attempt landed.
- Guarantees: Concurrent increments from many clients don't overwrite one another — no lost updates from read-modify-write races.
- Does not guarantee: Exactly-once counting. A retried increment after a timeout can double count; correctness depends on deduplication upstream.
Audit Logs
Access patterns: "give me every action taken on entity E between date A and date B," almost always for compliance or incident investigation — write-once, read-rarely, and the data must never silently disappear before its retention period.
CREATE TABLE audit_log (
entity_id TEXT,
log_day TEXT, -- 'YYYY-MM-DD' bucket
logged_at TIMESTAMP,
event_id TIMEUUID,
actor_id TEXT,
action TEXT,
details TEXT,
PRIMARY KEY ((entity_id, log_day), logged_at, event_id)
) WITH CLUSTERING ORDER BY (logged_at DESC, event_id ASC)
AND COMPACTION = {'class': 'TimeWindowCompactionStrategy',
'compaction_window_unit': 'DAYS',
'compaction_window_size': 7}
AND default_time_to_live = 220752000; -- 7 years, matches retention policy| Decision | Choice | Why |
|---|---|---|
| Write CL | QUORUM (cross-DC, not LOCAL_QUORUM) | Audit records are the one case here where "the record exists at all" matters more than latency — a lost audit entry is a compliance gap, not a UX blemish |
| Read CL | QUORUM | Investigations need to trust the answer is complete, not read a replica that might be lagging |
| Compaction | TWCS, 7-day windows | Append-only by definition (audit logs are never updated), long retention — wide windows because compaction runs rarely on cold, expired-eventually data |
| Deletes | None, ever — only TTL matching the legal retention window | Audit logs must never be hard-deleted early (defeats the purpose) or accumulate tombstones (kills read performance on the exact table you need to trust during an incident) |
| Immutability | Application never issues UPDATE against this table | Audit correctness depends on rows being genuinely append-only; an UPDATE after the fact would itself need to be a new audit event, not a mutation of history |
- Guarantees: An acknowledged audit record exists on a majority of all replicas across both datacenters, and a
QUORUMread overlaps that majority — the answer an investigator gets is complete. - Does not guarantee: Targeted physical erasure before the TTL. Under TWCS, an early delete hides data from reads but leaves it on disk until its window expires.
Cross-Cutting Summary
| Use case | Compaction | Write CL | Read CL | Deletes |
|---|---|---|---|---|
| IoT sensor data | TWCS | LOCAL_QUORUM | LOCAL_QUORUM | TTL only |
| User activity feeds | TWCS | LOCAL_QUORUM | LOCAL_ONE | TTL only |
| Time-series metrics | TWCS (raw) | LOCAL_ONE/ANY | LOCAL_ONE | TTL only |
| Messaging inboxes | LCS | LOCAL_QUORUM | LOCAL_QUORUM | TTL only, never hard delete |
| Recommendation counters | LCS | LOCAL_ONE / LOCAL_QUORUM | LOCAL_QUORUM | N/A (counters aren't deleted, they decay via TTL on the row if needed — see the correction in §5: counter tables can't use TTL) |
| Audit logs | TWCS (wide windows) | QUORUM | QUORUM | TTL matching legal retention only |
The pattern across all six:
Compaction strategy follows the read/write shape
TWCS for append-and-expire; LCS for read-heavy-and-updated.
Consistency level follows the cost of being wrong
How expensive a stale or lost read/write actually is to the business — not a single global default.
Applying
LOCAL_QUORUM/TWCS everywhere works, but it either overpays for latency on data that doesn't need it (metrics) or underpays for durability on data that does (audit logs).
- Guarantees: A defensible setup for any new table, derived from two questions: what shape are its reads and writes, and what does a lost or stale row cost?
- Does not guarantee: That the defaults stay right. A table whose access pattern shifts — an append-only log that starts taking erasure requests, a feed that becomes billing input — needs its compaction and CL re-derived, not inherited.