Account merging: safely deduplicating users who signed up twice
A user signs up with their email and a password in March. In July they come back, click "Sign in with Google," and because that Google account uses the same email, your system either creates a second account or, worse, silently logs them into a different one. Now there are two identities for one human: two sets of data, two billing relationships, two support histories. Account merging is how you put them back together, and it is one of the few auth operations where a mistake can both lose data and leak it.
The reason this is genuinely hard is that a merge is a destructive, cross-cutting operation. You are reconciling authentication methods, re-parenting application data across every table that references a user, and collapsing sessions, all while making sure you never fuse two accounts that belong to different people.
Prevent first: link instead of duplicating
The cheapest merge is the one you never have to do. When a user authenticates through a new method, check whether a verified identifier already matches an existing account, and if it does, offer to link the new method rather than minting a second account.
async function onOAuthCallback(profile: OAuthProfile) {
// Only trust the email if the provider says it is verified.
if (!profile.emailVerified) return startManualSignup(profile);
const existing = await findUserByVerifiedEmail(profile.email);
if (existing) {
// Do NOT auto-link silently. Prove control of the existing account first.
return promptLinkFlow(existing, profile); // user confirms via password/passkey
}
return createUserWithIdentity(profile);
}
The model that makes this clean is separating users from identities. One user row owns many identity rows (a password, a Google link, a passkey, a SAML subject). Linking is then just attaching another identity to the existing user, no data to move at all.
CREATE TABLE identities (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
provider TEXT NOT NULL, -- "password", "google", "passkey", "saml:acme"
subject TEXT NOT NULL, -- provider's stable user id
email CITEXT,
verified BOOLEAN NOT NULL DEFAULT false,
linked_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (provider, subject)
);
Gotcha: never auto-merge on an unverified email. If you link a Google login to an existing account just because the email strings match, an attacker can register an OAuth identity with a victim's email at a sloppy provider and walk straight into the victim's account. The email must be provider-verified, and the user should still prove control of the existing account before linking.
When you must merge two real accounts
Prevention fails sometimes, and you end up with two accounts that are genuinely the same person. A true merge has to designate a surviving account (the primary) and fold the other (the secondary) into it. The order of operations matters because the operation must be atomic: a half-finished merge that moved some data but not the login leaves a user worse off than two clean duplicates.
1. Verify the human owns both
Require the user to authenticate into both accounts, or to prove control of a verified identifier on each, before anything moves. A merge is irreversible enough that it deserves the same scrutiny as account deletion.
2. Decide survivorship and conflict rules
Pick the primary deterministically (often the older account, or the one with billing) and define how conflicts resolve: which display name wins, how you combine roles and permissions (union, not the weaker set, unless that is a security concern), what happens to two active subscriptions.
3. Re-parent data in one transaction
Move every row that references the secondary user to the primary, then retire the secondary.
BEGIN;
-- Re-point owned data. Repeat for every table keyed on user_id.
UPDATE projects SET user_id = $primary WHERE user_id = $secondary;
UPDATE audit_events SET user_id = $primary WHERE user_id = $secondary;
UPDATE identities SET user_id = $primary WHERE user_id = $secondary;
-- Resolve unique-constraint collisions explicitly, do not let them abort blindly.
-- e.g. two memberships in the same org: keep the higher role, drop the dupe.
-- Revoke the secondary's sessions and tombstone it rather than hard-deleting.
UPDATE sessions SET revoked_at = now() WHERE user_id = $secondary;
UPDATE users SET merged_into = $primary, status = 'merged', merged_at = now()
WHERE id = $secondary;
COMMIT;
Tombstone, do not delete. Keep the secondary account as a redirect record (merged_into) instead of removing the row. Old links, foreign keys you missed, and support lookups all still resolve, and you retain an audit trail of exactly what was merged and when. A hard delete turns a stray reference into a dangling pointer.
Sessions, caches, and the moment of cutover
At the instant the merge commits, every session on the secondary account must be revoked and the user re-pointed to the primary. If the user was signed into both, revoke and reissue so there is no window where a token still resolves to the retired account. Invalidate any cached user lookups keyed on the secondary ID, and make sure background jobs already enqueued against the secondary either follow the redirect or are re-targeted.
- Revoke all secondary sessions and trusted devices in the merge transaction.
- Redirect reads of the secondary ID through
merged_intofor a long grace period. - Re-target in-flight jobs, webhooks, and queued notifications.
Guard against merging strangers
The worst merge bug is the one that fuses two different people, because it is simultaneously a data loss and a data leak: person A now sees person B's projects. The safeguard is to never treat a matching email or name as sufficient evidence on its own. Require a verified, provider-attested identifier or an authenticated session on both sides, make the merge an explicit user-initiated action with a clear confirmation of what will combine, and log the whole thing so it can be reviewed and, if necessary, disputed.
Design the data model for this on day one
Account merging is painful to retrofit because it touches every table that references a user and every assumption that one human equals one row. Teams that model users-and-identities separately from the start turn most merges into a simple link and keep true merges rare and contained. That is a schema decision, which means it is one you want to own. When you run your own identity layer, you can shape the user and identity tables, the survivorship rules, and the session cutover to fit how your data is actually structured, instead of bending your model to fit whatever a hosted provider decided a "user" was.
Run it yourself
Bastionary is free, open-source software. Follow the quick start to have it running on your own server, or browse the releases on Git.