Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Concept · 25 min · revision 2

Partition Keys and Clustering in Wide-Column Stores

See how a partition key places rows on nodes and clustering columns order them, design one table per query, and size partitions so they neither grow without limit nor concentrate the load on one node.

Contentsand lesson path

What you will learn

  • Design a wide-column or key-value table around partition and clustering keys that avoids hot and unbounded partitions.

01. Why it matters

In a wide-column store such as Apache Cassandra, or a key-value store such as Amazon DynamoDB, the primary key is the query plan. There is no optimiser that will find another way to your data. A query that names the right key reads one small, sorted slice from a few nodes; a query that does not name it is refused, or has to read the whole table.

Key mistakes also stay hidden at first. A table keyed by driver works perfectly in a test with ten drivers and a week of data. A year later one partition holds millions of rows, or one popular key takes most of the traffic while the other nodes sit idle. This lesson shows the mechanism behind both failures and the standard fixes, using small Python models you can run with Python 3.12 and no packages. Lesson 4 then builds a full table set for the ride-hailing workload.

02. Partition key and clustering columns

A Cassandra primary key has two parts, written PRIMARY KEY ((a, b), c, d). The columns in the inner brackets form the partition key; the columns after it are clustering columns.

  • The partition key decides where a row lives. Cassandra hashes it (with the Murmur3 function by default) into a number called a token, and the token decides which nodes hold the row. All rows with the same partition key form one partition and live on the same set of replica nodes.
  • The clustering columns decide the order of rows inside a partition. Rows are stored sorted by them, ascending unless the table says WITH CLUSTERING ORDER BY (ts DESC). That order cannot be changed after the table is created, and queries can only return the stored order or its exact reverse.

Here is a table for driver location pings, written in CQL, Cassandra's query language. This lesson does not run Cassandra; the block shows what the Python model below imitates:

CQL · illustrative, not run in this lesson
CREATE TABLE driver_pings (
  driver_id text, day date, ts timestamp,
  lat double, lon double, speed float, heading float,
  PRIMARY KEY ((driver_id, day), ts)
) WITH CLUSTERING ORDER BY (ts ASC);

SELECT ts, lat, lon FROM driver_pings
WHERE driver_id = 'D007' AND day = '2026-11-02' AND ts >= '2026-11-02 08:30';

The model keeps each partition as a sorted list, and stands in for the token ring with an MD5 hash of the key modulo six nodes. Real Cassandra uses Murmur3 tokens and keeps several replicas, but the property that matters is the same: one partition key, one place.

Python · partitions.py
import hashlib
from bisect import insort
from collections import defaultdict

NODES = 6


def node_for(partition_key: tuple) -> int:
    """Stand-in for Cassandra's Murmur3 token ring: hash the key, pick a node."""
    digest = hashlib.md5(repr(partition_key).encode()).digest()
    return int.from_bytes(digest[:8], "big") % NODES


# Table driver_pings: PRIMARY KEY ((driver_id, day), ts)
table: dict[tuple, list] = defaultdict(list)  # partition key -> rows sorted by ts


def insert(driver_id: str, day: str, ts: str, lat: float, lon: float) -> None:
    insort(table[(driver_id, day)], (ts, lat, lon))  # clustering order: ts


for minute in range(0, 60, 10):
    for driver in ("D007", "D012"):
        for day in ("2026-11-01", "2026-11-02"):
            insert(driver, day, f"08:{minute:02d}", 51.50 + minute / 1000, -0.12)

for key in sorted(table):
    print(key, "-> node", node_for(key), "|", len(table[key]), "rows")

# "Latest 3 pings of D007 on 2 Nov": one partition, a slice from its sorted end.
print("latest 3:", [row[0] for row in table[("D007", "2026-11-02")][-3:]])

# "Every ping at 08:20, any driver": no partition key, so read every partition.
hits = [k for k, rows in table.items() if any(r[0] == "08:20" for r in rows)]
print("partitions read without a key:", len(table), "| with a match:", len(hits))
Terminal
python partitions.py
Expected output
('D007', '2026-11-01') -> node 0 | 6 rows
('D007', '2026-11-02') -> node 0 | 6 rows
('D012', '2026-11-01') -> node 2 | 6 rows
('D012', '2026-11-02') -> node 5 | 6 rows
latest 3: ['08:30', '08:40', '08:50']
partitions read without a key: 4 | with a match: 4

