Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Spring Data Cassandra partition keys: model the read before the row

Last updated: 1 Oct 20264 min read
tutorial
IntermediateBy AITrove Editorial

A Cassandra partition key decides where rows live and which reads stay bounded.

Start with the access path

A parcel event viewer reads one tenant's events for one parcel in descending event time. Put tenant and parcel in the partition key; place event time in the clustering columns. An entity with only an event ID as its key cannot serve this read without another table or a scan. Tenant predicates in a relational query do not repair a Cassandra table whose partition key omits tenant ownership.

Watch partition growth

A single tenant-wide partition can grow without bound. Using the parcel ID reduces that risk, but a parcel with millions of events may still need a time bucket. Bucket size is a workload decision: smaller buckets spread storage and require more reads for a long history. State the maximum requested time window before choosing the bucket.

Verify the actual query

Create two tenants with the same parcel identifier, then request one tenant's recent events. Confirm the generated CQL selects by the full partition key and does not use ALLOW FILTERING. Measure partition size and p95 latency under the expected event distribution.

Implementation sketch

Java
@Table("parcel_events")
class ParcelEvent {
    @PrimaryKeyColumn(ordinal = 0, type = PrimaryKeyType.PARTITIONED)
    String tenantId;
    @PrimaryKeyColumn(ordinal = 1, type = PrimaryKeyType.PARTITIONED)
    String parcelId;
    @PrimaryKeyColumn(ordinal = 2, type = PrimaryKeyType.CLUSTERED,
        ordering = Ordering.DESCENDING)
    Instant recordedAt;
    String status;
}

Cost and verification

Reads within one known partition avoid a cluster-wide scan, but writes and stored rows still concentrate on hot keys. A bucket spreads load at the cost of extra reads.

Common Mistakes

  • Do not add ALLOW FILTERING to hide a missing access path.
  • Do not use a tenant-only partition key when one tenant can produce an unbounded event stream.
  • Do not assume Cassandra can sort arbitrary columns outside clustering order.

Read next

Spring JdbcTemplate tenant predicates: put ownership in the SQL query, Spring Data MongoDB tenant uniqueness: enforce it in an index, Spring Data Cassandra paging state: continue the same bounded query.

Related boundary

Spring Data Cassandra conditional insert: reserve one key once

Check your understanding

Spring Cassandra write and query contracts quiz

spring
spring-boot
data-transactions
cassandra-partition-key-query
Storage details