Column-Family Databases: Cassandra and HBase Architecture

Cassandra and HBase data storage explained. Learn partition key design, column families, time-series modeling, and consistency tradeoffs.

published: reading time: 35 min read author: Geek Workbench updated: November 8, 2026
Quick Summary

Column-family databases like Cassandra and HBase organize data into column families optimized for write-heavy workloads and massive scale. Despite the name, they store data row by row, grouping columns into families. Cassandra uses partition key design for data distribution across nodes without a master. HBase relies on HDFS with RegionServers managing horizontal partitions. Both handle time-series data well when modeled correctly with bucketing to prevent unbounded partition growth.

Column-Family Databases: Cassandra and HBase Architecture

Column-family databases feel like spreadsheets but behave nothing like relational systems. They organize data into column families, rows, and columns—optimized for write-heavy workloads, massive scale, and queries that fetch many columns from a single row. The two major players in this space are Cassandra and HBase. They share the wide-column model but differ significantly in architecture and operational characteristics.

The Wide-Column Model

Despite the name, column-family databases are not column-oriented like analytical databases (ClickHouse, Redshift). They store data row by row, but group columns into families.

-- Cassandra CQL looks like SQL but isn't
CREATE TABLE users (
    user_id uuid PRIMARY KEY,
    profile frozen<profile_type>,
    preferences map<text, text>,
    created_at timestamp
);

Under the hood, data is stored as:

RowKey: user-123
|
+-- Column Family: profile
|   +-- Column: first_name, value: "Alice", timestamp: 1709256000
|   +-- Column: last_name, value: "Chen", timestamp: 1709256000
|   +-- Column: bio, value: "Engineer", timestamp: 1709256000
|
+-- Column Family: preferences
    +-- Column: theme, value: "dark", timestamp: 1709256000
    +-- Column: language, value: "en", timestamp: 1709256000

Each cell has a value and a timestamp. The timestamp enables optimistic concurrency and can track data versioning.


Cassandra: Distributed by Default

Cassandra is designed as a distributed, masterless database. Every node can serve any request. Data is replicated across nodes based on a configurable replication factor.

Partition Key Design

The partition key determines data distribution. All columns with the same partition key reside on the same node(s).

-- Good: high cardinality column as partition key
CREATE TABLE orders_by_user (
    user_id uuid,
    order_id timeuuid,
    total decimal,
    status text,
    items list<text>,
    PRIMARY KEY (user_id, order_id)
);

-- Query: get all orders for a user (efficient - single partition lookup)
SELECT * FROM orders_by_user WHERE user_id = ?;

-- Bad: low cardinality as partition key
CREATE TABLE orders_by_status (
    user_id uuid,
    order_id timeuuid,
    status text,
    PRIMARY KEY (status, order_id)
);

-- Query: get all orders with status = 'pending' (scans many partitions)
SELECT * FROM orders_by_status WHERE status = 'pending';

Data Modeling for Query Patterns

Start with a concrete request: list one customer’s orders for a selected day, newest first. In Cassandra, make that access pattern explicit in the primary key: the partition key locates the data, and clustering columns order rows inside that partition.

CREATE TABLE orders_by_customer_day (
    customer_id uuid,
    order_day date,
    placed_at timestamp,
    order_id uuid,
    status text,
    PRIMARY KEY ((customer_id, order_day), placed_at, order_id)
) WITH CLUSTERING ORDER BY (placed_at DESC, order_id ASC);

SELECT order_id, placed_at, status
FROM orders_by_customer_day
WHERE customer_id = ? AND order_day = ?
  AND placed_at >= ? AND placed_at < ?;

This keeps the lookup on one known partition and orders results by time. If a customer can generate too many rows in one day, add a smaller bucket to the partition key and query the affected buckets. If the table is instead keyed only by customer for unbounded history, a high-activity customer can create an oversized, hot partition; bucketing bounds growth but adds reads for broader time ranges. Validate the design against the real sampling rate, retention window, and query volume. Cassandra’s data-modeling guide describes partition and clustering key roles.

In Cassandra, you model for queries, not entities. You create separate tables for each access pattern.

-- Table for user profile lookups
CREATE TABLE user_profiles (
    user_id uuid PRIMARY KEY,
    email text,
    name text,
    created_at timestamp
);

-- Table for looking up users by email
CREATE TABLE user_emails (
    email text PRIMARY KEY,
    user_id uuid
);

-- Table for getting all users (for admin views)
CREATE TABLE all_users (
    tenant_id uuid,
    user_id uuid,
    email text,
    name text,
    PRIMARY KEY (tenant_id, user_id)
);

-- Table for time-based activity queries
CREATE TABLE user_activity (
    user_id uuid,
    activity_date date,
    activity_hour int,
    event_type text,
    event_data map<text, text>,
    PRIMARY KEY ((user_id), activity_date, activity_hour, event_type)
);

Consistency Levels

Cassandra offers tunable consistency. You can trade consistency for availability.

from cassandra.cluster import Cluster

cluster = Cluster(['cassandra-node-1', 'cassandra-node-2', 'cassandra-node-3'])
session = cluster.connect('mykeyspace')

# Example only: choose levels based on replication strategy and consistency needs.
session.execute(
    "INSERT INTO user_profiles (user_id, email, name) VALUES (%s, %s, %s)",
    [user_id, email, name],
    consistency_level=ConsistencyLevel.QUORUM
)

