PG to PG: Add ORDER BY in MERGE to handle non-PK unique columns#4169
Merged
Conversation
serprex
approved these changes
Apr 13, 2026
heavycrystal
approved these changes
Apr 13, 2026
Contributor
|
Have we measured perf impact for large batch sizes? |
Contributor
Author
For large batch sizes the bottleneck will be the CTE taking too much memory or the MERGE I/O. Even for 10 million unique pkeys in a batch the sort itself shouldn't take more than a second Definitely worth the R&D there though |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem statement
Consider a Postgres table such with
idPRIMARY KEY andemailTEXT with a UNIQUE constraint on it. Let's say there is a mirror of this table to another PG database, and the following changes are made on source:This can result in a unique constraint violation error in normalize:
This is because MERGE in Postgres processes rows in non-deterministic fashion, therefore across PKeys we could attempt replicating the INSERT first before DELETE (note: for rows pertaining to the same PKey this is not possible as we rank there), resulting in us hitting a non-PK unique constraint.
Fix
According to Postgres docs for MERGE, it says:
We are already using the
source_querysyntax in our MERGE. This PR adds an ORDER BY to our subquery which sorts by_peerdb_timestampwhich is representative of WAL order, thereby not running into this issue.