> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cockroachlabs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Make writes idempotent with ON CONFLICT

> Use an idempotency key so a retried request records a payment and debits an account exactly once, in one SQL statement.

> [!NOTE]
>
> **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`)](https://docs.cockroachlabs.com/docs/stable/transaction-retry-error-reference). Without an idempotency key, each retry risks charging the customer twice.

## Start a cluster

> [tab] Cockroach Continuum
>
> Create a free cluster by following the [Continuum quickstart](https://docs.cockroachlabs.com/docs/continuum/tutorial-quickstart.md), then open a SQL shell with the connection string from the Console.

> [tab] Local (self-hosted)
>
> [Install CockroachDB](https://docs.cockroachlabs.com/docs/stable/install-cockroachdb-mac.md), then start a temporary in-memory cluster with a SQL shell:
>
> ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> cockroach demo --no-example-database
> ```

## Create the schema

The idempotency key is the primary key of `payments`, so the database itself enforces "one payment per key". The `CHECK` constraint on `accounts` stops an overdraft.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
CREATE TABLE accounts (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  balance DECIMAL(12,2) NOT NULL CHECK (balance >= 0)
);

CREATE TABLE payments (
  idempotency_key STRING PRIMARY KEY,
  account_id UUID NOT NULL REFERENCES accounts (id),
  amount DECIMAL(12,2) NOT NULL CHECK (amount > 0),
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

INSERT INTO accounts (id, balance)
  VALUES ('7f1c2a3e-0000-4000-8000-000000000001', 100.00);
```

## The pattern

Claim the key and apply the debit in a single statement:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
WITH ins AS (
  INSERT INTO payments (idempotency_key, account_id, amount)
  VALUES ('order-4521-charge', '7f1c2a3e-0000-4000-8000-000000000001', 25.00)
  ON CONFLICT (idempotency_key) DO NOTHING
  RETURNING account_id, amount
)
UPDATE accounts SET balance = accounts.balance - ins.amount
FROM ins
WHERE accounts.id = ins.account_id
RETURNING accounts.balance;
```

How it works:

1. [`INSERT ... ON CONFLICT DO NOTHING`](https://docs.cockroachlabs.com/docs/stable/insert#on-conflict-clause) claims the key. `RETURNING` produces a row only if the insert happened.
2. `UPDATE ... FROM ins` debits the account only when the insert returned a row.
3. 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

| Request | Result |
| - | - |
| First request with `order-4521-charge` | Returns `balance = 75.00`. One payment row is recorded |
| Retry with the same key | `UPDATE 0`. No new payment, balance stays `75.00` |
| A new key for `500.00` | Fails with `failed to satisfy CHECK constraint (balance >= 0:::DECIMAL)`. No payment row is written, so the key is not used up |
| 8 concurrent requests with the same new key | Exactly one debit; the other 7 return `UPDATE 0` |

In your application, treat "no row returned" as "this request already ran". Read the stored payment and return it to the caller:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
SELECT idempotency_key, amount, created_at
FROM payments
WHERE idempotency_key = 'order-4521-charge';
```

## How it fails

| Situation | What happens | What the client does |
| - | - | - |
| The response is lost and the client retries | The key already exists, so nothing changes | Return the stored payment |
| Two requests with the same key arrive at once | One commits. The other waits, then finds the key and does nothing. Under heavy contention it may get `40001` instead | Retry on `40001`. The key makes the retry a no-op |
| A node fails mid-request and the client gets `result is ambiguous` (`40003`) | The statement either committed or it didn't | Retry with the same key. [Idempotent statements are safe to retry](https://docs.cockroachlabs.com/docs/stable/common-errors.md#result-is-ambiguous) |
| Insufficient balance | The `CHECK` fails and the whole statement rolls back, including the payment row | Report the error. The same key can be used again later |

## Trade-offs and when not to use it

* **Same key, different request.** `DO NOTHING` silently 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](https://docs.cockroachlabs.com/docs/stable/row-level-ttl.md) 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](https://docs.cockroachlabs.com/docs/stable/understand-hotspots.md).
* **Multi-statement work.** If the business operation spans several statements, run them in one explicit transaction with a [client-side retry loop](https://docs.cockroachlabs.com/docs/stable/advanced-client-side-transaction-retries.md), and claim the key first.

## Give it to your agent

```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
Make this write idempotent on CockroachDB. Add a payments table whose primary key
is the client's idempotency key. In one statement, INSERT ... ON CONFLICT
(idempotency_key) DO NOTHING RETURNING the row, and apply side effects with
UPDATE ... FROM that CTE. If no row comes back, read and return the stored payment.
Retry on SQLSTATE 40001 and 40003 with the same key.
Reference: https://docs.cockroachlabs.com/docs/cookbook/idempotent-writes
```

## Go deeper

* [`INSERT ... ON CONFLICT`](https://docs.cockroachlabs.com/docs/stable/insert#on-conflict-clause) and [`INSERT ON CONFLICT` vs. `UPSERT`](https://docs.cockroachlabs.com/docs/stable/insert#insert-on-conflict-vs-upsert)
* [Transaction retry error reference](https://docs.cockroachlabs.com/docs/stable/transaction-retry-error-reference.md)
* [Client-side transaction retries](https://docs.cockroachlabs.com/docs/stable/advanced-client-side-transaction-retries.md)
* Idempotency keys also guard the [Order management](https://docs.cockroachlabs.com/docs/cookbook/order-management.md) and [Payments ledger](https://docs.cockroachlabs.com/docs/cookbook/payments-ledger.md) Blueprints

> [card] [Practice transactions in Cockroach University](https://learn.cockroachlabs.com/?utm_source=docs\&utm_medium=recipe\&utm_content=idempotent-writes)
>
> Free developer path with hands-on browser labs.