The two days of driver D007 happen to land on the same node here, and D012's days on different nodes: placement follows the hash, not the meaning of the key. Latest 3 pings of D007 on 2 November names a whole partition key, so it goes to one place and reads a contiguous slice from the end of a sorted list. Every ping at 08:20 names no partition key, so it must open every partition on every node. With four partitions that is cheap; with ten million it is a full cluster scan. Cassandra refuses such a query unless you add ALLOW FILTERING, which is its way of saying you asked for a scan.

The rules that follow from this: a query must give every partition key column with equality (an IN list counts as equality); it may then restrict clustering columns in their declared order, using a range only on the last one it restricts; and it can sort only by the clustering order or its reverse.

03. One table per query

Because each table answers only questions about its partition key, you design tables from queries, not from entities. The ride-hailing app reads trips three ways: by rider (history), by driver and day (earnings) and by city and hour (a live demand map). In a relational database one trips table with three indexes would serve all three. In Cassandra you create three tables, trips_by_rider, trips_by_driver_day and trips_by_city_hour, and the application writes every trip to all three.

That is denormalisation: the same facts stored several times, each copy arranged for one read. Cassandra is built for heavy write traffic, so this is the normal trade. The costs are more storage and keeping the copies in step: if a trip's fare is corrected, every table holding that trip must be updated. Cassandra also has secondary indexes and materialised views, but its configuration reference marks materialised views as experimental and not recommended for production, so query tables remain the default design.

04. Unbounded partitions and time buckets

A partition that keeps growing for as long as its key exists is unbounded. Partition only by driver_id, and every ping a driver ever sends lands in one partition. The Cassandra documentation measures partition size in cells, the stored values: rows times non-key columns, plus any static columns. Its hard limit is 2 billion cells per partition, and it warns that you will likely hit performance problems well before that. Very large partitions slow down reads and background work such as compaction and repair on their replicas, and they load one replica set more than the others.

The fix is a bucket: an extra partition key column that cuts the stream into bounded pieces, usually a time unit. Compare bucket sizes for a driver who pings every 4 seconds over a 10-hour shift:

Python · buckets.py
PING_EVERY_S = 4
SHIFT_HOURS = 10  # one full-time driver's day online
rows_per_hour = 3600 // PING_EVERY_S
rows_per_day = rows_per_hour * SHIFT_HOURS
VALUES_PER_ROW = 4  # lat, lon, speed, heading: the non-key columns


def cells(rows: int) -> int:
    """Cassandra's sizing formula with no static columns: rows x values per row."""
    return rows * VALUES_PER_ROW


DESIGNS = [  # partition key, rows in its largest partition, partitions per day read
    ("(driver_id)", rows_per_day * 365 * 3, 1),  # after 3 years, still growing
    ("(driver_id, month)", rows_per_day * 31, 1),
    ("(driver_id, day)", rows_per_day, 1),
    ("(driver_id, hour)", rows_per_hour, SHIFT_HOURS),
]
print(f"{'partition key':<20} {'rows':>10} {'cells':>11} {'reads/day query':>16}")
for key, rows, reads in DESIGNS:
    print(f"{key:<20} {rows:>10,} {cells(rows):>11,} {reads:>16}")
Terminal
python buckets.py
Expected output
partition key              rows       cells  reads/day query
(driver_id)           9,855,000  39,420,000                1
(driver_id, month)      279,000   1,116,000                1
(driver_id, day)          9,000      36,000                1
(driver_id, hour)           900       3,600               10

The unbucketed key is the only one that keeps growing: almost 10 million rows after three years, and more every day. A day bucket gives 9,000 rows, and the main query, one driver's day, still reads exactly one partition. An hour bucket makes partitions tiny, but the same query now reads ten of them. Choose the bucket from the read pattern: make it the unit your main query asks for, or a little larger, so a typical read touches one or two partitions while the largest stays bounded.

Buckets combine with clustering order. The driver profile shows the 50 most recent ratings a driver received, and a busy driver collects thousands a year. A key such as PRIMARY KEY ((driver_id, year), rated_at, trip_id) with CLUSTERING ORDER BY (rated_at DESC) keeps each driver's ratings in yearly pieces, with the newest rows first, so the read is one slice from the top of one partition. Early in January the current bucket may hold fewer than 50 ratings, so the application also reads the previous year and stops when it has enough. trip_id is a clustering column only to keep two ratings with the same timestamp from overwriting each other.

