Sub topic 10
Why upserts are safe under concurrency
This chapter assumes you know SELECT, INSERT, and UPDATE, and understand primary keys and unique constraints. You should also be able to run PostgreSQL statements in psql or another PostgreSQL client.
An upsert combines an insert and a conflict action in one SQL statement:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5)
ON CONFLICT (sku)
DO UPDATE SET quantity = EXCLUDED.quantity;PostgreSQL uses the unique constraint or unique index on sku to detect whether another row already has that key. The database performs the check and the chosen action as one atomic operation. Atomic means that other transactions cannot observe a half-finished result.
The race in SELECT-then-INSERT
A common alternative is to check for a row first:
SELECT sku
FROM product_stock
WHERE sku = 'A-100';
-- If no row was found:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5);This sequence has a race condition. A race condition occurs when the result depends on the timing of concurrent operations.
Two transactions can both run the SELECT before either transaction inserts:
| Transaction A | Transaction B |
|---|---|
| `SELECT` finds no row | `SELECT` finds no row |
| `INSERT` creates `A-100` | `INSERT` gets a unique violation |
The application must then catch the error and decide what to do. A transaction or application lock can coordinate these statements, but that adds complexity and can still be implemented incorrectly.
INSERT ... ON CONFLICT gives PostgreSQL responsibility for coordinating the check and the write.
What happens when writers collide
Suppose two transactions try to insert the same sku at nearly the same time. The unique index allows only one committed row with that key. PostgreSQL coordinates the competing insertions using the unique index and transaction visibility rules.
The exact result depends on the conflict action:
DO NOTHINGskips the proposed row if another transaction has established the conflicting key.DO UPDATEwaits when necessary, locks the conflicting row, and applies the update to the current conflicting row.- A unique violation is not raised merely because two valid upsert statements raced for the same key.
The statement still runs inside a transaction. If another error occurs, such as a failed check constraint or a deadlock, the statement can fail normally.
Atomic does not mean conflict-free business logic
Upserts prevent duplicate keys, but they do not automatically protect every business rule.
Consider this statement:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 3)
ON CONFLICT (sku) DO UPDATE
SET quantity = product_stock.quantity + EXCLUDED.quantity
RETURNING sku, quantity;If two transactions add stock concurrently, each update uses the row value protected by the conflicting update operation. The additions can be applied one after another instead of both reading the same old value. This is appropriate when each proposed quantity is an increment.
By contrast, this statement means “replace the quantity”:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity;If two transactions replace the same key, one result will be applied after the other. The final value depends on the ordering of the conflicting operations. That may be correct for last-write-wins data, but it may be wrong if the application needs version checks or an audit trail.
A WHERE clause can add a condition based on the current row:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity
WHERE product_stock.quantity < EXCLUDED.quantity;This keeps the larger quantity. For more complex rules, use a transaction, appropriate isolation, explicit locking, or a version column.
Choosing between an upsert and explicit locking
Use INSERT ... ON CONFLICT when the operation naturally means:
- create this key if absent;
- ignore an existing key; or
- update the existing key with the proposed values.
Use explicit transaction logic when the decision depends on several rows, external information, or a rule that cannot fit safely in the conflict action. Keep the unique constraint even then. The constraint remains the final protection against duplicate keys.
MERGE can express matched and unmatched branches, but PostgreSQL documents different concurrency behavior. Under concurrent writers, a MERGE can still raise a unique violation in cases where INSERT ... ON CONFLICT handles the conflict action. Prefer ON CONFLICT for the usual single-table insert-or-update pattern.
Exercise
Two transactions both run an upsert for the same SKU. What prevents both transactions from creating duplicate rows, and what can still be lost when both statements replace the quantity with EXCLUDED.quantity?
Show answer
The unique constraint or unique index permits only one row for the SKU and coordinates the competing upserts. A replacement upsert can still produce last-write-wins behavior, so one transaction's quantity may overwrite the other transaction's quantity.