SQLSTATE and retries
Overview
PostgreSQL reports five-character SQLSTATE codes. 40001 is serialization failure, 40P01 is deadlock, 23505 is unique violation and 23503 is foreign-key violation. SQLite exposes its own error codes, not PostgreSQL SQLSTATE. Classify errors using the actual driver, not localized message text.
First example
BEGIN;INSERT INTO ai_purchase VALUES(4,1,1250,'req-1') ON CONFLICT(request_id) DO NOTHING;SELECT changes();ROLLBACK;Observed SQLite result (rows in JSON):
[ [ 0 ]]How it works
Retry the entire failed transaction for known retryable concurrency failures, with bounded attempts, backoff and jitter. Recompute decisions from fresh reads. Most constraint errors require correction, not blind retry; rare concurrency-dependent unique failures need explicit reasoning. A lost commit response has ambiguous outcome: use an idempotency key and reconcile rather than blindly replaying. Below ON CONFLICT illustrates duplicate request handling; the host model checks payload equality.
Practical example
SELECT account_id,cents FROM ai_purchase WHERE request_id='req-1';Observed SQLite result (rows in JSON):
[ [ 1, 1250 ]]Practice and mistakes
Practice: classify 40001, 40P01 and 23505; retry only the first two by default. Hint: rollback first and bound attempts. Check duplicate request with different payload is rejected. Mistake: retry every exception forever.
PostgreSQL 17 example — NOT RUN
SELECT 1/0;Expected result, not executed: "SQLSTATE 22012 (division by zero); not a retryable concurrency failure."