Kandra

Recipe: soft delete

Problem: "delete" in your product means "hide it, let the user undo it, maybe purge it for real later" — a todo marked done, a message someone unsent, a listing taken down. A real Cassandra DELETE writes a tombstone that every read has to page past until gc_grace_seconds (ten days by default) elapses — a workload that does this constantly accumulates tombstones and degrades read latency on that table. @SoftDelete reframes "delete" as a TTL'd write instead: no row tombstone at delete time, and an undo window for free. It doesn't make tombstones go away, though — the expiring cells still become tombstones when ttlSeconds fires. The row itself does eventually disappear too, just later, once the marker's own (longer) TTL expires. Both are covered below.

The scenario

A todo list where "done" items disappear from the active view but can be recovered for a while.

Todo.kt
import io.kandra.core.annotations.*
import java.util.UUID
 
@ScyllaTable("todos")
@SoftDelete(ttlSeconds = 604_800, markerProperty = "isDeleted") // 7 days
data class Todo(
    @PartitionKey val ownerId: UUID,
    @ClusteringKey(order = ClusteringOrder.DESC, index = 0) val createdAt: java.time.Instant,
    @ClusteringKey(index = 1) val todoId: UUID,
    val title: String?,  // nullable: expires with the TTL
    val isDeleted: Boolean = false,
)

@SoftDelete(ttlSeconds, markerProperty) is a class-level annotation. markerProperty names a Boolean property on the entity — required if you want findActive() to work at all (more below). Every other non-key property is nullable on purpose: once the TTL fires, those columns read back as NULL.

What delete() actually does — TTL write, not DELETE

Call todoRepo.delete(todo) on a @SoftDelete entity and BatchEngine does not issue a CQL DELETE. It issues two statements instead — an UPDATE for the data columns, and an INSERT (not a second UPDATE — see why below) for the marker:

-- 1. All non-key, non-marker columns, TTL'd
UPDATE todos USING TTL 604800 SET title = ? WHERE owner_id = ? AND created_at = ? AND todo_id = ?
 
-- 2. The marker, as an INSERT (not an UPDATE), under its own longer TTL
INSERT INTO todos (owner_id, created_at, todo_id, is_deleted) VALUES (?, ?, ?, ?) USING TTL 1468800
Why the marker is an INSERT with a TTL, not a plain UPDATE

The marker has to outlive the data columns so there's still something to distinguish "this row is soft-deleted" from "this row is live" while the other columns' values are expired but the row should still exist. @SoftDelete(markerTtlSeconds) controls how much longer — it defaults to ttlSeconds + gcGraceSeconds (604800 + 864000 above = 1,468,800s, since this example's @ScyllaTable doesn't override gcGraceSeconds).

Why an INSERT rather than a second UPDATE, though: the row's original save() is itself an INSERT, which writes a Cassandra row-marker cell — a separate, internal thing from any column — with no TTL of its own. That row marker alone keeps the partition "alive" for SELECT forever, regardless of what TTL a later UPDATE puts on individual columns; UPDATE never touches it. Only a later INSERT, with a real TTL, can supersede it (Cassandra resolves same-cell conflicts by latest write time). So the soft-delete marker write has to be an INSERT specifically to retire that original eternal row marker — an UPDATE would leave it in place forever regardless of what TTL the marker column itself carried.

The row's primary key itself is never touched by a row-level tombstone, and no DELETE is ever issued by delete(). Here is what happens over time:

  • Until ttlSeconds: the row is fully intact with isDeleted = true. This is the undo window.
  • At ttlSeconds: the TTL'd columns expire. Each expired cell becomes a cell-level tombstone that reads have to skip until compaction removes it. is_deleted is untouched — its own, later TTL hasn't fired yet.
  • At ttlSeconds + markerTtlSeconds: the marker's INSERT-backed TTL fires too, retiring both the marker cell and the original row-marker it superseded. The partition has no live cells and no live row-marker left — it's gone, not a husk. Nothing further to do; there's no "hard-delete the ones you don't need to keep" step required anymore (see kandra#154 for the full before/after).
