Scrivio Interview library
DesignIntermediate6 min read · updated 12 November 2026

An IoT system stores readings per device in Cassandra with PRIMARY KEY ((device_id), ts). Some devices send a reading every second for years, and reads time out on those partitions. Redesign the key and explain how queries change.

With PRIMARY KEY ((device_id), ts), every reading a device ever sends goes into one partition, so a device sending once per second for years builds a partition of hundreds of megabytes that is slow to read, heavy to compact and hard on the heap. The fix is to bucket the partition key by time, for example PRIMARY KEY ((device_id, day), ts), so each partition holds one device-day of about 86,400 rows. Range queries then compute the list of buckets, query each one, ideally in parallel with the driver's async API, and merge the results, and a TTL with TimeWindowCompactionStrategy makes old data cheap to drop.

Why this question is asked

Time series data is one of Cassandra's best use cases and also the most common way to break it. The first table design almost always uses the device as the partition key, and it works perfectly in testing and for months in production, until the oldest devices have accumulated enough history to make their partitions enormous. Interviewers ask this because the fix shows whether we understand what a partition is physically and how to bound it. In this answer, we will see why the current partition is a problem, redesign the key with a time bucket, choose the bucket size with arithmetic, change the queries in Java, and handle expiry with TTL and TWCS.

1Why the Current Partition Keeps Growing

A partition is all rows sharing one partition key. Here the partition key is device_id alone, so it has no upper bound: every new reading is one more row in the same partition, forever. Let us size it. One reading per second is 86,400 rows a day and about 31.5 million rows a year. At roughly 50 bytes per row on disk after overhead, that is around 1.5 GB per device per year, and a device running for three years has a partition of several gigabytes.

Cassandra handles a partition as a unit in several places. Reads have to locate rows inside it through index structures that grow with it, compaction must merge its pieces across SSTables, repair compares it as a whole, and some operations bring large chunks into the heap. So reads of these partitions slow down until they time out, while small devices stay fast, which matches the symptom exactly.

2Bucketing the Partition Key by Time

We add a time bucket to the partition key so that a partition covers a fixed slice of time for one device.

Java
CREATE TABLE readings_by_device_day (
device_id text,
day date, -- the bucket: one partition per device per day
ts timestamp,
value double,
PRIMARY KEY ((device_id, day), ts)
) WITH CLUSTERING ORDER BY (ts DESC)
AND default_time_to_live = 7776000 -- 90 days, if old data expires
AND compaction = {'class': 'TimeWindowCompactionStrategy',
'compaction_window_unit': 'DAYS',
'compaction_window_size': 1};
-- one device-day: at most 86,400 rows, about 4 MB
Partitions before and after bucketing
Partition keyRows per partitionSize after 3 years
(sensor-17)grows by 86,400 per dayabout 4.7 GB, one partition
(sensor-17, 2026-11-05)at most 86,400about 4 MB each
(sensor-17, 2026-11-06)at most 86,400about 4 MB each
Bucketing turns one unbounded partition into many bounded ones.

Notice that the partition key is now the pair (device_id, day). Both values must be given to locate a partition. The device's history is spread across many partitions, one per day, and those land on different nodes because the pair hashes to different tokens, which also spreads the load of busy devices.

3Choosing the Bucket Size

The bucket size comes from two numbers: the write rate and a target partition size. A common guideline is to keep partitions well under about 100 MB, and ideally to tens of megabytes; the exact comfortable limit depends on your Cassandra version and hardware, so check your version and measure. At one reading per second and 50 bytes per row, one day is about 4 MB, so a day bucket is comfortable. A week would be about 30 MB, also acceptable, and would mean fewer partitions to query for long ranges.

The other side of the trade-off is how queries use the data. If dashboards mostly show the last 24 hours, a day bucket means one or two partitions per query. If users often look at a whole month, a day bucket means 30 queries, while a week bucket means five. Devices with very different rates can even use different bucket sizes, as long as the application knows the size for each device.

4How Queries Change in Java

A query for a time range can no longer name a single partition. The application computes every bucket the range covers, queries each one, and merges the results. With the DataStax Java driver 4.x we send the queries asynchronously so they run in parallel.