# Read with quorum
result = session.execute(
    "SELECT * FROM user_profiles WHERE user_id = %s",
    [user_id],
    consistency_level=ConsistencyLevel.QUORUM
)

# Consistency levels:
# ONE: one replica must respond
# QUORUM: a majority of replicas for the relevant consistency scope
# ALL: every replica must respond; unavailable if a required replica cannot respond
# Read/write overlap (R + W > RF) applies only when both operations use
# compatible replica sets and the same replication scope.
# LOCAL_ONE: local datacenter only
# LOCAL_QUORUM: quorum in local datacenter

Time-Series Modeling

Cassandra handles time-series data well when modeled correctly.

-- Time-series table with bucketing
CREATE TABLE sensor_readings (
    sensor_id text,
    bucket date,  -- daily bucket
    reading_time timestamp,
    temperature float,
    humidity float,
    PRIMARY KEY ((sensor_id, bucket), reading_time)
) WITH CLUSTERING ORDER BY (reading_time DESC);

-- Query a specific sensor for a day
SELECT * FROM sensor_readings
WHERE sensor_id = 'temp-sensor-001'
  AND bucket = '2024-03-15';

-- Query for a time range within a bucket
SELECT * FROM sensor_readings
WHERE sensor_id = 'temp-sensor-001'
  AND bucket = '2024-03-15'
  AND reading_time > '2024-03-15T10:00:00'
  AND reading_time < '2024-03-15T14:00:00';

The bucket prevents unbounded partition growth. Each partition holds one day’s worth of data for one sensor.

flowchart TD
    W["Write Request"]
    WL["WAL<br/>(Write-Ahead Log)"]
    MS["MemStore<br/>(In-Memory)"]
    HF["HFiles<br/>(Disk)"]
    RS["Read Request"]
    BC["BlockCache"]
    Merge["HFiles<br/>(Merged)"]

    W --> WL --> MS -->|Flush when full| HF
    RS --> BC
    BC --> MS
    Merge -->|Compaction| HF
    HF -.->|"On read"| Merge

HBase’s write path goes through WAL (durability) then MemStore (speed). Reads check BlockCache first, then MemStore, then merged HFiles. Compaction runs in the background to merge HFiles and remove deleted cells.


HBase: Hadoop’s Column Store

HBase is built on top of HDFS (Hadoop Distributed File System). It integrates with the Hadoop ecosystem and is optimized for sequential reads and writes.

Architecture

HBase stores data in HFiles on HDFS. Regions serve ranges of row keys and split as they grow. HBase uses ZooKeeper for coordination.

Client -> ZooKeeper -> Meta Table (lists regions) -> Region Server
                                      |
                                      v
                              HFile (stored on HDFS)

The region is the fundamental unit of data distribution in HBase. Each region holds a contiguous, non-overlapping range of row keys. When a region grows past a configured threshold (default 10GB), HBase splits it into two roughly equal halves and the RegionServer reports the split back to ZooKeeper. This split happens on the RegionServer itself, which minimizes coordination overhead. The HBase Master then reassigns the daughter regions to other RegionServers for load balancing.

The write path follows a specific sequence. First, data hits the Write-Ahead Log (WAL) on HDFS — this guarantees durability even if a RegionServer crashes before data is persisted. Then it goes to the MemStore, an in-memory sorted structure keyed by column family. When the MemStore fills up, HBase flushes it as a new HFile. Because HDFS writes are sequential, each flush creates a new HFile with sorted key-value pairs. Over time, many HFiles accumulate per column family per region, and HBase compacts them in the background into fewer, larger files.

The ZooKeeper ensemble maintains the cluster state. The HBase Master election happens through ZooKeeper — only one Master is active at a time, handling region assignments andDDL operations. RegionServers heartbeat to ZooKeeper to confirm they are alive. If a RegionServer fails to heartbeat for a configured interval (default 3 minutes), the Master treats it as dead and reassigns its regions to live servers. The Meta Table, hosted in ZooKeeper, tracks which RegionServer hosts which region — the client queries this table once, caches the location, and goes directly to the right RegionServer for subsequent requests.

Data Model

HBase uses a sparse, multi-dimensional sorted map.

Key: (Row Key, Column Family, Column Qualifier, Timestamp)
Value: byte[]
from happybase import Connection

connection = Connection('hbase-host')
table = connection.table('user_events')

# Store events
row_key = f'user-123#{datetime.now().isoformat()}'
table.put(row_key, {
    'cf:event_type': 'purchase',
    'cf:amount': '129.99',
    'cf:product_id': 'SKU-001',
    'cf:timestamp': datetime.now().isoformat()
})

# Scan with filters
for key, data in table.scan(row_start='user-123',
                             row_stop='user-124',
                             filter="SingleColumnValueFilter('cf', 'event_type', =, 'binary:purchase')"):
    print(key, data)

# Get specific row
row = table.row('user-123#2024-03-15T10:30:00')

Row Key Design

Row keys in HBase determine locality. Sequential keys cause write hotspots.

# Bad: sequential keys cause hotspot on one region server
row_key = f'order-{order_id:010d}'  # order-0000000001, order-0000000002...

# Better: salted keys distribute writes
# But adds complexity to reads

