Skip to content

Idempotent inserts in PostgreSQL

Two matching stamped slips sit above one cardboard package.

Too long, didn’t read

A pickup can already be queued when the app gives up waiting for a reply. Give the first request and its retry the same key. Postgres can then keep one job, and the app can look up its number if it needs to reply.

The app sends 103 again

An operator scans the box for order 103. The app asks Postgres to queue its pickup. Suppose Postgres commits and the connection drops before the reply reaches the app. The app owes the operator an answer, so it sends the request again.

Illustrative timeout. The app requests a pickup for order 103. Postgres commits the job, the reply is lost, and the app retries order 103.

One scan was plenty. The warehouse still has two requests for the same pickup. What does Postgres make of the second one?

Which job numbers come back?

In a scratch database on PostgreSQL 18.7, the app ran the same insert twice. Each attempt committed before the next. The second run started with an empty queue again, this time with a rule to keep one row per order and job kind.

Observed results Two attempts for order 103
Queue rule First returnRetry return
Unique job number 1 2
Unique order and kind 1 No row

In the first run, the primary key checked each new job number. Both numbers were unique and both jobs said “pick up order 103.”

In the second run, the unique constraint made (103, pickup) the same key for both attempts. The app asked Postgres to skip a conflicting insert with ON CONFLICT DO NOTHING. A separate read found one job for that key, job 1. PostgreSQL constraints · PostgreSQL INSERT

INSERT INTO pickup_jobs (order_id, kind)
VALUES (103, 'pickup')
ON CONFLICT (order_id, kind) DO NOTHING
RETURNING id;

What if the first request is still open?

This time the first connection inserts the pickup and leaves its transaction open. Both connections use Read Committed, PostgreSQL’s default isolation level. Before the first commit, compare two things the second connection could try.

  • Can I read the job? The statement sees what was committed when it started. The first insert is still invisible to that read.
  • Can I insert the same key? Postgres checks the unique constraint. The insert can wait for the first transaction to finish.
Predicted with two connections The retry is waiting on the key
First transaction Retry gets
Commits No row
Rolls back Its own job number

This follows from the uniqueness check and the isolation rules. The scratch run sent its two inserts in sequence. PostgreSQL uniqueness checks · Read Committed isolation

What can the app tell the operator?

RETURNING id reports what this insert added. A skipped insert leaves the app with a blank result and an operator who may still need a job number. While the original row is still there, the reply depends on what the caller needs.

  • Confirmation that a job exists. The app can report that the pickup has been queued.
  • The original job number. The app looks up the same key in a new statement. At Read Committed, that read gets a fresh snapshot and can find the earlier job.

PostgreSQL INSERT · Read Committed isolation

Make the key fit what the app calls a retry. If order 103 later needs a different pickup, give that dispatch its own identity. If the same key can arrive with a different address, decide what the app should return. In a queue that stores addresses, the skipped insert leaves the first address alone.

If you delete the original key, the next retry can queue another job for 103. Keep the row for as long as the app accepts retries. If the queue deletes old jobs, have the enqueue path check a separate record of the key and its original job number.

Replay the two insert attempts

Use a fresh scratch database. In psql, leave autocommit enabled.

CREATE TABLE pickup_jobs (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  order_id bigint NOT NULL,
  kind text NOT NULL
);

Run this plain insert twice. It returns job numbers 1 and 2.

INSERT INTO pickup_jobs (order_id, kind)
VALUES (103, 'pickup')
RETURNING id;

Run the reset and add the unique constraint. The reset clears only the scratch queue and restarts job numbering. Resolve any existing duplicates before adding the constraint to a real queue.

TRUNCATE pickup_jobs RESTART IDENTITY;

ALTER TABLE pickup_jobs
  ADD CONSTRAINT one_pickup_per_kind UNIQUE (order_id, kind);

Run the guarded insert twice. It returns 1, then no rows. Query SELECT id, order_id, kind FROM pickup_jobs; to see the single retained job for order 103.