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

Spring Data Cassandra conditional insert: reserve one key once

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

An IF NOT EXISTS write can reject a competing reservation for the same Cassandra primary key.

A read is not a reservation

Two dispatch workers ask whether parcel P-47 already has an active route claim. Both can read no row and then write. A regular Cassandra INSERT is an upsert, so one claim can replace the other. A conditional INSERT with IF NOT EXISTS makes the database decide which write applied. Spring Data Cassandra exposes this through InsertOptions. This is a lightweight transaction, with more coordination than an ordinary write. Tenant-scoped idempotency must still be modeled in the key.

Use the result as the decision

Do not return success merely because the CQL request completed without a driver exception. Inspect the applied result, then return either the accepted reservation or a conflict with the existing owner. A retry after a timeout is ambiguous until the caller reads the key or repeats an idempotent command. Keep the reservation row narrow and choose a partition key that does not send every tenant's claims to one hot partition.

Race two callers

Start both requests at the same barrier with different worker IDs. Exactly one must report an applied write; the stored row must name that winner. Then drop the response after commit and retry the same command ID to test how the API resolves an unknown outcome. A repository mock cannot establish this behavior.

Implementation sketch

cql
INSERT INTO route_claims (tenant_id, parcel_id, worker_id, claim_id)
VALUES ('north-47', 'P-47', 'worker-21', 'claim-81')
IF NOT EXISTS;

Cost and verification

A conditional write coordinates replicas and costs more latency than a normal upsert. Use it for a specific uniqueness invariant, not every telemetry event.

Common Mistakes

  • Do not use read-then-insert as the uniqueness guarantee.
  • Do not equate a completed conditional request with an applied mutation.
  • Do not retry a timed-out claim under a new command ID without checking the first outcome.

Read next

Spring Data Cassandra partition keys: model the read before the row, Spring Data Cassandra @Version: a conflict is not a merge, Spring POST idempotency keys: bind replay to tenant and command.

spring
spring-boot
data-transactions
cassandra-conditional-reservation
Storage details