# Better yet: randomizing keys for write distribution
import uuid
row_key = f'{uuid.uuid4().hex}#user-123'

# For time-series: reverse timestamp keys for hot/cold access patterns
# or use salting with date prefixes
row_key = f'2024-03-15#{uuid.uuid4().hex}#user-123'

Read/Write Paths

HBase writes go through a Write-Ahead Log (WAL) and MemStore before being flushed to HFiles.

Write: Client -> WAL -> MemStore (in memory) -> Flush to HFile
                                                              |
Read: Client -> BlockCache -> MemStore -> HFiles (merged) <--+

Compaction merges HFiles, removing deleted or overwritten cells.


Comparing Cassandra and HBase

Characteristic Cassandra HBase
Architecture Masterless, every node equal Master-slave with ZooKeeper
Consistency Tunable per-query Strong consistency only
Write Performance Excellent Good
Query Language CQL (SQL-like) No native SQL (requires Phoenix)
Secondary Indexes Limited, local Limited
Hadoop Integration Limited Native MapReduce, Spark
Operational Complexity Lower (no ZooKeeper) Higher ( ZooKeeper, HDFS)
Global Scans Possible but expensive Efficient via MapReduce
Use Case Fit Write-heavy, multi-datacenter Hadoop ecosystem, sequential access

When to Use / When Not to Use Column-Family Databases

Use them when:

  • You need to handle millions of writes per second with horizontal scaling
  • Your access patterns are known upfront and map to partition keys
  • You need multi-datacenter replication with tunable consistency (Cassandra)
  • Time-series data with bucketing fits your workload
  • You’re in the Hadoop ecosystem and need native Spark/Hive integration (HBase)

Do not use them when:

  • You need ad-hoc queries on arbitrary columns — CQL is not SQL and joins are not supported
  • Your team can’t manage ZooKeeper, HDFS, and region management (HBase)
  • You need strong consistency across wide range queries with complex aggregation
  • Your data model changes frequently — wide-column schemas require rethinking partition keys
  • You need real-time secondary indexing across non-key columns

Partition Key Strategies

The partition key is the most critical design decision.

Goals for Partition Keys

  1. Distribute writes evenly across partitions
  2. Keep related data in the same partition
  3. Avoid partitions that grow too large
  4. Enable efficient range queries when needed
-- E-commerce: multiple access patterns

-- Pattern 1: User-centric
CREATE TABLE user_orders (
    user_id uuid,
    order_id timeuuid,
    total decimal,
    items list<text>,
    PRIMARY KEY (user_id, order_id)
);

-- Pattern 2: Product-centric (for "who bought this?")
CREATE TABLE product_orders (
    product_id uuid,
    order_id timeuuid,
    user_id uuid,
    quantity int,
    PRIMARY KEY (product_id, order_id)
);

-- Pattern 3: Time-based (for analytics)
CREATE TABLE daily_sales (
    date date,
    product_id uuid,
    order_id timeuuid,
    quantity int,
    PRIMARY KEY (date, product_id, order_id)
) WITH CLUSTERING ORDER BY (product_id ASC, order_id DESC);

Avoiding Hotspots

-- Bad: monotonically increasing key causes hotspot
CREATE TABLE events (
    event_id bigint,
    data text,
    PRIMARY KEY (event_id)
);
-- All writes go to one partition (highest event_id)

-- Good: hash the key to distribute
CREATE TABLE events (
    event_id bigint,
    partition_key text,  -- first part of composite key
    data text,
    PRIMARY KEY ((partition_key), event_id)
);

-- Better: use a natural key that has cardinality
CREATE TABLE user_events (
    user_id uuid,
    event_id timeuuid,
    data text,
    PRIMARY KEY ((user_id), event_id)
);

Time-Series Data Modeling

Time-series is a natural fit for wide-column stores.

-- Cassandra: bucket by time, query by partition
CREATE TABLE metrics (
    metric_name text,
    bucket text,  -- YYYY-MM-DD
    timestamp timestamp,
    value double,
    tags map<text, text>,
    PRIMARY KEY ((metric_name, bucket), timestamp)
);

-- Query: get all CPU metrics for a host on a day
SELECT * FROM metrics
WHERE metric_name = 'cpu.usage'
  AND bucket = '2024-03-15'
  AND timestamp > '2024-03-15T00:00:00'
  AND timestamp < '2024-03-15T23:59:59';
# HBase: store metrics with composite row key
# Row key: metric_name#hostname#timestamp

from happybase import Connection
import time

def store_metric(connection, metric_name, hostname, value, tags=None):
    table = connection.table('metrics')
    timestamp = int(time.time() * 1000)
    row_key = f'{metric_name}#{hostname}#{timestamp:013d}'

    data = {'cf:value': str(value), 'cf:timestamp': str(timestamp)}
    if tags:
        for k, v in tags.items():
            data[f'cf:tag.{k}'] = v

    table.put(row_key, data)

def query_metrics(connection, metric_name, hostname, start_time, end_time):
    table = connection.table('metrics')
    start_row = f'{metric_name}#{hostname}#{start_time:013d}'
    end_row = f'{metric_name}#{hostname}#{end_time:013d}'

    return table.scan(row_start=start_row, row_stop=end_row)

Consistency Tradeoffs

Wide-column databases make interesting consistency tradeoffs.

