08. Soft delete and undo
DELETE /todos/{createdAt}/{todoId} from page 05 is permanent right now. The product wants a
real, common feature instead: delete a todo, but let the user recover it for a week before it's
really gone. This page builds that, and it's worth being precise about the actual timeline — "delete,
but recoverable for a while" is not the same thing as a relational soft-delete flag, because
Cassandra doesn't have a free, silent DELETE to fall back on once the window closes.
@SoftDelete on Todo
@ScyllaTable("todos")
@SoftDelete(ttlSeconds = 604_800, markerProperty = "isDeleted")
data class Todo(
@PartitionKey val ownerId: UUID,
@ClusteringKey(order = ClusteringOrder.DESC, index = 0) val createdAt: Instant,
@ClusteringKey(index = 1) val todoId: UUID,
val title: String = "",
val assigneeId: UUID?,
val done: Boolean = false,
@Version val version: Long = 1L,
@UpdatedAt val updatedAt: Instant = Instant.EPOCH,
val isDeleted: Boolean = false,
)ttlSeconds = 604_800 is seven days. markerProperty = "isDeleted" names a Boolean property
Kandra validates exists and is actually Boolean at registration time — without it, delete() still
works (it defaults to 86_400 seconds and no marker at all) but there is no CQL predicate that can
tell a soft-deleted row apart from a live one before its TTL expires, and findActive() throws
KandraSchemaException outright if called with no marker configured. No code in this app's own
delete() call site changes — todoRepo.delete(existing), already used since
page 05, starts behaving differently the moment this annotation exists.
@SoftDelete requires every non-key, non-marker column to be nullable or have a constructor
default — title is the only property on Todo that was neither before this default was added.
Leave it as a bare val title: String and the app refuses to even start:
SchemaRegistry.register() throws KandraSchemaException naming the property, at startup, before
any route runs. See the callout further down for why this check exists.
What delete() actually does now — two separate writes, not one
-- 1. Every non-key, non-marker column, rewritten with a fresh 7-day TTL
UPDATE todos USING TTL 604800
SET title = ?, assignee_id = ?, done = ?, version = ?, updated_at = ?
WHERE owner_id = ? AND created_at = ? AND todo_id = ?
-- 2. The marker, in a separate statement — an INSERT, not an UPDATE, under its own longer TTL
INSERT INTO todos (owner_id, created_at, todo_id, is_deleted)
VALUES (?, ?, ?, ?)
USING TTL 1468800Both statements set the deleted state conceptually, but only the second one touches is_deleted.
The first rewrites every other column with its current value, just now carrying a 7-day TTL — the
whole row's data, not a single flag, is what expires first. The marker gets a separate, much longer
TTL (ttlSeconds + gcGraceSeconds by default — 7 days + the 10-day gc_grace_seconds default
mentioned below, 1,468,800 seconds — tunable via @SoftDelete(markerTtlSeconds = ...)) so
findActive() can still tell "deleted" from "live" for the whole window after the data columns
expire, while the row still eventually disappears completely instead of becoming a permanent husk —
see the timeline below for exactly why this is an INSERT, not a second UPDATE.
findActive() — and why it's the wrong tool here anyway
// KandraSuspendRepository, which this app uses
suspend fun findActive(allowFullScan: Boolean = false): List<T>
// KandraRepository (blocking) has the same signature without `suspend`isDeleted here has no @SecondaryIndex, so as of 0.4.8 a bare findActive() throws
KandraQueryException instead of scanning. Only findActive(allowFullScan = true) runs
SELECT * FROM todos WHERE is_deleted = ? ALLOW FILTERING, bound to false (adding
@SecondaryIndex to the marker makes it query the index instead). Every other page on this site, correctly, says Kandra's
query DSL has no method that produces ALLOW FILTERING — that's still true of QueryContext/
findAll/findPage/find. findActive() is hand-written CQL outside that DSL entirely, built
specifically because there is no partition-scoped way to express "every row where a non-key column
equals X" — and when you do opt in, it logs a WARN every call naming exactly that cost ("scans with ALLOW FILTERING
... scatter-gather across all nodes"), the same treatment @SecondaryIndex queries get. It's a
real, deliberate, narrow exception to the "no ALLOW FILTERING, ever" rule — not a contradiction of
it, but worth knowing about precisely rather than assuming the rule is absolute everywhere.
More importantly for this app: findActive() takes no predicate at all — it scans the entire
todos table, every owner's partition, and returns every non-deleted row across the whole app.
That's exactly wrong for "show me my non-deleted todos." The right tool, per
Kandra's own capstone example
hitting this identical problem with a soft-deleted, partitioned Post table, is the query this app
already has: an ordinary partition-scoped findPage, filtered client-side.
get("/todos/mine") {
val ownerId = call.ownerIdOrRespondBadRequest() ?: return@get
// ... pageSize, token as before ...
val page = todoRepo.findPage(pageSize, token) { TodoTable.ownerId eq ownerId }
val active = page.items.filterNot { it.isDeleted }
call.respond(TodoPage(active, page.nextPageToken, page.hasMore))
}The one line that changes from page 05's version: filter out isDeleted
rows after the (still cheap, still partition-scoped) fetch. GET /todos/trash is the mirror image —
same query, opposite filter:
get("/todos/trash") {
val ownerId = call.ownerIdOrRespondBadRequest() ?: return@get
val pageSize = call.request.queryParameters["size"]?.toIntOrNull() ?: 20
val token = call.request.queryParameters["token"]
val page = todoRepo.findPage(pageSize, token) { TodoTable.ownerId eq ownerId }
val deleted = page.items.filter { it.isDeleted }
call.respond(TodoPage(deleted, page.nextPageToken, page.hasMore))
}Filtering happens after the fetch, so a heavily-deleted (or heavily-active) owner's page can shrink
to a handful of items, or none, without hasMore being false — there may be more matching rows on
the next page. A client walking pagination has to keep fetching until it has enough items or
hasMore is false, not stop at the first partially- or fully-filtered page. This app leaves that
loop to the client for now — the same simplification Kandra's own capstone example makes for the
identical problem.
The real timeline — not hand-waved
Say a todo is soft-deleted at day 0:
- Day 0–7: the row is fully intact —
findById(ownerId, createdAt, todoId)returns every field with its real value,isDeleted = true. This is the undo window: the data hasn't gone anywhere, only the marker changed, immediately. - Day 7: the TTL on
title/assigneeId/done/version/updatedAtfires. Those columns don't vanish instantly and cleanly — each becomes, individually, a cell-level tombstone.is_deletedis untouched and still readstrue— its own, much longer TTL (day 7 + 17 more days, by default; see below) hasn't fired yet. - Day 7 → day 24 (
ttlSeconds+ the defaultmarkerTtlSeconds): the data columns' tombstones persist and get read past on any query touching this partition, same as any other TTL'd column —/foundationscovers that mechanism in general.is_deletedstill readstruethroughout this whole window, sofindActive()keeps correctly excluding the row. - Day 24:
is_deleteditself finally expires. Kandra writes that marker as a freshINSERTunder its own TTL (not anUPDATE) specifically so this moment fully retires the row — the originalsave()'sINSERTset a permanent "this partition has a row here" marker of its own, separate from any column, that anUPDATEcan never touch; only a laterINSERTwith a real TTL can supersede it. Past day 24, the partition has no live cells and no live row-marker left at all — it's gone, not a key-plus-marker husk. Nothing this app does, or needs to do, differs from whatdelete()already does on day 0.
Between day 7 and day 24, title/assigneeId/done/version/updatedAt read back as CQL
NULL — at the storage layer, regardless of what type Kandra declared for them. KandraCodec.decode()
checks exactly this case: a NULL column backing a non-nullable Kotlin property throws
KandraQueryException, verbatim: "Column 'title' is NULL in Scylla but property 'title' is non-nullable (kotlin.String). Mark the property nullable or ensure the column always has a value."
A todo soft-deleted for over a week used to hit exactly that the moment any read reached it — findById,
or a findPage scan of that owner's partition that happened to include one. For GET /todos/mine/
GET /todos/trash, a single expired row in a page would break the entire page, not just that row.
Kandra now catches this far earlier: SchemaRegistry.register() rejects a @SoftDelete entity with
any non-key, non-marker property that's non-nullable with no constructor default — at app startup,
before any route runs, naming the property. That's why title above has = "" rather than being a
bare val title: String: without it, this app wouldn't start at all (see
kandra#153). assigneeId is already nullable;
done/version/updatedAt already had defaults.
A default (title: String = "") rather than making title nullable is a real trade-off, not a
free choice — title: String? would be more honest to the data's actual lifecycle (a soft-deleted
todo past day 7 genuinely has no title), but it pushes null-handling into every reader of Todo,
including page 05's and page 06's routes,
which already treat .title as always present. For a field that's only ever read on an
already-isDeleted = true row past its data TTL — exactly the window GET /todos/trash returns —
a default that reads as "no title" is close enough to not be worth the ripple. A field your app
actually displays or acts on after that window would be a better candidate for the nullable route
instead of a default.
This app never calls deleteById (every delete route in this tutorial loads the entity via
findById first, then calls delete(entity)) — worth knowing anyway: KandraRepository.deleteById
(the blocking repository) used to bypass @SoftDelete entirely and hard-delete regardless, a real
bug tracked and fixed as
ISS-015.
Current source confirms the fix: deleteById now looks the entity up first and delegates to the
same soft-delete-aware BatchEngine.delete path every other delete call uses, invalidating the
cache too. If you ever reach for deleteById(ownerId, createdAt, todoId) directly on a @SoftDelete entity
instead of the find-then-delete() pattern this tutorial uses, this is the history of why that used
to be a trap.
Verify the checkpoint: DELETE /todos/{createdAt}/{todoId}, then GET /todos/mine (gone) and GET /todos/trash
(present, with its real title intact) using the same X-User-Id. Nothing in this app builds a
"restore from trash" route — per @SoftDelete's own mechanics, restoring
before the TTL fires would mean rewriting the row with is_deleted = false and fresh values via a
plain save(), which clears the TTL on write; left as an exercise, the same way this tutorial left
authentication out of page 05.
Next: page 09 — a lifetime completion count that has to survive the todo itself being deleted, and stay correct under concurrent writers.