Java
List<LocalDate> days = from.toLocalDate().datesUntil(to.toLocalDate().plusDays(1)).toList();
PreparedStatement ps = session.prepare(
"SELECT ts, value FROM readings_by_device_day WHERE device_id = ? AND day = ? AND ts >= ? AND ts < ?");
List<CompletableFuture<List<Reading>>> futures = days.stream()
.map(d -> session.executeAsync(ps.bind(deviceId, d, from.toInstant(), to.toInstant()))
.toCompletableFuture()
.thenApply(rs -> collect(rs))) // collect pages through the async result set
.toList();
List<Reading> readings = futures.stream()
.flatMap(f -> f.join().stream())
.sorted(Comparator.comparing(Reading::ts).reversed())
.toList();
// a 3-day range: 3 small partition reads in parallel instead of one huge one

Each query is fast because it reads a bounded partition. For long ranges we limit concurrency, for example eight queries in flight per request, so one user asking for a year does not flood the cluster. Notice also that empty buckets, days when the device was offline, simply return no rows, which is cheap.

Writes barely change: the application computes day from the reading's timestamp, in UTC to avoid bucket confusion around time zones, and inserts as before.

5Expiring Old Data With TTL and TWCS

If readings are kept for 90 days, setting a TTL lets Cassandra expire them automatically. Expired cells become tombstones, which would normally have to be compacted away row by row. TimeWindowCompactionStrategy (TWCS) groups SSTables by the time window in which data was written. Because all data in an old window expires together, Cassandra can drop the whole SSTable once everything in it has expired, without rewriting anything. That makes deletion almost free.

Step throughReading a 3-day range
  1. Compute buckets2026-11-04, 11-05, 11-06
  2. Query each bucket asyncUp to 8 in flight
  3. Each partition returns rowsAt most 86,400 rows, sorted
  4. Merge and sort in the clientNewest first
  5. Return to the caller

5 steps in order. Play them, or step through them one at a time.

The client does the scatter and gather the old key avoided.

6Follow-up questions

Why is TWCS a good fit for this table?

Readings are written once in time order, never updated, and expire after a fixed TTL. TWCS compacts SSTables only within the same time window, so each day's data ends up in one or a few SSTables, and since every row in an old window expires at about the same time, the whole file can be dropped when it fully expires. This avoids the repeated rewriting that size-tiered or leveled compaction would do, and avoids scanning tombstones. The pattern breaks if data arrives very late or is updated later, because then old windows keep receiving writes, so out-of-order writes should be limited.

How do we migrate the existing data?

We create the new table, make the application write to both tables, backfill history from the old table device by device with a throttled job, switch reads to the new table once the backfill is verified, and finally stop writing to the old table and drop it. Each step can be rolled back until the drop.

Could we keep device_id alone and just use LIMIT?

LIMIT reduces the rows returned, not the size of the partition the node must manage. Compaction, repair and heap pressure still scale with the whole partition, so LIMIT does not fix the underlying problem.

7Conclusion

In this answer, we saw that ((device_id), ts) creates an unbounded partition, about 31.5 million rows a year for a device reporting every second, which slows reads, compaction and repair. Bucketing the partition key by day bounds each partition to about 4 MB. Queries now compute the buckets, read them in parallel with the async driver and merge, the bucket size follows from write rate and target size, and TTL with TWCS turns expiry into dropping whole files.

What to say in the interviewAbout 80 seconds aloud

Open with

The problem is that the partition is unbounded. The partition key is just device_id, so every reading a device sends goes into the same partition forever: at one per second that is about 31 million rows a year, gigabytes after a few years, and Cassandra reads, compacts and repairs a partition as a unit, so those devices time out while small ones stay fast.

Then, if they want more

I would bucket the partition key by time: PRIMARY KEY ((device_id, day), ts) with clustering order ts descending. Then each partition holds one device-day, at most 86,400 rows and around 4 MB.

I would pick the bucket from the write rate and a target partition size, well under about 100 MB, and from how wide typical queries are; a week bucket could also work here.

Queries for a range now compute the list of days, run one query per bucket with executeAsync in parallel, with a concurrency limit, and merge and sort the results in the client. Writes compute the day in UTC.

If old data expires, I would set a default TTL and use TimeWindowCompactionStrategy with daily windows, so whole SSTables are dropped when they expire instead of compacting tombstones. Migration would be dual writes, a throttled backfill, a read switch and then dropping the old table.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "An IoT system stores readings per device in Cassandra with PRIMARY KEY ((device_id)...": https://scrivio-interview-library.netlify.app/databases/cassandra-and-dynamodb/aaaa26947e/