cswork / libraryOpen practice workspace

Articles

Cassandra Interview Questions: Partition Keys, Consistency, Compaction, and Repair

Prepare for Cassandra interview questions on partition keys, consistency levels, compaction, tombstones, repair, and production performance.

Cassandra interview questions test whether you can turn an access pattern into a safe partition, trace that partition to replicas, state the exact consistency promise, and keep replicas convergent over time. A strong backend engineer does not stop at “Cassandra is highly available.” They explain which nodes receive a write, what acknowledgement means, when a read can be stale, and how compaction and repair preserve correctness.

The question-bank records below are practice material, not predictions of your exact interview.

What Cassandra interviewers are actually testing

Use one reusable framework: Partition → Placement → Promise → Maintenance.

  1. Partition: Start from a query, choose the partition key and clustering order, and bound partition growth.
  2. Placement: Hash the partition key to a token, map the token range to vnodes, and place replicas across racks or datacenters.
  3. Promise: Choose a consistency level per operation and state what the client may observe after success, timeout, or failure.
  4. Maintenance: Budget flushes, compaction, tombstone reclamation, repair, and hotspot diagnosis as correctness work.
Interview areaWeak answerStrong Cassandra signal
Partition key“Choose a high-cardinality column”Starts from queries, bounds size, preserves locality, and tests skew
Consistency“Use quorum for strong consistency”Names RF, read CL, write CL, datacenter scope, and failure behavior
Compaction“It deletes old SSTables”Chooses a strategy from read, update, TTL, and I/O patterns
Repair“Hints fix missed writes”Separates best-effort hints/read repair from scheduled anti-entropy repair

How should you choose a Cassandra partition key?

A Cassandra partition key is the first component of a CQL primary key. Cassandra hashes it to choose a token and replica set; every row with that partition key stays on those replicas. Clustering columns then determine row uniqueness and on-disk order inside the partition.

Model one table per access pattern. If the query is “fetch a tenant’s events for one day in descending time order,” a defensible table is:

CREATE TABLE events_by_tenant_day (
  tenant_id text,
  event_day date,
  event_time timestamp,
  event_id uuid,
  payload text,
  PRIMARY KEY ((tenant_id, event_day), event_time, event_id)
) WITH CLUSTERING ORDER BY (event_time DESC);

The composite partition key is (tenant_id, event_day). The day bucket prevents one tenant’s lifetime history from becoming one unbounded partition, while clustering supports the required range scan. The trade-off is application-side fan-out for queries spanning many days.

“High cardinality” alone is not enough. A celebrity tenant or one global status value can still become hot. Estimate rows and bytes per bucket, test the largest tenant, and include a deterministic shard suffix only when one bucket can exceed the node’s throughput or partition-size budget. Random salting without a read plan merely moves the problem to fan-out.

How do tokens, vnodes, and replicas place data?

With the default Murmur3Partitioner, Cassandra hashes the serialized partition key into a token. The token falls in a token range owned by a node. Virtual nodes let one physical node own multiple ranges, which improves balancing and makes incremental expansion more flexible.

Replication is configured per keyspace. Production deployments should use NetworkTopologyStrategy, even for one datacenter. It accepts a replication factor per datacenter and uses rack information to spread replicas across failure domains when topology permits.

For a write, any contacted node may act as coordinator. It hashes the partition key, discovers the natural replicas, sends the mutation to all of them, and waits only for enough acknowledgements to satisfy the requested consistency level. The coordinator is a request role, not a permanent leader for that key.

How does Cassandra tunable consistency work?

Tunable consistency chooses how many replica responses a coordinator requires for one read or write. With replication factor RF=3, QUORUM requires two responses. If both reads and writes use quorum, their replica sets overlap, so at least one read participant saw the acknowledged write.

That overlap is a visibility condition, not permission to call every Cassandra operation linearizable. Last-write-wins timestamps, concurrent mutations, time synchronization, failed requests with ambiguous outcomes, multi-partition work, and lower consistency levels still matter. Lightweight transactions use Paxos when a compare-and-set style linearizable decision is required.

Consistency levelCoordinator waits forUseful interview interpretation
ONE / LOCAL_ONEOne replica; local only for LOCAL_ONELower latency and greater failure tolerance, but a later low-CL read can be stale
QUORUMMajority of all replicasCross-datacenter work if replicas span datacenters
LOCAL_QUORUMMajority of replicas in the local datacenterCommon for datacenter-local reads and writes without WAN quorum latency
EACH_QUORUMMajority in every datacenterStronger cross-datacenter acknowledgement at higher latency and lower availability
ALLEvery replicaMaximum overlap, but one unavailable replica fails the operation
ANYOne replica or a stored hintWrite-only; success may mean the natural replica has not received the mutation yet

In an interview, state the full tuple: topology, RF per datacenter, read CL, write CL, and client routing. “LOCAL_QUORUM everywhere” is incomplete if clients can switch datacenters immediately after a write.

What happens on Cassandra's write and read paths?

On each replica, a normal write is appended to the commit log and applied to the table’s memtable. When the memtable reaches a trigger, Cassandra flushes its sorted contents into immutable SSTables. The commit log makes unflushed mutations recoverable; the memtable is the current in-memory state, not the durable boundary by itself.

A read may need to reconcile versions from the memtable and several SSTables. Bloom filters can prove that an SSTable does not contain the requested partition key, while partition indexes and summaries help find likely disk locations. Cassandra then merges relevant rows, timestamps, TTLs, and tombstones to produce the result.

This is why compaction health affects foreground latency. If a partition is spread across many overlapping SSTables, the read does more work even though the CQL query has not changed.

