Idempotent synchronization: replay without drift
Overview
An idempotent synchronization has the same intended state after repeating the same input. A unique business key, absolute values and a monotonic revision guard make the demonstrated product feed replay-safe. This is different from incrementing a counter on every retry. A revision must identify an authoritative version; conflicting payloads for the same revision should be rejected or reconciled before loading.
First example
BEGIN;INSERT INTO sync_item(sku,price,rev)SELECT sku,price,rev FROM sync_feed WHERE trueON CONFLICT(sku) DO UPDATE SET price=excluded.price,rev=excluded.revWHERE excluded.rev > sync_item.rev;SELECT sku,price,rev FROM sync_item ORDER BY sku;ROLLBACK;Observed SQLite result (rows in JSON):
[ [ "A", 120, 2 ], [ "B", 200, 3 ], [ "C", 80, 1 ]]How it works
INSERT SELECT uses WHERE true to avoid SQLite parsing ambiguity before ON CONFLICT. The first example synchronizes A and C and ignores stale B. The second applies the same feed twice; the second execution changes zero rows. The target-only policy is to keep rows. This demonstrates sequential logical state idempotency, not exactly-once delivery or absence of all side effects. Sequence allocations, triggers, audit entries, locks and retries may differ by engine. For additive events, use a unique event receipt and the corresponding balance change in one transaction; do not simply add excluded.quantity on every replay. Handle concurrent conflicts and retry entire failed transactions according to engine rules.
Practical example
BEGIN;INSERT INTO sync_item(sku,price,rev)SELECT sku,price,rev FROM sync_feed WHERE trueON CONFLICT(sku) DO UPDATE SET price=excluded.price,rev=excluded.revWHERE excluded.rev > sync_item.rev;INSERT INTO sync_item(sku,price,rev)SELECT sku,price,rev FROM sync_feed WHERE trueON CONFLICT(sku) DO UPDATE SET price=excluded.price,rev=excluded.revWHERE excluded.rev > sync_item.rev;SELECT changes();ROLLBACK;Observed SQLite result (rows in JSON):
[ [ 0 ]]Practice and mistakes
Practice: add a newer revision for B to the staging table and run the feed twice. Hint 1: preserve one row per sku. Hint 2: require incoming rev > stored rev and compare the final sorted state. Test an equal-version different-payload diagnostic before import.