Two requests can both observe that a row is absent and then compete to create it. A pre-insert existence check does not decide the winner or define what the second caller should receive. Put the identity rule in the database and choose the conflict outcome from the business meaning of the operation.
In PostgreSQL 18, a tenant-scoped external reference can be inserted, accepted unchanged on an identical duplicate, or rejected when its immutable payload differs. Work backward from those caller outcomes to the unique constraint and conflict action. Authorization and any external side effects still need their own protocol.
Define what makes two records the same
Write the logical identity before choosing an index. In the synthetic service, an external reference is unique within a tenant. The same external reference may legitimately exist in a different tenant. A global uniqueness rule would encode the wrong business boundary.
Decide how case, whitespace, missing values, and normalization affect identity. The application validator and database constraint must agree. If one path normalizes an external reference and another stores its original representation, callers can receive inconsistent duplicate behavior.
The PostgreSQL constraint documentation describes the database mechanisms available for uniqueness. Select the mechanism that actually represents the rule, including the treatment of nulls and any partial condition. Avoid replacing a database constraint with an application-only check that races with another writer.
Review the migration separately. Existing duplicates or a newly broadened tenant boundary can make adding the rule fail. Inspect and resolve those records through an owned data-change process before relying on the new constraint in request handling.
Choose the meaning of a conflict
An attempted duplicate can mean rejection, acceptance of an already-existing resource, or an authorized update. Those outcomes are different API contracts. Choose deliberately instead of adopting the shortest upsert statement offered by an ORM.
The PostgreSQL insert reference documents ON CONFLICT DO NOTHING and ON CONFLICT DO UPDATE. It also describes how the conflict target selects the relevant uniqueness mechanism. Use that target to express the intended conflict rather than swallowing every uniqueness failure without explanation.
For the synthetic reference record, an existing row owned by the same tenant might be returned unchanged. A differing immutable payload might instead require a conflict response. An update path should specify which mutable fields the caller may replace and which fields preserve server-owned state.
Avoid an update performed solely to obtain a return value unless its write behavior is acceptable. Triggers, audit events, modification timestamps, and contention can make an apparently harmless update observable. Review those effects as part of the chosen operation, not as incidental implementation detail.
Follow an ignored insert through the duplicate lookup
Work through a tenant-scoped mapping whose identity is (tenant_id, external_ref). For this example, both fields are non-null, the pair has a unique constraint, and payload_hash represents an immutable, server-calculated payload fingerprint. These SQL fragments illustrate the statement contract for PostgreSQL 18; they assume that schema and bound parameters rather than defining a complete API:
INSERT INTO external_records (tenant_id, external_ref, payload_hash)
VALUES ($1, $2, $3)
ON CONFLICT (tenant_id, external_ref) DO NOTHING
RETURNING id, payload_hash;
The tenant parameter must come from the caller's authorized server context. The other values must be validated and bound through the driver. A returned row means this statement inserted it. An empty result means the statement did not insert a row; it does not establish that the existing payload matches the request.
If the contract accepts identical duplicates, the conflict path needs an explicit lookup:
SELECT id, payload_hash
FROM external_records
WHERE tenant_id = $1 AND external_ref = $2;
Compare the stored immutable fingerprint with the validated request fingerprint. A match can return the existing identity under the documented API contract; a mismatch should return a stable conflict response. If deletion or identity reuse is allowed, define what an empty follow-up read means and bound any retry. Do not silently turn that case into a successful duplicate response.
There is a snapshot trap here. At Read Committed, an insert can wait on another transaction's unique-key conflict and then do nothing even though the conflicting row was not visible to the insert statement's snapshot. A separate follow-up statement can receive a newer snapshot. Combining insertion and fallback selection into one statement does not automatically provide that newer view. The PostgreSQL isolation reference describes this conflict visibility behavior. Choose the transaction protocol before replacing the two steps with a clever-looking single query.
Define what the caller receives for an insertion, an accepted duplicate, and a rejected mismatch. Do not infer that a returned empty row set means an internal error. The insert reference explains that RETURNING reports rows actually inserted or updated; an ignored conflict is a distinct result to handle.
If the contract requires returning an existing row after an ignored insertion, design the read and its transaction scope explicitly. Consider a concurrent transaction that creates, updates, or deletes that row around the conflict. The follow-up lookup needs an understood consistency and retry policy.
Keep client behavior aligned with the outcome. A create form should not announce a newly created resource when the server accepted an existing one. A background synchronization job should distinguish an unchanged record from a mutable update if downstream processing depends on that difference.
Use stable public errors for conflicts that cannot be accepted. Keep raw constraint names, SQL text, and storage details out of the client response. Preserve a sanitized internal classification so operators can distinguish a business duplicate from an unexpected uniqueness violation.
For an intentional DO UPDATE, make its predicate and assignments part of the contract too. A condition can reject an update after the conflicting row is found and locked; that row is then absent from RETURNING. An empty result is therefore not a universal “already exists” signal across all upsert forms. Do not detect insert versus update by inspecting undocumented system-column tricks when the API can model the needed outcome directly.
Preserve authorization through the update path
Derive tenant scope from authenticated, authorized server context. Do not let the request choose a conflicting tenant identifier and then rely on the upsert to find a record. Check both access to the logical object and permission to change each requested property.
Review ORM-generated conflict updates carefully. A broad mapping from request fields to update fields can overwrite ownership, immutable references, or internal status. Define a narrow update shape with validated values and preserve fields outside the caller's authority.
For a synthetic membership change, creation and update can have different permission requirements. A caller authorized to create a new mapping is not necessarily authorized to replace an existing one. Evaluate the conflict path under its own authorization rule.
The object authorization guide provides a related access matrix. Apply it to insert success, conflict acceptance, and update behavior so a duplicate request cannot become a route around ownership checks.
Test simultaneous callers and ambiguous completion
Use independent database sessions to submit the same logical identity concurrently. Assert the number of committed rows, the preserved ownership fields, and each caller's documented outcome. Include different tenants with the same external reference to verify the intended uniqueness boundary.
Test identical duplicate payloads and conflicting payloads separately. Add a concurrent deletion if the service permits it. These schedules expose assumptions hidden by a sequential test that creates the row and only afterward sends the duplicate.
Finally, simulate a lost acknowledgment after commit at the application boundary. A caller may retry without knowing whether creation succeeded. Row uniqueness alone does not tell the service whether to repeat an associated notification or external action. Use the idempotent operation guide for that broader request contract.
Keep the resulting test cases attached to the API contract: first insert, identical duplicate, differing payload, same external reference in another tenant, simultaneous callers, and deletion during the fallback read. Each needs a defined row count, returned identity or error, and side-effect outcome. Those observations make the chosen SQL behavior reviewable when an ORM or transaction wrapper changes.
Was this guide useful?
Your rating helps us prioritize clearer, more practical technical content.
Review diffs, run checks, and prepare the release in Arezgit.
Keep Git review, security scanning, API checks, database inspection, and release preparation together in one local desktop application.
Explore Arezgit