← All posts

Technical tutorial ·

PostgreSQL Constraints and Safe Retries

postgresqlsqlbackenddata-integrity

Disclaimer: The views expressed on this website are my own and do not necessarily reflect the views of Oracle. Nothing published here is written on behalf of, endorsed by, or reviewed by my employer. All technical content is written from public documentation and personal study, and describes general industry practice rather than any specific employer system, configuration, or product plan.

A user clicks Submit, the server creates a record, and the connection drops before the response arrives. The browser retries. Should the application create another record?

This is a different problem from validating a form. The first request may already have succeeded. A backend needs a way to recognize the same operation without assuming every retry is a new action.

This tutorial uses a fictional work-request application to connect three tools: database constraints, an idempotency key, and a conditional state update. Run the SQL in a disposable PostgreSQL database. The examples use features available in PostgreSQL 18.

Put durable invariants in the schema

A work request has an owner, a positive number of units, a state, and a client-generated key that identifies one submission attempt.

CREATE TABLE demo_work_request (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    owner_id bigint NOT NULL,
    idempotency_key text NOT NULL,
    units integer NOT NULL CHECK (units > 0),
    state text NOT NULL DEFAULT 'draft'
        CHECK (state IN ('draft', 'submitted', 'approved', 'rejected')),
    CONSTRAINT demo_owner_request_key
        UNIQUE (owner_id, idempotency_key)
);

The example treats owner_id as an identifier supplied by an authenticated application. A complete schema would normally connect it to a real user table with a foreign key.

Each constraint protects a specific invariant. NOT NULL requires a value, CHECK limits valid values, and the composite UNIQUE prevents the same owner from creating two rows with the same key. A check expression alone does not reject null, which is why the relevant columns also say NOT NULL. These semantics are documented in PostgreSQL's constraints reference.

Application validation still matters: it can give users a useful explanation before a write. The database supplies another enforcement point for imports, scripts, and competing requests.

Why checking first leaves a race

Imagine two workers receiving the same submission:

Worker A: look for the key -> no row found
Worker B: look for the key -> no row found
Worker A: insert a row
Worker B: insert a row

A separate lookup cannot establish uniqueness across both workers. The unique constraint arbitrates the write. This matters even if every individual request handler looks correct when tested alone.

PostgreSQL's default Read Committed isolation gives each statement a snapshot; a transaction is not automatically a global lock around this sequence. Its transaction isolation documentation explains the visibility and conflict behavior.

Let the insert report whether it created anything

INSERT INTO demo_work_request (owner_id, idempotency_key, units)
VALUES (7, 'submission-42', 3)
ON CONFLICT (owner_id, idempotency_key) DO NOTHING
RETURNING id, state;

In a fresh database, this creates a draft and returns its identifier. Run the same statement again: it returns no rows because the unique key already exists. RETURNING reports rows actually inserted or updated, so an empty result is a meaningful branch in the application flow. See the INSERT reference.

After an empty result, retrieve the existing request in a separate statement:

SELECT id, state, units
FROM demo_work_request
WHERE owner_id = 7
  AND idempotency_key = 'submission-42';

At Read Committed, that later statement gets a new snapshot. This avoids assuming that a lookup in the same statement must see the row responsible for a concurrent conflict.

Compare the stored payload with the retried payload. If the same key arrives with a different units value, report a conflict rather than returning success for a different operation. A larger application may store a normalized request fingerprint, the operation type, and the original response.

Scope the key to the authenticated owner and operation. Choose and document a retention policy. This example keeps the row and key together; deleting the row would also remove its duplicate protection.

Make state changes conditional

An ORM call that reads a draft and later writes submitted can encounter a concurrent edit. A conditional SQL update expresses the expected state at the write boundary:

UPDATE demo_work_request
SET state = 'submitted'
WHERE owner_id = 7
  AND idempotency_key = 'submission-42'
  AND state = 'draft'
RETURNING id, state;

Run it twice. The first update changes the draft; the second returns no rows because the record is already submitted.

The application must interpret that empty result. It might be a harmless retry, a stale request, a missing record, or an authorization failure. Do not automatically turn every zero-row update into success. The UPDATE documentation describes the affected-row count and RETURNING behavior.

The state check in the schema only limits the set of labels. It does not enforce the transition graph, the reviewer's role, or separation of duties. Those policies still need explicit enforcement, as shown in the Python workflow tutorial.

Keep related writes in one transaction

If submission also creates an audit record, commit both together:

BEGIN
  conditional update
  if a row changed: insert audit event
COMMIT

An external API call or email is outside that database transaction. For reliable delivery, an application can record an outbound event in the transaction and let a separate worker deliver it with a retry policy. The receiver may need its own idempotency key.

What to verify

A useful integration test should establish that:

The SQL examples above can demonstrate constraints and repeated operations in one session. A concurrency claim needs an additional test with independent database connections and coordinated transactions. Avoid inferring that result from a successful sequential test.

The views expressed on this website are my own and do not necessarily reflect the views of Oracle. Nothing published here is written on behalf of, endorsed by, or reviewed by my employer.