Cassandra’s Tunable Consistency

For a single datacenter replication factor of three, QUORUM normally waits for two replicas. If both a write and a subsequent read use compatible quorum scopes, their replica sets overlap (R + W > RF), so the acknowledged write is visible to that read. This arithmetic does not by itself guarantee linearizability for every concurrent operation or every multi-datacenter configuration. See the Cassandra consistency-level documentation for the scope and behavior of each level.

# Read repair: check other replicas after read
# If mismatch found, repair asynchronously

# For high consistency: use SERIAL consistency
session.execute(..., consistency_level=ConsistencyLevel.SERIAL)
# Requires CL=QUORUM for writes
# Linearizable consistency for lightweight transactions

HBase’s Strong Consistency

HBase’s default STRONG consistency routes reads and writes through a primary region server, so reads see committed writes. HBase also supports TIMELINE reads from replicas, which may be stale. See the Apache HBase consistency guide for the distinction.

Strong reads use the primary region server. With region replicas, an application can request TIMELINE consistency and accept potentially stale reads in exchange for another read path during primary delays. Choose the read mode based on the freshness requirement.

Strong consistency has an availability cost during failover: a region may be temporarily unavailable while its primary is reassigned. The duration depends on failure detection and recovery configuration. Region replicas and timeline reads can improve read availability, with a risk of returning stale data.

Region splits and moves change where clients find data. Their impact depends on the operation and cluster; monitor the deployed version and workload rather than assuming a fixed pause duration.

Handling Inconsistency

# Application-level conflict resolution
def write_with_retry(session, key, value, max_retries=3):
    for attempt in range(max_retries):
        try:
            # Write with latest timestamp
            session.execute(
                "INSERT INTO events (key, value) VALUES (%s, %s)",
                [key, value]
            )
            return
        except WriteTimeoutException:
            if attempt == max_retries - 1:
                raise
            time.sleep(0.1 * (attempt + 1))

# Conflict resolution strategies:
# 1. Last-write-wins (use TTL for automatic cleanup)
# 2. Application-defined merge (examine timestamps, values)
# 3. CRDTs (Conflict-free Replicated Data Types)

Capacity Estimation: Partition Sizing and Bloom Filter Memory

Partition-size guidance is version- and workload-specific, not a universal service limit. The current Cassandra 5.0 data-modeling guide gives general guidelines of fewer than 100,000 values and less than 100 MB on disk per partition, while noting that requirements vary by application. The 2-billion-cell hard limit is documented in the Cassandra 4.0 model-refinement guide; treat that as a version-pinned implementation limit, not a safe target. Measure your actual schema and workload, and use the release-specific docs.

Estimate a partition from its expected rows and values, then validate that estimate against data in the deployed schema. For example, if a sensor query reads one day at a time, use (sensor_id, day) as the partition key and timestamp as a clustering column; estimate the day’s rows from the sampling rate and retention, and choose a smaller bucket if that partition would become too large. At higher sampling rates, an unbucketed per-sensor history concentrates writes and reads in one growing partition. The bucket adds another query dimension, so the application may need to request several buckets for a wider time range.

Cassandra uses bloom filters to avoid reading partitions that do not contain the requested row key. Each SSTable has its own bloom filter, and bloom filter memory is roughly 1-2 bytes per key per SSTable. For a table with 100GB of data stored across 100 SSTables and 1 billion partition keys, you are looking at roughly 200MB of bloom filter memory per node. This is compact enough to keep in memory and is why bloom filters are effective at reducing unnecessary disk reads.

HBase also uses bloom filters at the StoreFile level. The block size (default 64KB or 128KB) determines how many disk reads a bloom filter can eliminate. With a bloom filter, HBase can skip entire blocks when the row key is confirmed absent. Without it, HBase reads the block index and then the data block.

Do not derive a cluster’s partition count from one target-size division. Partition-key distribution, replication strategy, number of nodes, hot keys, SSTable layout, and query fan-out all affect behavior. Use the size and cell-count tools for your Cassandra release (for example, the Cassandra 5.0 sstablepartitions tool) and validate with representative reads and writes.

Observability Hooks: Cassandra Nodetool and HBase Master Metrics

For Cassandra, nodetool is the primary operational interface. The commands that matter in production: nodetool status shows which nodes are up and how much data each owns. nodetool tpstats shows thread pool statistics — if DroppedMessages is non-zero, your cluster is overloaded and messages are being dropped. nodetool tablestats gives per-table read/write latency, tombstone counts, and bloom filter false positive rates. nodetool proxyhistograms shows the full distribution of latencies across all coordinators.

The bloom filter false positive rate (FFP) tells you if bloom filters are working. An FFP above 1% means too many unnecessary disk reads are occurring — your bloom filter is not eliminating enough absent key lookups. This usually happens when partition sizes grow too large or when the bloom filter was misconfigured at table creation.

For HBase, the HBase Master UI exposes region assignment, load distribution, and compaction queue depth. The RegionServer metrics are more critical: MemStoreSize (if it approaches hbase.regionserver.global.memstore.size, writes will be blocked), StoreFileCount (too many StoreFiles indicate compaction is lagging), and compactionQueueSize. If the compaction queue grows faster than it is consumed, read latency degrades.

