Recipe · 15 minutes · Works on: Cockroach Continuum, CockroachDB Cloud, self-hosted · Verified on: CockroachDB v26.4.1, Dec 1, 2026
What you’ll build
A payment write that is safe to retry. The client sends an idempotency key with each request. The first request records the payment and debits the account in one statement. Any retry with the same key changes nothing. Retries are normal in a distributed application. Networks drop responses, clients and agents resend requests, and CockroachDB asks clients to retry transactions that fail with a serialization error (40001). Without an idempotency key, each retry risks charging the customer twice.
Start a cluster
- Cockroach Continuum
- Local (self-hosted)
Create a free cluster by following the Continuum quickstart, then open a SQL shell with the connection string from the Console.
Create the schema
The idempotency key is the primary key ofpayments, so the database itself enforces “one payment per key”. The CHECK constraint on accounts stops an overdraft.
The pattern
Claim the key and apply the debit in a single statement:INSERT ... ON CONFLICT DO NOTHINGclaims the key.RETURNINGproduces a row only if the insert happened.UPDATE ... FROM insdebits the account only when the insert returned a row.- The whole thing is one statement, so it runs as one implicit transaction. The payment and the debit commit together or not at all.
Run it
In your application, treat “no row returned” as “this request already ran”. Read the stored payment and return it to the caller:
How it fails
Trade-offs and when not to use it
- Same key, different request.
DO NOTHINGsilently ignores a retry that carries a different amount. If clients might reuse keys by mistake, store a hash of the request with the key and reject mismatches. - The key table grows forever. If the payments themselves must be kept, store keys in their own table and expire them with row-level TTL once your retry window has passed.
- Choose keys that spread out. Client-generated UUIDs or opaque request IDs distribute writes across the cluster. Sequential keys concentrate them in one range. See Understand hotspots.
- Multi-statement work. If the business operation spans several statements, run them in one explicit transaction with a client-side retry loop, and claim the key first.
Give it to your agent
Go deeper
INSERT ... ON CONFLICTandINSERT ON CONFLICTvs.UPSERT- Transaction retry error reference
- Client-side transaction retries
- Idempotency keys also guard the Order management and Payments ledger Blueprints
Practice transactions in Cockroach University
Free developer path with hands-on browser labs.

