Designing a Customer Account Remapping and History Preservation Engine
System DesignModel answerLast updated
Architect an idempotent system to merge platform customer identities while maintaining account ledgers, resolving entity conflicts, and preserving query accuracy.
You are designing a customer identity merge service for a high-scale financial platform (handling millions of accounts and billions of immutable ledger events).
Implement the architectural design for a function:
mergeCustomers(oldId, newId)
When two customer profiles belong to the same real-world entity, the system must consolidate oldId into the surviving customer newId.
Key Constraints & Requirements
- Ledger Immutability: Financial ledger entries (transactions, balances) reference an
account_id, not acustomer_id. Account history must remain completely unaltered. Accounts themselves are remapped to the surviving identity, not merged or deleted. - Backward Compatibility: After the merge completes, any API request, link, or legacy reference using
oldIdmust continue to function predictably, mapping to the canonicalnewId. - Idempotency & Concurrency: Merges must be idempotent and safe under concurrent requests (including multi-step chains like
A -> Bfollowed byB -> C, or simultaneousA -> BandB -> C).
Design Requirements
In your response, address each of the following components explicitly:
- Identifier Unification & Resolution: How is identity mapped so both old and new IDs resolve to a single canonical ID on both read and write paths? How do you prevent multi-hop lookup chains?
- Ownership Remapping: How do you move accounts, payment methods, and scheduled transfers without modifying ledger records? How do you handle non-colocated or sharded databases?
- Scheduled Items & Historical Data: How are future/recurring operations remapped without missing runs or triggering duplicate executions?
- In-Flight & Pending Transactions: How are pending authorizations, holds, and active transfers settled correctly post-merge?
- Deterministic Conflict Resolution: Define explicit rules for resolving collisions (e.g., duplicate payment tokens, duplicate scheduled transfers, identical beneficiaries, nickname collisions).
- Caching & Top-N Leaderboards: How are read-through caches updated and how is a global leaderboard (e.g., top spenders/payers) updated without double-counting?
- Consistency, Idempotency & Cycles: How do you prevent cycles (e.g.,
A -> BandB -> A), ensure operational idempotency, and guarantee atomicity across system boundaries? - Complexity Analysis: Provide time and space complexity for both the merge operation itself and the post-merge read paths.
Hints
Hint 1
Focus on flattening alias chains during resolution to keep lookup times O(1).
Hint 2
Decouple financial ledger entries from customer identity by maintaining an immutable association between balances/transactions and account IDs.
Hint 3
Use a deterministic tie-breaker (like creation timestamp or lexicographical ID) for handling duplicate payment methods or beneficiaries during entity conflicts.
Hint 4
For leaderboards and windowed counters, execute atomic, idempotent delta transfers backed by an idempotent execution table.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Architectural Overview
A core principle of financial ledger platforms is the strict separation of Identity (Customer) from Value Store (Account) and Value Transfer (Ledger Entry).
+------------------+ +-------------------+
| Customer Alias |-------->| Canonical Customer|
+------------------+ +-------------------+
|
| owns (Metadata Remap)
v
+-------------------+
| Account |
+-------------------+
|
| immutable reference
v
+-------------------+
| Ledger Entry |
+-------------------+
Because ledger transactions point strictly to immutable account_id records, merging two customers is an ownership metadata remapping problem rather than a monetary transaction problem. No ledger entries need to be updated.
1. Identifier Unification & Resolution
To unify oldId into newId while ensuring single-hop $O(1)$ lookups, we maintain two core models:
Schema
customer_identity(id PK, status [ACTIVE|MERGED], canonical_id, version)customer_alias(alias_id PK, canonical_id)
Resolution Policy (Single-Hop Guarantee)
When merging oldId into newId:
- Find the root canonical ID of
newId(call itrootNew). - Find all existing aliases that currently point to
oldId(or whose root canonical ID isoldId). - Update
customer_identityforoldIdto setstatus = MERGEDandcanonical_id = rootNew. - Insert or update
customer_aliasmapping entries so thatoldIdAND all ofoldId's previous aliases directly referencerootNew.
Before: A -> B, Merge(B, C)
After: A -> C, B -> C (Flattened, depth is always 1)
Read/Write Path Routing
- Read Path: A lightweight
IdentityResolvermiddleware wraps every API entry point. It checks a local, high-performance cache forresolve(id) -> canonical_id. If unmapped, it falls back to database lookup oncustomer_alias. - Write Path: Incoming writes targeting
oldIdare rewritten torootNewbefore entering business logic. Database updates execute conditional writes using optimistic concurrency control (WHERE customer_id = rootNew AND version = expected_version).
2. Ownership Remapping
Entities dependent on customer identity include account, payment_instrument, beneficiary, scheduled_transfer, and saved_preference.
Relational / Monolithic Remap
Within an ACID database transaction:
UPDATE account
SET customer_id = :rootNew
WHERE customer_id = :oldId;
INSERT INTO ownership_history (entity_type, entity_id, previous_customer_id, new_customer_id, merge_id, created_at)
SELECT 'account', id, :oldId, :rootNew, :mergeId
FROM account WHERE customer_id = :rootNew;
Distributed / Sharded Remap
If entities reside across distinct microservice databases or sharded keys spaces:
- Alias Registering: Commit the alias
oldId -> rootNewin the Identity Service. - Asynchronous Distributed Saga: Emit an event
CustomerMerged(merge_id, old_id, new_id)via a transactional outbox. - Idempotent Local Remap: Each domain service consumes the event and executes local updates (
UPDATE ... SET customer_id = new_id WHERE customer_id = old_id). - Dual-Read Filtering: During the async transition window, services query entities using:
WHERE customer_id IN (canonical_id, alias_1, alias_2...)
3. Scheduled Items & Historical Data
Historical Records
Past completed transfers are immutable ledger artifacts. Their header and entry rows retain original timestamps, source accounts, and destination accounts. Querying history for oldId expands oldId to rootNew and retrieves all accounts ever linked to that canonical lineage.
Scheduled and Recurring Transfers
To prevent double execution or missed payments during a merge:
- Scheduler Lock: Acquire a distributed lock (or database row lock) on
scheduled_transferrows for botholdIdandnewIdin sorted order byscheduled_transfer_idto prevent deadlocks. - Deduplication: Check for duplicate recurring transfers (matching
destination_account,amount,cadence).- Rule: Retain the older active schedule (
created_attimestamp). Cancel the duplicate schedule with statusCANCELLED_MERGE_DUPLICATE. - Execution State: Copy over
last_executed_attimestamp to the retained schedule to ensure no interim payments are skipped or repeated.
- Rule: Retain the older active schedule (
- Idempotent Execution Engine: All scheduler workers issue execution requests using an idempotency key structured as
hash(schedule_id, scheduled_execution_date).
4. Pending & In-Flight Transactions
Pending authorizations, card holds, and active wire transfers operate strictly against account_id.
- Account-Level Settlement: Holds and authorizations remain attached to their originating
account_id. Settlement completes normally without modification because accounts are not merged or destroyed. - Customer-Level Limits: Risk thresholds (e.g., daily transfer limits, velocity checks) are calculated against
resolve(customer_id). Upon merge commit, velocity counters foroldIdandnewIdare aggregated instantly or summed on demand, enforcing combined daily spend caps immediately on new authorization attempts. - Approved Holds: Pre-approved holds are grandfathered under their initial authorization state and are not retroactively failed due to combined aggregate limits post-merge.
5. Deterministic Conflict & Duplicate Resolution
When both oldId and newId possess identical or single-cardinality resources, resolve conflicts deterministically without dropping historical records:
| Entity Type | Conflict Trigger | Resolution Policy |
|---|---|---|
| Payment Method | Same token / fingerprint | Retain newId's instrument. Mark oldId's instrument as MERGED_DUPLICATE. Insert an entry into instrument_alias(old_instrument_id -> retained_instrument_id) so legacy references route correctly. |
| Beneficiaries | Identical account details | Retain the earliest created beneficiary (min(created_at)). Set verified_status = (old.verified OR new.verified). |
| Primary Account | Both profiles have a designated primary | Retain newId's primary account selection. Demote oldId's primary account to a standard secondary account. |
| Nicknames / Labels | Per-customer unique constraint collision | Append a deterministic suffix to the incoming oldId entity (e.g., Savings (Merged 1)). Tie-break using entity ID. |
6. Indexes, Caching & Leaderboard Updates
Cache Invalidation
Read-through caches store customer profiles using versioned keys: customer:{id}:v{version}.
On merge commit:
- Publish an invalidation event for both
oldIdandnewId. - Increment the
versioncolumn in the database forrootNew. Subsequent cache reads reload fresh aggregated state.
Top-N Leaderboards (e.g., Top Spenders)
Leaderboards are typically maintained using Redis Sorted Sets (ZSET) or indexed summary tables aggregated by customer ID.
Leaderboard Key: leaderboard:spending:2026-Q1
To update the leaderboard atomically without double-counting:
-- Atomic Redis Script executed on merge
local old_score = tonumber(redis.call('ZSCORE', KEYS[1], ARGV[1]) or 0)
local new_score = tonumber(redis.call('ZSCORE', KEYS[1], ARGV[2]) or 0)
if old_score > 0 then
redis.call('ZINCRBY', KEYS[1], old_score, ARGV[2])
redis.call('ZREM', KEYS[1], ARGV[1])
end
ARGV[1]=oldId,ARGV[2]=newId- This transfers
oldId's score tonewIdand purgesoldIdin a single atomic operation.
7. Consistency, Idempotency & Cycle Prevention
Preventing Cycles (A -> B, B -> A)
Before executing a merge, detect potential cycles using depth-first search or canonical resolution checks:
def validate_merge(old_id, new_id):
root_old = resolve_canonical(old_id)
root_new = resolve_canonical(new_id)
if root_old == root_new:
# Idempotent case: already merged
return ALREADY_MERGED
if is_ancestor(root_old, root_new):
raise CycleDetectedException(f"Cannot merge {old_id} into {new_id}: forms a cycle")
Concurrency Lock Ordering
To execute merges safely when requests arrive simultaneously (e.g., Merge(A, B) and Merge(B, C)):
- Sort all participating customer IDs lexicographically:
lock_keys = sort([old_id, new_id]). - Acquire pessimistic distributed locks in strict sorted order:
lock(lock_keys[0]), thenlock(lock_keys[1]). - Re-read canonical IDs after locking to confirm states have not shifted.
State Machine for Operation Idempotency
Merges run through a merge_execution table tracking state:
[INITIATED] ---> [ALIASES_UPDATED] ---> [RESOURCES_REMAPPED] ---> [COMPLETED]
If a process fails midway, re-invoking mergeCustomers(oldId, newId) inspects the merge_execution record and resumes from the uncompleted phase safely.
8. Complexity Analysis
Time Complexity
-
Merge Execution:
- Identity flattening: $O(A)$, where $A$ is the number of existing aliases targeting
oldId(typically $A \le 5$). - Resource remapping: $O(E)$, where $E$ is the total count of dependent entities (accounts, schedules, payment methods) attached to
oldId. Since individual customers own bounded entities ($E \ll 1000$), this runs in $O(1)$ relative to total platform scale. - Leaderboard update: $O(\log N)$, where $N$ is the number of entries in the top-$N$ structure.
- Overall Merge Time: $O(E + \log N)$ operational steps.
- Identity flattening: $O(A)$, where $A$ is the number of existing aliases targeting
-
Post-Merge Read Path:
- Identity resolution: $O(1)$ lookup due to single-hop alias flattening.
- Account balances & history queries: $O(1)$ indexed lookup by
account_idorcanonical_id.
Space Complexity
- Storage Footprint: $O(1)$ net structural growth per merge. We write $1$ alias record in
customer_aliasand append audit tracking rows proportional to remapped entities ($O(E)$). No historical transactions are cloned or duplicated.