Enum columns and soft delete (0.5.2 — [#198](https://github.com/Dev-Pasaka/kandra/issues/198))

The soft-delete rewrite now encodes values through KandraCodec like every other write. Through 0.5.1 it bound raw property values, so a @SoftDelete entity with an enum (or custom-encoded) column or key failed delete() with CodecNotFoundException.

Kandra won't let you model a non-nullable column into this trap

Caught at registration time, not at read time

Between ttlSeconds and ttlSeconds + markerTtlSeconds, the data columns read back as NULL — title: String? above is nullable specifically because of this window. A non-nullable property with no constructor default would have nothing legal to decode into there: KandraCodec refuses to put NULL into a non-nullable Kotlin property and throws KandraQueryException, "Column 'title' is NULL in Scylla but property 'title' is non-nullable." Any read that reaches such a row would fail, including a partition-scoped findPage that happens to include one old deleted todo — one row breaking a whole page.

Rather than let that surface as a runtime crash the first time a read happens to hit an expired row, SchemaRegistry.register() now rejects a @SoftDelete entity outright if any persisted, non-key, non-marker property is non-nullable with no default — KandraSchemaException, at startup, naming the property, before any route runs (kandra#153). Make the property nullable (as title is here) or give it a constructor default — either satisfies the check; tutorial page 08 uses a default instead, and explains the trade-off between the two.

findActive(): a real query, with a real cost

// KandraSuspendRepository
suspend fun findActive(allowFullScan: Boolean = false): List<T>
// KandraRepository (blocking)
fun findActive(allowFullScan: Boolean = false): List<T>

What it runs depends on whether the marker column is indexed:

  • Marker has @SecondaryIndex: SELECT * FROM todos WHERE is_deleted = ? through the index. No ALLOW FILTERING; allowFullScan is irrelevant.
  • No index, allowFullScan = false (the default): throws KandraQueryException at call time instead of scanning. This changed in 0.4.7 (still current in 0.4.8) — before that it silently ran the scan below.
  • No index, allowFullScan = true: SELECT * FROM todos WHERE is_deleted = ? ALLOW FILTERING, with a WARN naming the cost.

Unpaged results are capped: past the limit Kandra truncates with a WARN instead of loading an unbounded scan into memory, so use findPage() for anything large.

findActive() is a whole-table scan — it is not partition-scoped

This is the single most important thing to know about findActive(), and it's easy to miss because nothing about the method signature warns you: it takes no predicate at all. Whether it goes through a @SecondaryIndex or an opted-in ALLOW FILTERING scan, it reads WHERE <marker> = false across the entire table — every partition, every node, scatter-gather. For Todo above, findActive() does not mean "this owner's active todos" — it means every owner's active todos, cluster-wide. If what you actually want is "my active rows" on a table partitioned by owner, findActive() is very likely the wrong tool.

The right tool for "my non-deleted rows" on a partitioned, time-series-style table is the ordinary partition-scoped findPage/findAll you'd use anyway, plus a client-side filter on the marker:

val page = todoRepo.findPage(pageSize = 20) { TodoTable.ownerId eq ownerId }
val active = page.items.filterNot { it.isDeleted }

The tradeoff: a page can come back with fewer live items than pageSize (possibly zero) after filtering, since the filter happens after the fetch, not in the query. If you need a consistent page size, keep fetching pages until you have enough live items or run out — this is exactly what /recipes/social-feed-capstone had to do for a per-author feed, and it's the honest, working pattern, not a workaround.

findActive() is the right call when the whole table really is what you mean — a small, non-partitioned-for-scale reference table where "all active rows" is a legitimate, bounded query. It stops being appropriate the moment the table is meaningfully partitioned by owner/tenant/user, which is most Cassandra tables.

deleteById used to bypass soft delete entirely

ISS-015: one delete path skipped the TTL rewrite completely

Historically, KandraRepository.deleteById(vararg keyValues) (the blocking repository's key-only delete) built its own raw LOGGED BATCH of a hard deleteById plus lookup-table deletes and executed it directly — it never checked schema.isSoftDelete. Every other delete path on the same table (delete(entity), the suspend repository's deleteById) correctly routed through BatchEngine's soft-delete-aware logic. The result: for a @SoftDelete entity, calling repo.deleteById(id) permanently tombstoned the row — a silent, path-dependent divergence where two methods on the same repository, both named "delete," did fundamentally different things to the same table. It also skipped cache invalidation.

Fixed: deleteById now looks the entity up first (which it already did, to find lookup rows to clean up) and, when found, delegates to the same batchEngine.delete(schema, entity) path every other delete method uses. If the entity doesn't exist, it falls back to a harmless hard-delete-by-key no-op. If you're on an older Kandra version, verify which delete path you're actually calling before trusting @SoftDelete to apply uniformly across a repository's methods.

Lookup rows survive a soft delete — on purpose

If the entity also has a @LookupIndex field, soft-deleting it does not remove the lookup row:

BatchEngine.kt — softDeleteSuspend
// Lookup rows are deliberately left alone (see ISS-030) -- a soft-deleted row still "exists"
// until its TTL expires, so it must remain resolvable via its @LookupIndex too, exactly like
// a direct findById/findActive would still see it. Hard delete is the only path that should
// ever remove lookup rows.
This is correct, but it surprises people coming from hard-delete intuition

A soft-deleted row is still, semantically, "there" until its TTL actually runs out — its non-key data hasn't expired yet, findById still returns it. Removing its lookup row immediately would make it resolvable by primary key but not by the field the lookup indexes on, which is an inconsistent state worse than leaving both paths agreeing. If you need "soft-deleted rows shouldn't be findable-by-lookup either," filter on the marker column after resolving through the lookup, the same way you'd filter a partition-scoped page.

Storage tradeoffs: what you're actually trading

Hard delete()@SoftDelete
Tombstone written immediatelyYes — a row tombstone, right awayNo — TTL'd UPDATE, not a DELETE
Tombstones laterRemoved after gc_grace_seconds (default 10 days)Cell tombstones when ttlSeconds fires, removed gc_grace_seconds later
Row physically goneAfter gc_grace_secondsAfter ttlSeconds + markerTtlSeconds (defaults to ttlSeconds + gcGraceSeconds)
Undo windowNoneExactly ttlSeconds, and undo means writing the row back before it expires
Read cost while "deleted"N/A — row's goneFull row until ttlSeconds, then a husk (still correctly resolvable via isDeleted) until markerTtlSeconds, counted in partition size throughout
Right forRare, deliberate deletes; queue/session-store cleanup you actually want gone fastUndo flows, "trash" semantics, anything a user expects to recover
deleteAll() still warns about tombstones — soft delete doesn't change that call

@SoftDelete only changes what delete()/deleteById()/deleteBy() do for a single entity. deleteAll(entities) on a soft-deleted entity still routes each entity through the same TTL rewrite — no direct tombstones — but if you're bulk-hard-deleting a different, non-@SoftDelete table with deleteAll(), Kandra logs an explicit WARN once the row count exceeds tombstoneWarnThreshold (default 1000), naming gc_grace_seconds in the log line itself. That tripwire and @SoftDelete solve the same underlying problem from two different angles — pick @SoftDelete at modeling time for tables you know will be delete-heavy, and let the deleteAll() warning catch the ones you didn't plan for.

See /foundations for the tombstone mechanics this recipe builds on, and /tutorial/08-soft-delete-and-trash for the fully worked tutorial version with an actual undo endpoint.