HBase also exposes metrics via JMX: HRegionServer.metrics shows per-region read/write latencies. The SlowGet metric tracks get operations taking longer than hbase.slow.get.threshold (default 1000ms). If SlowGet is climbing, your BlockCache is likely thrashing or HFiles have grown too large.

For both systems, monitor your compaction impact. Cassandra’s nodetool compactionhistory shows compaction throughput over time. HBase’s admin.getCompactionState() per table shows whether minor or major compactions are running. Compaction I/O competes with normal read/write I/O — if latency spikes coincide with compactions, consider throttling compaction throughput or scheduling it during off-peak hours.

Illustrative Case: bucketing an activity feed

Consider an activity feed partitioned only by user ID. A high-activity account can accumulate far more rows than an ordinary account, creating a hot and oversized partition. This is an illustrative scenario, not a report about a named company.

A bounded bucket such as (user_id, month) or (user_id, bucket_number) can spread that history across partitions. The query must then select the relevant buckets, which adds read fan-out and application logic. Choose the bucket size from retention, write rate, and read patterns, and monitor real partition sizes.

The design lesson is to estimate growth and access patterns before selecting a bucket, then revisit the estimate with observed partition sizes and query latency.

Interview Questions

1. You are designing a Cassandra table for an IoT sensor network. Each sensor sends 100 readings per minute, and you need to query readings by sensor and time range. How do you model the partition key?

Illustrative sizing exercise: for a sensor writing 100 rows per minute, a daily bucket holds 144,000 rows before accounting for other data. Estimate the actual partition size from the serialized row shape and Cassandra's storage overhead; the 200-byte row size is only a placeholder and must come from measurement. If the bucket would grow beyond an acceptable size for your workload, use a shorter interval. Keeping only sensor_id as the partition key with time as a clustering column can leave a long-lived, growing partition.

2. Your Cassandra cluster has one node showing 3x higher latency than other nodes despite similar data sizes. What do you investigate first?

Check nodetool tpstats on the slow node for non-zero DroppedMessages, which indicates the node is overloaded and cannot keep up with requests. Then check nodetool compactionstats — if compactions are running constantly, the node is I/O bound. Also check nodetool tablestats for that node specifically to see if one table has unusually large partitions or a high bloom filter false positive rate. A single large partition forces Cassandra to read more data per query, and if that partition is hosted on one node, that node bears the extra load while others do not.

3. When would you choose HBase over Cassandra?

HBase makes sense when you are already in the Hadoop ecosystem and need native integration with MapReduce, Spark, or Hive for bulk processing of your data. HBase also makes sense when you need strong consistency guarantees — Cassandra's tunable consistency means you can accidentally read stale data if your consistency level does not match your requirements. HBase is also preferable when your access patterns are predominantly sequential reads and writes (which HDFS handles well) and when you need efficient wide scans across large tables. If you do not have ZooKeeper expertise and are not in the Hadoop ecosystem, HBase's operational complexity is a liability.

4. What happens internally when a Cassandra partition becomes too large?

Cassandra does not split an oversized logical partition into smaller partitions automatically. Large partitions can increase read work, memory pressure, and compaction cost, but the outcome depends on schema, release, and workload. Current Cassandra 5.0 guidance gives general targets below 100 MB on disk and 100,000 values per partition; these are guidance, not hard rejection thresholds. Cassandra 4.0 docs describe the 2-billion-cell hard limit. If projected growth approaches a suitable limit, design a bounded bucket in the partition key and account for the extra reads it requires.

5. What is the difference between Cassandra's Leveled Compaction Strategy (LCS) and Size-Tiered Compaction Strategy (STCS)? When would you choose each?