Which Cassandra compaction strategy should you choose?

Compaction reads SSTables, merges their contents, processes overwritten values and tombstones when safe, and writes new SSTables. It reduces read amplification and reclaims space, but consumes CPU, disk bandwidth, temporary space, and additional writes.

For Cassandra 5.0, Unified Compaction Strategy (UCS) is the recommended starting point for most new workloads. Legacy strategies still matter in interviews and existing clusters because they expose workload trade-offs.

StrategyStrong fitMain trade-off to name
UCSNew mixed, read-heavy, write-heavy, or time-series workloadsTune scaling and reservations; still budget background I/O
STCSWrite-oriented fallback and existing workloadsSimilar-size SSTables compact together; reads and temporary space can grow
LCSRead-heavy tables or many updates/deletesFewer overlapping SSTables per level, but higher CPU and write amplification
TWCSMostly immutable time-series data with TTLsTime windows can expire cleanly; late writes can contaminate old windows

Do not choose from labels alone. Measure SSTables per read, pending compaction work, write rate, disk utilization, and tail latency. If flushes create work faster than compaction consumes it, apply backpressure before disk exhaustion turns maintenance debt into an outage.

Why are tombstones, gc_grace_seconds, and repair connected?

A delete or expired TTL becomes a tombstone that follows the normal write path. Cassandra cannot remove it immediately because an unavailable replica may still hold the older live value. If every tombstone copy disappears before that replica is repaired, the older value can reappear as a zombie.

gc_grace_seconds is therefore not a cleanup timer you lower merely to save disk. It defines part of the safety window for replica convergence. Repair must cover affected token ranges before grace expires, and the schedule needs slack for failed or delayed jobs. Changing grace requires evidence about repair completion, topology, outages, backups, and the table’s deletion behavior.

Hints and foreground read repair reduce divergence but are best effort. Anti-entropy repair compares replica data for common token ranges using Merkle trees and streams differences. Incremental repair limits routine work to unrepaired data; occasional full repair remains necessary for corruption, operator mistakes, or older inconsistencies that incremental repair may not revisit.

How do you diagnose hot partitions and slow Cassandra queries?

Start with the data model and narrow the failure before changing compaction or adding nodes.

  1. Capture the exact CQL, consistency level, coordinator datacenter, latency distribution, timeout type, and trace for a representative request.
  2. Confirm whether the query names a full partition key and a contiguous clustering range. Broad scans and ALLOW FILTERING do not become safe because the cluster is large.
  3. Use nodetool toppartitions to sample active partitions, tablestats for partition sizes and SSTable/compaction signals, and tablehistograms for latency and size distributions.
  4. Check pending compactions, dropped messages, thread-pool pressure, disk latency, garbage collection, repair age, hints, replica availability, and free-space headroom.
  5. Fix the smallest causal issue: rebucket a wide partition, split a hot key, change a query-specific table, repair stale replicas, or retune compaction from measured workload evidence.

Adding nodes helps distributed load, but it cannot split one indivisible hot partition across its replica set. That requires a data-model change or a safe read cache, not another round of uniform hashing.

A seven-day Cassandra interview plan

DayFocusDeliverable
Day 1Query-first modelingDesign two tables per feature and defend partition bounds
Day 2Tokens and topologyDraw key → token → vnode → rack/DC replicas
Day 3ConsistencyWalk RF=3 failures at ONE, LOCAL_QUORUM, and ALL
Day 4Storage pathsTrace one write, read, TTL, and delete through memtables and SSTables
Day 5Compaction and repairChoose UCS/LCS/TWCS and build a grace-safe repair schedule
Day 6OperationsDiagnose a hot tenant, tombstone-heavy read, and compaction backlog
Day 7Mock interviewDeliver the four-step framework in 35 minutes, then review gaps

Frequently asked questions

What is the difference between a partition key and a clustering key in Cassandra?

The partition key is hashed to choose the token and replica set, so it controls data distribution and locality. Clustering columns order and uniquely identify rows inside that partition. A strong design uses both to satisfy a known query while keeping each partition bounded and evenly loaded.

Does QUORUM make Cassandra strongly consistent?

Matching quorum reads and writes with R + W > RF guarantees replica overlap for that key and topology. It does not automatically provide linearizability for every operation. Timestamp ordering, concurrent writes, client datacenter changes, failed requests, and multi-partition behavior still need explicit rules.

Why can deleted Cassandra data come back?

Deleted data can reappear when a tombstone is purged before an unavailable replica carrying the older value is repaired. The repair schedule, grace period, topology, and outage history must establish that stale copies cannot outlive the tombstone safety window.

Is repair automatic in Apache Cassandra?

No. Hinted handoff and read repair are best-effort mechanisms, while anti-entropy repair is an operator-managed process unless an orchestration feature is configured. Schedule incremental repair regularly, include occasional full repair, monitor completion, and finish coverage before the relevant grace window expires.

What is the best compaction strategy for Cassandra?

For Cassandra 5.0, UCS is the official starting recommendation for most new workloads. LCS and TWCS still fit specific existing patterns, while STCS remains a fallback. The correct choice depends on reads, updates, TTLs, disk headroom, and measured compaction and latency behavior.

Final takeaway

The best Cassandra interview answers connect partition, placement, promise, and maintenance. Design from the query, trace a key through tokens and replicas, name the exact consistency contract, and show how compaction, tombstones, and repair keep that contract credible after failures.

Sources and Further Reading

Research note: This guide was checked on September 1, 2026. Version-specific defaults, topology, consistency levels, and repair schedules should be verified against the deployed Apache Cassandra version and the application's failure contract.