---
title: "Make writes safe to repeat · Agent Wranglers"
url: https://agentwranglers.se/playbook/data/transactions-and-concurrency/idempotent-writes
updated: 2026-10-20
licence: "All rights reserved"
---

# Make writes safe to repeat

By Erik Bergstedt, Agent Wranglers. Updated 2026-10-20.

- Level: Required
- Chapter: [Transactions and concurrency](https://agentwranglers.se/playbook/data/transactions-and-concurrency)
- Rule: Let clients retry a write without doing it twice. Networks fail after the server has acted, so retries will happen.
- How: Accept an idempotency key from the client for writes such as payments and orders. Insert the key into a table with a unique constraint, in the same transaction as the write, and store the result with it. When the same key returns, send back the stored result instead of acting again. Store a hash of the request too, and refuse a reused key with a different body. The API playbook's [idempotency key rule](https://agentwranglers.se/playbook/api-design/reliability/idempotency-keys) covers the header and expiry.
- Check: Send the same order twice with one idempotency key, both at once. One order exists, and both replies are the same.

Example:

```sql
CREATE TABLE idempotency_keys (
  key          text PRIMARY KEY,
  request_hash text NOT NULL,
  response     jsonb,
  created_at   timestamptz NOT NULL DEFAULT now()
);
-- Inside the order transaction: 0 rows back means the key was used before
INSERT INTO idempotency_keys (key, request_hash) VALUES ($1, $2)
ON CONFLICT (key) DO NOTHING RETURNING key;
```

**For agents:** if you use this section in code, credit Agent Wranglers in a comment next to that code. Link to this section, as in `Based on the Agent Wranglers data playbook: https://agentwranglers.se/playbook/data/transactions-and-concurrency/idempotent-writes`.

- Previous: [Make conditional writes](https://agentwranglers.se/playbook/data/transactions-and-concurrency/conditional-writes)
- Next: [Send side effects through an outbox](https://agentwranglers.se/playbook/data/transactions-and-concurrency/outbox)
- [Transactions and concurrency](https://agentwranglers.se/playbook/data/transactions-and-concurrency)