In the Cassandra 5.0 documentation, UCS is recommended for many new workloads. STCS can suit workloads where other strategies do not fit or LCS I/O is too high; LCS targets read-heavy workloads and workloads with many updates or deletes; TWCS targets mostly immutable time-series data with TTLs. These strategies have different disk and I/O costs. Check the [Cassandra compaction guide](https://cassandra.apache.org/doc/stable/cassandra/managing/operating/compaction/overview.html) and benchmark with representative data before choosing one.

6. How does Cassandra's lightweight transactions (LWT) work, and what is the performance cost?

Cassandra LWT uses the IF clause in CQL (for example, UPDATE ... IF condition) to provide compare-and-set semantics through Paxos. This adds coordination compared with a regular write, so measure latency and throughput with the deployed topology and workload. Use LWT when the conditional operation needs that guarantee; an application-level read-then-write can race unless it uses an equivalent atomic mechanism.

7. How do you handle Cassandra tombstone accumulation and the resulting read performance degradation?

Deletes and TTL expiration create tombstones so Cassandra can reconcile replicas. Reads that scan many tombstones can require more work. Use TTLs only when expiration matches the data-retention requirement; TTL does not remove tombstones immediately. TWCS can help for mostly immutable time-series data with TTLs when the window settings match the data's arrival and expiration pattern. Monitor the deployed Cassandra version's tombstone and compaction metrics, and use cleanup commands only after checking their release-specific behavior.

8. Compare HBase's HFile structure to Cassandra's SSTable. How does the storage format affect read/write performance?

Both HBase HFiles and Cassandra SSTables are immutable, append-only storage files with sorted key-value pairs. The key difference is in how they handle writes: HBase writes go through a MemStore and are flushed to HFiles when full; compaction merges HFiles and removes deleted cells. Cassandra writes go through a MemTable and are flushed to SSTables, with compaction merging SSTables and handling tombstones. Read performance in both depends on bloom filters and block indexes stored at the file level — these determine whether a file must be read for a given row key. HBase's BlockCache caches data blocks in memory; Cassandra's key cache caches row summaries. Both benefit from row-tiered storage that keeps recent data in fast access tiers. The compaction strategy in both systems determines the tradeoff between write amplification and read performance.

9. How does the HBase write path differ from Cassandra's, and what are the implications for durability?

HBase write path: Client → WAL (Write-Ahead Log) on HDFS → MemStore (in-memory) → acknowledgment. Data is durable as soon as it is written to the WAL, which is replicated across HDFS DataNodes. Cassandra write path: Client → WAL (commitlog) → MemTable → acknowledgment. Data is durable when written to the commitlog on disk. The difference: HBase's WAL is on HDFS, which provides replication and durability guarantees beyond a single node. Cassandra's commitlog is local disk — for true durability you need replication to other nodes or proper fsync configuration. HBase's architecture means data survives node failures more gracefully (HDFS handles replication and rebalancing). Cassandra requires explicit replication factor settings and repair operations for durability.

10. What is the difference between anti-entropy repair and incremental repair in Cassandra?

Repair compares replica data and streams differences so replicas can converge. Its runtime and resource use depend on data size, topology, and repair settings. nodetool repair -pr limits work to the node's primary ranges. Incremental repair behavior and options depend on Cassandra version; follow the release-specific repair guide and schedule work with the table's repair and tombstone requirements in mind.

11. How do you design a Cassandra schema for a messaging application where you need to query by conversation and by time, and handle unlimited message growth?

Design with bucketing to handle unlimited growth. Use (conversation_id, bucket_id, message_id) as the primary key, where bucket_id is a time bucket (e.g., monthly). This keeps messages within a conversation grouped together for queries, and bounds partition size to one bucket's worth of messages. For querying all messages in a conversation within a time range, you query the specific buckets that cover the time range. Each partition is bounded: even a busy conversation only stores 1-2 months of messages per bucket. Add writetime as a clustering column for ordering within the bucket. Use a separate table for the latest message per conversation (updated on each send) for inbox listing queries, so you do not need to scan all buckets to show the conversation list.

12. What are the tradeoffs between HBase's ZooKeeper-based coordination versus Cassandra's gossip-based coordination?

ZooKeeper provides a centralized, consistent coordination service — all cluster state changes go through ZooKeeper consensus. This gives HBase strong consistency guarantees on cluster operations (region assignment, master election) but creates a dependency: ZooKeeper is a single point of failure if not properly replicated, and ZooKeeper performance limits cluster operation speed. Cassandra uses gossip protocol — nodes exchange state information peer-to-peer, no central coordinator. This is more resilient to node failures (no single point of failure) and scales better for large clusters, but achieving consistency takes longer (must wait for gossip to propagate through the cluster). Cassandra's approach is operationally simpler (no ZooKeeper cluster to manage) but requires more nodes for quorum decisions. ZooKeeper's approach is more predictable but adds operational complexity.

13. How does Cassandra's hint replay work, and what happens to writes during a node's downtime?

When a Cassandra node is down, other nodes store hints (small files containing the failed write) for the duration of max_hint_window (default 3 hours). When the down node comes back, the coordinator replays the hints — the writes are applied as if they came from the original coordinator. This provides eventual durability for writes that failed during the downtime. The implications: if a node is down longer than max_hint_window, writes to that node are lost and must be recovered via anti-entropy repair. The node that was down will be out of sync until repair runs. Use nodetool repair after any significant downtime to synchronize data.

14. What is the difference between LOCAL_ONE and LOCAL_QUORUM consistency levels, and when would you use each?

LOCAL_ONE requires one replica in the coordinator's local datacenter; LOCAL_QUORUM requires a majority of replicas in that datacenter. QUORUM counts a majority in the operation's replica set; it does not mean a majority in every datacenter. For reads and writes, reason about the chosen levels together with the keyspace replication strategy. With a single replication scope, read and write quorums whose counts satisfy R + W > RF intersect. This is not by itself a promise of linearizability for all concurrent operations.

15. How should you interpret Cassandra partition-size guidance and the documented cell limit?

Cassandra 4.0 documentation identifies a 2-billion-cell hard partition limit; the Cassandra 5.0 modeling guide gives size guidance that depends on the application. Neither value is a universal safe target. Estimate maximum rows, values, and bytes for the schema, then validate against observed partitions with tools supported by the deployed release. If unbounded growth is possible, a time bucket can cap a partition's age or row count, at the cost of reading more partitions for wider ranges.

16. How do Cassandra's bloom filters work, and how would you diagnose a bloom filter false positive rate that has climbed to 5%?

A Bloom filter can say that a partition is absent from an SSTable, but a positive result may be a false positive. A false positive can cause an extra SSTable lookup; it does not always mean a physical disk read. Memory use and the false-positive rate depend on the table settings and workload. Check the deployed release's Bloom-filter metrics and configuration before changing the chance of a false positive; compaction or rebuilding data is not a general first response to one rate value.

17. What are virtual nodes (vnodes) in Cassandra, and how should a team choose the token count?

Virtual nodes assign multiple token ranges to a physical node. More ranges can make cluster expansion more flexible, but also change how many peers share data and how much token-management work the cluster does. Cassandra 5.0 production guidance uses num_tokens: 16 as its default example and discusses other counts by cluster size and availability goals. Treat that as release-specific guidance: check the [current token recommendations](https://cassandra.apache.org/doc/stable/cassandra/getting-started/production.html#tokens) and benchmark the cluster's topology.

18. How does HBase's major versus minor compaction differ, and when would you intentionally delay major compaction?

Minor compaction merges a few smaller HFiles into a larger one, reducing the number of files that must be read on each query. Major compaction merges all HFiles for a region into a single file and removes deleted cells (tombstones). By default, HBase runs minor compactions continuously and major compactions on a schedule (typically every 24 hours). Delaying major compaction is sometimes intentional when: you have time-sensitive workloads that cannot tolerate the I/O spike (major compaction is I/O intensive on large tables), you rely on TTLs and the TTL window means tombstones will be cleaned before major compaction runs, or you are in a period of high write load and prefer to defer compaction overhead. The risk: deleted data remains visible until major compaction runs (HBase retains deleted cells for versioning), and read performance may degrade as HFile count grows. Monitor compactionQueueSize and StoreFileCount on RegionServers — a growing queue signals compaction is falling behind.

19. What is the role of Cassandra's snitch, and how does the GossipingPropertyFileSnitch differ from SimpleSnitch in a multi-datacenter deployment?

The snitch determines the network topology of a Cassandra cluster — it tells Cassandra which datacenter and rack a node belongs to, so the replication strategy can place replicas correctly. SimpleSnitch treats all nodes as if they are in the same datacenter and rack — use it only for single-datacenter single-rack clusters. GossipingPropertyFileSnitch is the standard for multi-datacenter deployments: each node gossips its own location (datacenter and rack) to other nodes, and this information propagates cluster-wide via the gossip protocol. This allows Cassandra's replication strategy to place replicas in different datacenters and racks for fault tolerance. Using SimpleSnitch in a multi-datacenter cluster means Cassandra ignores topology — replicas may end up in the same datacenter when they should be spread across datacenters, defeating the purpose of multi-datacenter replication. Always configure endpoint_snitch: GossipingPropertyFileSnitch and set dc and rack in the cassandra-rackdc.properties file for any cluster with more than one datacenter.

20. You need to build an analytics dashboard on Cassandra that aggregates data across all partitions. What are the tradeoffs between materialized views, manual denormalization tables, and Spark integration for this use case?

Materialized views (MV) in Cassandra automatically maintain a denormalized table keyed by a different partition key — useful for shifting the partition key to a new shape while keeping data in sync. Tradeoff: MV writes add overhead to every write in the source table, and MV builds asynchronously so you may read stale data. For analytics aggregating across all partitions, MVs help but do not solve the fundamental problem: Cassandra is not designed for cross-partition scans. Manual denormalization (separate tables per access pattern) gives you full control and predictable performance, but requires your application to keep multiple tables in sync — more code, more complexity, risk of inconsistency. Spark integration (using Spark Cassandra Connector) allows parallel scans across the entire cluster by leveraging Spark's distributed execution model. This is the most scalable approach for analytics — you read all data in parallel, aggregate in Spark, and write results to a separate table or external system. Tradeoff: Spark jobs have startup overhead (not for sub-second queries), and the connector must carefully manage partition pruning to avoid scanning the entire cluster for every query. For dashboard use cases with moderate latency requirements (seconds to minutes), Spark is the right tool; for real-time dashboards, pre-aggregate into a separate table using scheduled Spark jobs.

Failure Scenarios and Trade-off Analysis

Compaction Strategy Trade-offs

Cassandra compaction merges SSTables and affects read work, disk use, and background I/O. The Cassandra 5.0 compaction guide recommends Unified Compaction Strategy (UCS) for many new workloads, while STCS, LCS, and TWCS remain useful for specific patterns. Check the deployed version’s guidance and measure your table before changing its strategy.

Strategy Workload guidance in Cassandra 5.0 docs Considerations
UCS Broad range of workloads, including time series and updates/deletes Tunable parameters; evaluate against the workload
STCS General fallback; may fit workloads where LCS I/O is too high Can require additional disk space during compaction
LCS Read-heavy workloads or workloads with many updates and deletes More I/O and CPU than some alternatives
TWCS Mostly immutable time-series data with TTLs Relies on data’s timestamp and expiration pattern

These descriptions are starting points, not performance guarantees. Compare read latency, disk use, compaction backlog, and write throughput on representative data.

Write Amplification Analysis

Wide-column databases suffer from write amplification — one logical write can become multiple physical writes during compaction.

STCS, LCS, and TWCS produce different compaction patterns, but none has a fixed write-amplification multiplier. The result depends on the data, write and delete patterns, table settings, and workload. Compare observed storage writes with logical writes for the deployed table before changing strategies.


Common Production Failures

Hot partition from an unsuitable key: A sequential value is not automatically a Cassandra hotspot; the partitioner hashes partition keys. A hotspot occurs when many writes target the same partition key, such as a single global counter or one sensor partition that receives all events. Choose a key that distributes writes while still supporting the required reads, and bucket high-volume histories when needed.

Illustrative risk: unbounded time-series partition: If IoT data is partitioned only by sensor and never bucketed, the partition can grow beyond the size the read workload can handle. Choose a time bucket from the retention and write rate, then verify partition sizes with the tools for the deployed Cassandra release.

HBase hotspot from sequential row keys: With a range-partitioned table, sequential row keys can direct new writes to the region that owns the current key range. Key salting, pre-splitting, or a different key design can spread load, but each changes read patterns and should be checked against the table’s access needs.

Cassandra consistency level chosen without matching the requirement: With a replication factor of three in one datacenter, ONE can return from one replica while another has a newer value. QUORUM normally waits for two replicas in the relevant scope, but the guarantee depends on the read and write levels, replication strategy, and operation. Choose both levels against the consistency requirement; a quorum setting alone does not guarantee linearizability.

HBase compaction starving compute resources: HBase runs major compaction at night, merging hundreds of HFiles. On large tables this saturates disk I/O and network bandwidth, and reads slow to a crawl right when your users are waking up. Schedule compactions during off-peak hours or use incremental compaction strategies.

Wrong partition key preventing efficient time-range queries: You model (user_id, order_id) as the primary key, then need to query all orders within a date range regardless of user. Cassandra scatters these across partitions, so range scans hit every node. If time-range access is a real use case, put the date or time bucket in the partition key from the start.


Security Checklist

  • Enable Cassandra’s authenticator and authorizer to enforce role-based access control on keyspaces and tables
  • Use TLS for all inter-node communication (Cassandra’s server_encryption_options) to prevent traffic sniffing between nodes
  • For HBase: enable Kerberos authentication via hbase.security.authentication = kerberos; use ACLs on namespace and table levels
  • Restrict HBase’s Thrift and REST ports to internal networks; disable the HBase Master UI port on public interfaces
  • Encrypt SSTable data at rest using sstableencryption in Cassandra and HDFS encryption at rest for HBase
  • Implement row-level access control in Cassandra using GRANT/REVOKE on roles to limit access to specific partition ranges

Common Pitfalls and Anti-Patterns

Unbounded partition size: A partition with no upper size limit can become expensive to read and compact. Cassandra 5.0 guidance gives general targets below 100 MB on disk and 100,000 values per partition; these are workload guidance, not a hard cap. Cassandra 4.0 documentation describes a hard limit of 2 billion cells. Keep these version-specific statements separate, design bounded buckets for growing histories, and measure partitions with tools for the deployed release.

Tombstone overload during reads: Cassandra marks deleted data as tombstones; queries that must scan many tombstones become slow. Fix: avoid querying partitions with high delete rates, and rebuild problematic tables with nodetool garbagecollect.

Hot partitions in Cassandra: A sequential clustering key does not by itself send writes to one node; Cassandra hashes the partition key. A hot partition occurs when too many writes target the same partition. Choose a partition key and, for high-volume histories, a bucket that distribute writes while still supporting the required queries.

HBase pre-splitting misconfiguration: Starting with a single region causes all initial writes to hit one region server until a split occurs. Fix: pre-split tables using a hex-split strategy or hash-based split keys.

Ignoring bloom filter memory: Bloom filters in Cassandra can consume significant memory for high-cardinality partitions. Fix: monitor BloomFilterFalsePositives and BloomFilterFalseRatio metrics.

Quick Recap Checklist

  • Wide-column databases suit write-heavy workloads with predictable access patterns and horizontal scaling needs
  • Design partition keys for even write distribution; avoid sequential keys and unbounded partition sizes
  • Cassandra offers tunable consistency per operation; HBase’s default strong reads use the primary region server, while timeline reads may be stale
  • Follow the release-specific index and bulk-loading guidance for Cassandra and HBase
  • Monitor tombstone counts, partition sizes, and bloom filter metrics continuously

Further Reading

  • Cassandra Documentation — Official docs, start with the data modeling and CQL sections
  • HBase Reference Guide — Apache HBase official documentation, particularly the region management and compaction chapters
  • DataStax Academy — Free Cassandra courses including certification prep
  • Hadoop Summit Talks — Conference talks on HBase at scale from LinkedIn, Salesforce, and other large-scale deployments
  • Designing Data-Intensive Applications by Martin Kleppmann — Chapters 3 and 5 cover wide-column stores and consistency models in depth

Conclusion

Model a wide-column table from the queries it must serve. In Cassandra, partition keys determine data placement and which reads can be served efficiently; in HBase, row keys determine range locality. Bucket growing histories only when the extra query fan-out is acceptable, and validate consistency and compaction behavior against the deployed release.

For more on NoSQL databases, see the NoSQL overview. For time-series specific databases, see Time-Series Databases. For scaling strategies, see Horizontal Sharding.

Category

Related Posts

CQRS Pattern

Decide whether separate command and query models solve a real problem, how to begin in one store, and when a read model can tolerate lag.

#database #cqrs #event-sourcing

Document Databases: MongoDB and CouchDB Data Modeling

Compare MongoDB and CouchDB data modeling, transactions, consistency settings, and replication behavior with relational databases.

#database #nosql #document-database

Event Sourcing

Storing state changes as immutable events. Event store implementation, event replay, schema evolution, and comparison with traditional CRUD approaches.

#database #event-sourcing #cqrs