Problem Statement
You need exactly-once effects for payment writes over flaky networks. Outline a database pattern that achieves safe retries.
Explanation
Use idempotency keys stored with a unique constraint. The client sends a stable key per logical operation. Wrap the insert or update in a transaction that first checks or inserts the key row. If the same key arrives again, the unique constraint forces an upsert path that returns the original result without applying the effect twice.
Pair this with atomic upserts on balances or ledger entries and commit once. Keep the key TTL long enough to cover realistic retry windows.
Code Solution
SolutionRead Only
INSERT INTO idempotency_keys(key, result_hash) VALUES(:k, :h) ON CONFLICT (key) DO NOTHING; -- proceed only once; fetch prior result when conflict occurs
Practice Sets
This question appears in the following practice sets:
