How do you enforce idempotency at the database level in SQL?
Topic: microservices, SQL Side. Level: Intermediate.
Answer
Store an **idempotency key** with a unique constraint so a retried request can't create duplicate side-effects. On the first call you insert the key (and result); a retry hits the unique violation and you return the stored result instead of re-executing. This makes at-least-once delivery / client retries safe for non-idempotent operations like payments.
```sql
CREATE TABLE processed_requests (
idempotency_key TEXT PRIMARY KEY, -- client-supplied, unique
response JSONB NOT NULL,
created_at TIMESTAMPTZ DEFAULT now()
);
-- First call inserts; a retry conflicts and returns the SAME response.
INSERT INTO processed_requests (idempotency_key, response)
VALUES ($1, $2)
ON CONFLICT (idempotency_key) DO NOTHING
RETURNING response; -- empty rowset => already processed, fetch stored response
```