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
DecisionChoiceWhy
Partition key(device_id, sensor_type)Every query filters on both; keeps partitions bounded per device+sensor combo
CompactionTWCS, 1-hour windowsAppend-only + TTL; whole SSTables drop at expiry, zero tombstone scanning
Write CLLOCAL_QUORUMDurable, tolerates one replica failure per DC, low enough latency for 5ms p99
Read CLLOCAL_QUORUMDashboards reading recent data need freshness; not ONE
TTL30 daysMatches "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
DecisionChoiceWhy
Partition key(user_id, activity_day)Bounds partition size — a power user active every day for years would otherwise build one unbounded partition
Clusteringoccurred_at DESC"Most recent first" is the dominant read; no reversal needed at query time
CompactionTWCS, 1-day windowsAppend-only, time-ordered, TTL'd — same reasoning as IoT
Write CLLOCAL_QUORUMActivity events are user-visible; losing one silently on a replica failure is acceptable, losing the write itself is not
Read CLLOCAL_ONEActivity feeds tolerate a few seconds of staleness; optimize for latency over freshness
TTLProduct-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_ONE read sees the write that just succeeded at LOCAL_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
DecisionChoiceWhy
Partition key includes hourly bucketBounds partition size under high-cardinality tag combos at high scrape frequencySame wide-partition defense as above, tighter window because metrics volume is higher
Write CLLOCAL_ONE or even ANY for non-critical metricsMetrics pipelines favor throughput over durability — losing one data point out of thousands is invisible on a graph
Read CLLOCAL_ONEDashboards don't need QUORUM-level freshness; a graph that's a few seconds stale is fine
RollupsSeparate table, populated by a stream job (Flink/Kafka Streams), not by Cassandra itselfCassandra has no server-side aggregation — downsampling must happen upstream before the write, exactly like the leaderboard synthesis pattern in the main study guide
Raw TTLShort (3 days)Raw resolution is only useful for recent incident debugging
Rollup TTLLong (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 / ANY an 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'};
DecisionChoiceWhy
CompactionLCS, not TWCSMessaging 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 CLLOCAL_QUORUMA "message sent" acknowledgment the user sees must actually be durable
Read CLLOCAL_QUORUMUsers notice stale inboxes ("why isn't my message showing") much faster than they notice a stale activity feed
DeletesTTL, never hard deleteHard-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 amplification3 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
User A sends a message in conversation C between A and B. The application issues three writes to three partitions across two tables: one insert into messages_by_conversation at partition C, which serves the last 50 messages in C; and one into conversations_by_user at partition A and one at partition B, which serve each user’s inbox newest first. Because last_message_at is a clustering column, each inbox write is really a delete of the old inbox row plus an insert, leaving one tombstone per participant per message.
One 1:1 message is three writes — two tables, three partitions

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:

  1. Routing is O(1), not a query plan. The partitioner hashes conversation_id and the coordinator already knows which replicas own that token range — one hop, no scatter-gather. A relational DB with a secondary index on conversation_id still walks a B-tree index, then does random heap-page fetches for the matching rows.
  2. Data is pre-sorted on disk for the read you'll actually do. sent_at DESC clustering 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.
  3. 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.
  4. 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:

DimensionCassandraCosmos DB
Replication modelLeaderless, 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 growthManual — you bucket the key yourself (the day-bucket pattern in section 2) or a hot conversation grows one wide partition foreverAutomatic — physical partitions auto-split around ~20GB and rebalance online with no operator involvement
Secondary indexingNone 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 internalsLSM 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 writesSupported (Cassandra pioneered multi-DC), but NetworkTopologyStrategy + CL reasoning is yoursTurnkey multi-master with a declared conflict-resolution policy (LWW or custom merge procedure)
Ops model / pricingYou run and tune the cluster (or pay DataStax Astra) — capacity planning is yoursFully 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_QUORUM on 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_id or user_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 = ?;
DecisionChoiceWhy
Column typeCassandra COUNTERPurpose-built distributed increment type — avoids read-modify-write races that a plain INT column would have under concurrent updates
Write CLLOCAL_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
CompactionLCSCounters are updated (not appended) at high frequency on the same small set of rows — read amplification matters more than write amplification here
Hot partitionsShard the counter across N buckets (item_id, shard_id) for very hot items, sum at read timeA 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
DecisionChoiceWhy
Write CLQUORUM (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 CLQUORUMInvestigations need to trust the answer is complete, not read a replica that might be lagging
CompactionTWCS, 7-day windowsAppend-only by definition (audit logs are never updated), long retention — wide windows because compaction runs rarely on cold, expired-eventually data
DeletesNone, ever — only TTL matching the legal retention windowAudit 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)
ImmutabilityApplication never issues UPDATE against this tableAudit 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 QUORUM read 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 caseCompactionWrite CLRead CLDeletes
IoT sensor dataTWCSLOCAL_QUORUMLOCAL_QUORUMTTL only
User activity feedsTWCSLOCAL_QUORUMLOCAL_ONETTL only
Time-series metricsTWCS (raw)LOCAL_ONE/ANYLOCAL_ONETTL only
Messaging inboxesLCSLOCAL_QUORUMLOCAL_QUORUMTTL only, never hard delete
Recommendation countersLCSLOCAL_ONE / LOCAL_QUORUMLOCAL_QUORUMN/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 logsTWCS (wide windows)QUORUMQUORUMTTL 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.