A time-partitioned outbox can't be unique per order, so order state blocks the second credit
A transaction platform I worked on sends credits through a transactional outbox: when SETTLE arrives, the same database transaction writes a credit row to the outbox, and a worker later delivers it to the partner’s wallet. A review in August 2026 found that a retried SETTLE could write a second credit with a new transaction_id. The partner de-duplicates on transaction_id alone, so DUPLICATE_OPERATION would not catch it and one order could be credited twice. A unique key on (order_id, op) would block the second row, but the outbox is partitioned by created_at and PostgreSQL refuses that key.
The fix uses the order’s state machine: SETTLE moves the order from pending to a new settling state, then writes the outbox row in the same transaction if the update changed a row. In a PostgreSQL 17.12 reproduction, two overlapping SETTLE calls that only checked for an existing credit wrote two rows in all three runs. Claiming the order with a compare-and-swap first left one row in each run with the same timing.
The partition key gets in the way
The PostgreSQL documentation requires a unique or primary key constraint on a partitioned table to include every partition key column; the partition key must not contain expressions or function calls. Each partition’s index enforces uniqueness only inside that partition, so uniqueness across partitions has to come from the partitioning scheme itself. Community PostgreSQL has no cross-partition global index in version 18. The designs posted to pgsql-hackers in 2022 and 2025 proposed adding that support.
The reproduction keeps only the columns it needs. The outbox gets a DEFAULT partition so the result doesn’t depend on the date it runs:
-- setup.sql
DROP TABLE IF EXISTS outbox, orders;
CREATE TABLE orders (
order_id text PRIMARY KEY,
state text NOT NULL CHECK (state IN ('pending','settling','settled')));
CREATE TABLE outbox (
order_id text NOT NULL, op text NOT NULL, transaction_id text NOT NULL,
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
) PARTITION BY RANGE (created_at);
CREATE TABLE outbox_default PARTITION OF outbox DEFAULT;
INSERT INTO orders VALUES ('o1', 'pending');
-- unique.sql
ALTER TABLE outbox ADD UNIQUE (order_id, op);
ALTER TABLE outbox ADD UNIQUE (order_id, op, created_at);
INSERT INTO outbox (order_id, op, transaction_id) VALUES ('o1', 'credit', 'tx-1');
INSERT INTO outbox (order_id, op, transaction_id) VALUES ('o1', 'credit', 'tx-2');
SELECT order_id, op, transaction_id FROM outbox;
$ psql -X -q -f setup.sql && psql -X -q -f unique.sql
psql:unique.sql:2: ERROR: unique constraint on partitioned table must include all partitioning columns
DETAIL: UNIQUE constraint on table "outbox" lacks column "created_at" which is part of the partition key.
order_id | op | transaction_id
----------+--------+----------------
o1 | credit | tx-1
o1 | credit | tx-2
(2 rows)
The first constraint is rejected. Adding created_at makes it valid, but different timestamps still allow both credits for the same order.
Check-then-insert lets overlapping retries through
Without the unique key, one option is to check first and skip the insert when the order already has a credit. Under the timing below, INSERT ... WHERE NOT EXISTS can still write a duplicate, just as a SELECT followed by an INSERT in Go can:
-- naive.sql
BEGIN;
INSERT INTO outbox (order_id, op, transaction_id)
SELECT 'o1', 'credit', :'tx'
WHERE NOT EXISTS (SELECT 1 FROM outbox WHERE order_id = 'o1' AND op = 'credit');
UPDATE orders SET state = 'settled' WHERE order_id = 'o1';
SELECT pg_sleep(2);
COMMIT;
#!/bin/sh
# Two SETTLE retries for one order, overlapping: A starts first and holds its
# transaction for 2 s, B starts 0.5 s later with a new transaction_id.
# Timing comes from sleeps only; any psql failure fails the run.
set -eu
psql -X -q -v ON_ERROR_STOP=1 -f setup.sql
psql -X -q -v ON_ERROR_STOP=1 -v tx=tx-1 -f "$1" > /dev/null &
a=$!
(sleep 0.5; psql -X -q -v ON_ERROR_STOP=1 -v tx=tx-2 -f "$1" > /dev/null) &
b=$!
status=0
wait "$a" || status=1
wait "$b" || status=1
[ "$status" -eq 0 ] || exit "$status"
psql -X -q -c "SELECT order_id, op, transaction_id FROM outbox ORDER BY transaction_id"
psql -X -q -c "SELECT order_id, state FROM orders"
$ sh run.sh naive.sql
order_id | op | transaction_id
----------+--------+----------------
o1 | credit | tx-1
o1 | credit | tx-2
(2 rows)
order_id | state
----------+---------
o1 | settled
(1 row)
All three runs produced the same result. Under PostgreSQL’s default READ COMMITTED, B’s NOT EXISTS uses the snapshot from the start of its statement. A’s credit is still uncommitted, so B cannot see it, and no unique constraint prevents the second insert. B’s UPDATE on orders waits for A, but B has already written its credit. The check would catch a retry that began after A committed; it fails with the overlap shown here.
One order settles once, locked on its own row
In the example, orders has order_id as its primary key, with one row per order. The project made a state transition the first step of SETTLE, putting the condition in the UPDATE’s WHERE clause. It writes to the outbox only when that update changes a row:
-- cas.sql
BEGIN;
WITH claimed AS (
UPDATE orders SET state = 'settling'
WHERE order_id = 'o1' AND state = 'pending'
RETURNING order_id)
INSERT INTO outbox (order_id, op, transaction_id)
SELECT order_id, 'credit', :'tx' FROM claimed;
SELECT pg_sleep(2);
COMMIT;
$ sh run.sh cas.sql
order_id | op | transaction_id
----------+--------+----------------
o1 | credit | tx-1
(1 row)
order_id | state
----------+----------
o1 | settling
(1 row)
All three runs left only tx-1. B’s UPDATE waits for A to release the lock on o1. After A commits, B re-evaluates its WHERE clause against the updated row, whose state is now settling. No row matches, so claimed is empty and the INSERT writes nothing, as PostgreSQL documents for UPDATE under READ COMMITTED.
“One live version per game, until two transactions overlap” reproduces a READ COMMITTED problem too. There the condition spans several rows and the waiting statement doesn’t rescan the table; here the check is on a single row, so the re-evaluation is enough to stop the second write.
In the project, SETTLE on an order that is still settling returns OPERATION_PENDING, and on an order already in a final state it returns applied:false with the current state. A retry that arrives after the order is final is not treated as an error.
What it costs
The design depends on code following the state transitions; nothing in the schema limits how many credits an order can have. Every path that writes a credit to the outbox has to pass the compare-and-swap first and commit with the state change. If an order row is ever recreated or set back to pending, the protection is gone. When the worker resends an existing outbox row, it has to keep the same transaction_id so the receiving side can de-duplicate.
An order can also remain in settling when, for example, the credit has been written but can’t be delivered. Every 30 seconds the project’s worker reports how long orders have been in settling. The outbox has an abandoned state for credits confirmed as no longer needing delivery, such as a credit that has not reached the wallet and will not arrive later, allowing a refund instead.
Retries of order creation are a separate problem that this change doesn’t solve. The platform generates order_id, so a client retry that looks like a new order can charge twice; that needs an idempotency key from the client.
Why there is no separate de-duplication table
The most direct alternative is an unpartitioned table keyed on (order_id, op), written in the same transaction as the outbox. The project kept the state machine alone.
“One credit per order” is a property of the order itself, and the state transitions already guard it. The orders table isn’t partitioned and has order_id as its primary key, so a conditional UPDATE under the row lock guarantees a single claim. SETTLE has to update that row anyway; adding the condition to that update enforces one credit per order. A de-duplication table would add a write per order and another index to maintain.
The de-duplication table would need its own retention period, covering the time in which a retry could still arrive, so it can’t simply be detached with old outbox partitions. Purged too early, it lets a late retry through. Stripe’s API v1 documentation says idempotency keys can be removed once they are at least 24 hours old, and a key reused after removal is treated as a new request. Credits need a retention period based on their own retry window.
The state machine distinguishes settling from a final state, so the code can return OPERATION_PENDING and report how long an order has been waiting. A table keyed on (order_id, op) can only say whether a row was written. A path that bypasses either guard and writes directly to the outbox remains unprotected, and an order needing several credits of the same kind would require a different de-duplication key.
Keeping both would leave two records of the same fact to keep in sync; the rule only needs to live in the layer that can actually hold it. Changes to the write paths or crediting rules, or a need to partition and archive orders itself, would be reasons to revisit that choice.
Two other approaches would also stop the second credit, each with its own condition:
- Hash-partition the outbox on order_id. In the same container,
UNIQUE (order_id, op)is accepted and the second insert fails on a duplicate key, but the outbox can no longer be partitioned by time and old data can’t be dropped a month at a time. - Take an advisory lock on order_id, run the check as a fresh READ COMMITTED statement after acquiring it, and hold the lock until the writing transaction ends. Only code paths that follow the same locking rule are protected.
Retries of payments in general are covered in “The Same Payment Sent Twice: Idempotency and Retries, by Way of Santander’s Christmas”.
Notes
- The partner de-duplicates on transaction_id, so a SETTLE retry with a new transaction_id gets past DUPLICATE_OPERATION.
- With the outbox partitioned by created_at, PostgreSQL requires any unique key to include the partition key; (order_id, op) is rejected, and adding created_at still lets retries with different timestamps in.
- Check-then-insert under READ COMMITTED can let two overlapping retries both write; the minimal reproduction wrote two credits in three runs out of three.
- Claiming settling with a compare-and-swap and inserting the outbox row in the same transaction left one credit in every run; the second UPDATE matched no row.
- No separate de-duplication table: the rule already sits on the unpartitioned order row, and a second table would add a write and need its own retention period.
- Every write path has to respect the state transitions, and orders stuck in settling need monitoring and follow-up.
Further reading
- PostgreSQL, “Table partitioning”: official documentation; the declarative partitioning limitations say unique and primary key constraints must include the partition key.
- PostgreSQL, “Transaction isolation”: official documentation on how an UPDATE under READ COMMITTED re-evaluates its WHERE clause after waiting.
- Dilip Kumar, “Proposal: Global Index for PostgreSQL”: a 2025 pgsql-hackers mailing-list proposal for cross-partition unique indexes.
- Chris Richardson, “Pattern: Transactional outbox”: pattern write-up on microservices.io, noting that the relay can publish a message more than once and consumers must be idempotent.
- Stripe, “Idempotent requests”: official API documentation; API v1 idempotency keys can be removed once at least 24 hours old.
- Wikipedia, “Compare-and-swap”: encyclopaedia entry on the atomic write that applies only if the current value matches.
Ideas and technical judgement by Sheng; drafted with Claude · Examples run on PostgreSQL 17.12 in an OrbStack container on a Mac.