05. Hot partitions and write sharding

A hot partition gets far more traffic than the others, usually because the key has few values or one value is far more popular. Since a partition lives on one replica set, its load cannot spread however many nodes you add. DynamoDB makes the ceiling explicit: each partition is designed to deliver at most 3,000 read units and 1,000 write units per second, so one hot key can be throttled while the table as a whole uses a fraction of its capacity.

The standard fix is write sharding: append a suffix to the key, such as London#0 to London#15, so one logical key becomes many partitions. A random suffix spreads writes best, but then nobody knows which shard holds a given item. A calculated suffix, such as a hash of the request ID modulo 16, spreads writes almost as well and lets you find an item again from its ID. The model sends 60,000 ride requests, 70% of them from London, to six nodes:

Python · hot.py
import hashlib
import random
from collections import Counter

NODES = 6
SHARDS = 16
rng = random.Random(1)
CITIES = ["London", "Leeds", "Bristol", "York"]
WEIGHTS = [70, 15, 10, 5]  # share of Friday-night ride requests per city


def h(text: str) -> int:
    return int.from_bytes(hashlib.md5(text.encode()).digest()[:8], "big")


def node_for(partition_key: str) -> int:  # stand-in for the token ring
    return h(partition_key) % NODES


requests = [(i, rng.choices(CITIES, WEIGHTS)[0]) for i in range(60_000)]
designs = {
    "city": [city for _, city in requests],
    # calculated suffix: the shard comes from the request id, so it is repeatable
    "city#shard": [f"{city}#{h(str(i)) % SHARDS}" for i, city in requests],
}
print(f"{'partition key':<14} {'partitions':>10} {'busiest partition':>18} "
      f"{'busiest node':>13}")
for name, keys in designs.items():
    per_partition = Counter(keys)
    per_node = Counter(node_for(k) for k in keys)
    print(f"{name:<14} {len(per_partition):>10} "
          f"{max(per_partition.values()) / len(keys):>18.1%} "
          f"{max(per_node.values()) / len(keys):>13.1%}")
Terminal
python hot.py
Expected output
partition key  partitions  busiest partition  busiest node
city                    4              70.0%         80.1%
city#shard             64               4.5%         33.3%

With the city as the key, one partition takes 70% of all writes, and the node holding London (shared with Bristol, as it happens) takes 80%. With 16 shards per city, the busiest partition takes 4.5%, well under any per-partition ceiling. The busiest node still takes 33%, not the ideal 17%, because 64 keys hashed onto six nodes do not spread evenly; more shards would smooth it further.

Sharding has a price on the read side. London requests in the last hour used to be one partition read; now it is 16 reads whose results the application merges. So shard only keys that are actually hot, pick the shard count from measured load, and prefer a key that is naturally spread (such as (city, hour) combined with a shard) over a large fixed fan-out.

06. Check your understanding

Practice check · 3 questions

Keys, buckets and shards

Each question has one best answer.

Q1. The table driver_pings has `PRIMARY KEY ((driver_id, day), ts)`. Which query can Cassandra serve from one partition without ALLOW FILTERING?
Q2. A driver app pings every 5 seconds during an 8-hour shift, into a table keyed `((driver_id, day), ts)`. About how many rows does one driver-day partition hold?
Q3. A hot key `campaign_42` is split into `campaign_42#0` to `campaign_42#19` with random suffixes. What must the dashboard that shows the campaign total now do?
Practice only: not graded, not saved, not evidence.

07. Apply it

For your ride-hailing project, write a Cassandra-style table for each of these queries: a rider's trip history, a driver's trips on a day, and the location pings of one trip. For each table, give the full PRIMARY KEY and clustering order, estimate the rows in the largest partition after three years from stated rates, and say whether any key value can be hot. If one can, choose a shard count and describe how the read side finds and merges the shards.

08. Review prompt

Without looking back:

  1. What do the partition key and the clustering columns each decide?
  2. Which conditions must a query meet to be served from one partition?
  3. How do you choose the size of a time bucket, and what goes wrong if it is too large or too small?
  4. What does write sharding fix, what does it cost, and when would you choose a calculated suffix over a random one?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check