DEV Community

Hunter
Hunter

Posted on

Why Your PostgreSQL API Sync Silently Deletes Live Customers

A reconciliation job can finish successfully and remove a customer who is still active upstream.

An API hard delete without a reliable event leaves the old row in PostgreSQL: a ghost row. Incremental sync can upsert existing rows, but cannot return one that has disappeared. A full scan finds ghosts only if its source view is complete. Missing is not proof of deletion.

I built a deterministic PostgreSQL 16 benchmark using a simulated FastAPI source: seven strategies, 10,000 subscriptions, two tenants, 100-row pages, and 20 trials. The measured source tree contains the harness, schema, and 32 tests. The JSON results record run metadata; BENCHMARK_TABLE.md presents the measurements.

Figure 1

Figure 1: Reconciliation architecture.

Five ways reconciliation can go wrong

Each sweep scans 5,000 IDs for one tenant in 100-row pages. One failure is a missing delete event; four arise during the scan:

  1. Hard-delete ghosts: A record disappears without a tombstone. Incremental sync misses it; the local row remains and may inflate monthly recurring revenue (MRR).
  2. OFFSET drift: Page 1 returns IDs 10 to 1000. The source deletes 420, shifting 1010 onto the already-read page. The next OFFSET 100 starts at 1020; ID 1010 is never seen and is falsely deleted.
  3. Backdated arrivals: A webhook commits after the sweep starts, but its source_created_at predates the cutoff. The row can still be deleted.
  4. Sequence races: nextval() is not commit order. A writer reserves 500 and pauses; the sweep reads 501; the writer commits later with a value below the high-water mark. See sequence functions.
  5. Replica lag: A webhook writes locally before the upstream read replica catches up. The scan misses the ID; a local lock cannot fix stale source data.

Figure 2

Figure 2: An earlier deletion shifts later IDs across the next OFFSET boundary.

Measure row correctness, not just revenue

Net MRR difference compares totals; gross MRR difference sums absolute row-level errors. One $50 ghost can offset one falsely deleted $50 subscription: $0 net error, $100 gross error (Strategy 2c). Matching totals do not prove row-level correctness.

Benchmark results

The run used commit 253fd33436, Python 3.12.11, PostgreSQL 16.15, a Linux 6.8 Azure x86_64 runner, 100-row pages, 20 trials per strategy, and seed 42 (2 November 2026). Correctness was identical across trials; repeats measure timing, not incident frequency. The JSON and table agree. CPU model and RAM were not recorded, so timings are runner-specific.

Strategy Ghost rows left False deletes Net MRR Gross MRR
0. Incremental tombstones 2 0 $100 $100
1. Naive OFFSET 1 4 $200 $300
2a. Keyset + source timestamp 1 2 $100 $200
2b. Keyset + sequence 1 2 $50 $150
2c. Epoch barrier 1 1 $0 $100
3. Two-phase quarantine 1 0 $50 $50
4. Consistent snapshot 2 1 $50 $150

Incremental sync leaves two ghosts; OFFSET falsely deletes four live rows. Keyset removes page drift, not other races. Epoch sealing prevents local writer races, not replica lag. Quarantine has no false deletes here; snapshot still misses the lagged row.

These are database timings, not end-to-end sweep durations. Pre-scan covers setup and watermark work; post-scan covers staging and reconciliation. Medians are independent, so their sum may differ from the total median. DELETE metrics use EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON).

Strategy API reqs Payload Pre DB Post DB Total DB med / P95 DELETE plan DELETE root shared hits
0. Incremental 1 0.8 KB 0.00 ms 2.77 ms 2.77 / 4.51 ms 0.00 ms N/A
1. OFFSET 50 29.4 KB 0.00 ms 73.52 ms 73.52 / 150.06 ms 61.97 ms 78
2a. Timestamp 50 30.5 KB 3.78 ms 51.56 ms 56.97 / 93.61 ms 10.42 ms 15,073
2b. Sequence 50 30.5 KB 4.37 ms 52.12 ms 57.94 / 127.56 ms 11.91 ms 15,089
2c. Epoch 50 30.5 KB 5.47 ms 51.69 ms 57.66 / 88.03 ms 11.76 ms 15,069
3. Quarantine 100 61.0 KB 7.02 ms 105.35 ms 113.29 / 145.72 ms 0.11 ms 6
4. Snapshot 51 30.5 KB 5.83 ms 50.64 ms 56.36 / 102.42 ms 10.66 ms 15,069

Quarantine scans twice; its final DELETE is small, but total work includes both scans and validation. These are workload-specific measurements.

1. Serialize sweeps per tenant

A table-level lock on destination_subscriptions would block webhook writes across tenants. The engine instead uses a session advisory lock (pg_try_advisory_lock) keyed by a signed 64-bit tenant hash. See tenant_advisory_lock_id() and PostgreSQL advisory locks.

def tenant_advisory_lock_id(tenant_id: str) -> int:
    digest = hashlib.sha256(f"reconcile_lock:{tenant_id}".encode()).digest()
    return int.from_bytes(digest[:8], "big", signed=True)
Enter fullscreen mode Exit fullscreen mode

The sweep commits after sealing, paginates, then opens its final transaction. A transaction-level lock would end at the first commit, leaving the tenant unprotected during the scan. A session lock survives commits while its connection stays open; cleanup unlocks it or closes the connection if release fails.

2. Use keyset pagination and COPY staging

The OFFSET baseline passes collected IDs directly to its delete:

DELETE FROM destination_subscriptions
WHERE tenant_id = %s AND is_deleted = FALSE
  AND NOT (id = ANY(%s));
Enter fullscreen mode Exit fullscreen mode

Other full sweeps page with id > last_seen_id ORDER BY id ASC LIMIT 100. This avoids shifts behind the cursor, but is not a source snapshot.

After fetching all pages, the worker bulk-loads IDs with Psycopg 3 COPY into an indexed UNLOGGED table:

CREATE UNLOGGED TABLE unlogged_seen_ids (
  sweep_id UUID NOT NULL, tenant_id TEXT NOT NULL, id BIGINT NOT NULL,
  PRIMARY KEY (sweep_id, tenant_id, id)
);
Enter fullscreen mode Exit fullscreen mode

The primary key supports NOT EXISTS; ANALYZE refreshes planner statistics after COPY. UNLOGGED data avoids normal WAL logging, is not replicated to standbys, and is truncated after crash recovery. See CREATE TABLE and COPY. The worker holds 5,000 IDs in memory; larger scans should stage pages as they arrive.

3. Seal the ingestion epoch

Keyset cannot protect backdated arrivals or sequence races. Strategy 2c uses a trigger to stamp normal writes with the tenant's epoch. During quarantine updates, it preserves the old epoch and rejects business-column changes:

IF TG_OP = 'UPDATE' AND NEW.missing_streak > OLD.missing_streak THEN
  IF (OLD.mrr_cents, OLD.is_deleted, OLD.source_created_at,
      OLD.updated_at, OLD.ingested_at, OLD.ingestion_seq)
     IS DISTINCT FROM
     (NEW.mrr_cents, NEW.is_deleted, NEW.source_created_at,
      NEW.updated_at, NEW.ingested_at, NEW.ingestion_seq) THEN
    RAISE EXCEPTION 'Quarantine update violation: business columns cannot be modified during quarantine maintenance on tenant % id %', OLD.tenant_id, OLD.id;
  END IF;
  NEW.ingestion_epoch := OLD.ingestion_epoch;
  RETURN NEW;
END IF;

SELECT current_epoch INTO v_epoch FROM tenant_watermarks
WHERE tenant_id = NEW.tenant_id FOR SHARE;
IF NOT FOUND THEN
  INSERT INTO tenant_watermarks (tenant_id, current_epoch)
  VALUES (NEW.tenant_id, 1) ON CONFLICT DO NOTHING;
  SELECT current_epoch INTO STRICT v_epoch FROM tenant_watermarks
  WHERE tenant_id = NEW.tenant_id FOR SHARE;
END IF;
NEW.ingestion_epoch := v_epoch;
Enter fullscreen mode Exit fullscreen mode

The full trigger also makes tenant_id immutable and resets quarantine on active writes. Webhook writers can share FOR SHARE locks; the sealer's UPDATE conflicts and waits:

UPDATE tenant_watermarks SET current_epoch = current_epoch + 1
WHERE tenant_id = %s
RETURNING current_epoch - 1 AS sealed_epoch;
Enter fullscreen mode Exit fullscreen mode

After prior writers commit or roll back, the sealer advances the epoch. Later writes receive the new epoch and are excluded:

DELETE FROM destination_subscriptions d
WHERE d.tenant_id = %s AND d.is_deleted = FALSE
  AND d.ingestion_epoch <= %s
  AND NOT EXISTS (
    SELECT 1 FROM unlogged_seen_ids s
    WHERE s.sweep_id = %s AND s.tenant_id = d.tenant_id AND s.id = d.id
  );
Enter fullscreen mode Exit fullscreen mode

Figure 3

Figure 3: Existing writers finish in the old epoch; later writes receive the new epoch.

Both timeout settings default to five seconds. lock_timeout caps each lock wait; statement_timeout caps the whole update. A timeout rolls back and raises IncompleteSweepError. Only trigger-firing writes are protected; heavy ingestion can contend on the watermark row. See seal_tenant_ingestion_epoch().

4. Quarantine before deleting

The epoch barrier cannot fix a stale replica. On a miss, quarantine increments missing_streak and records the sweep sequence; last_missed_sweep_seq prevents one sweep from counting twice:

UPDATE destination_subscriptions d
SET missing_streak = missing_streak + 1, last_missed_sweep_seq = %s
WHERE d.tenant_id = %s AND d.is_deleted = FALSE
  AND d.ingestion_epoch <= %s AND d.last_missed_sweep_seq < %s
  AND NOT EXISTS (SELECT 1 FROM unlogged_seen_ids s
    WHERE s.sweep_id = %s AND s.tenant_id = d.tenant_id AND s.id = d.id);
Enter fullscreen mode Exit fullscreen mode

If the row reappears or an active webhook arrives, its streak resets. A row still missing on a later completed sweep reaches missing_streak >= 2 and becomes eligible for deletion:

DELETE FROM destination_subscriptions
WHERE tenant_id = %s AND is_deleted = FALSE AND missing_streak >= 2;
Enter fullscreen mode Exit fullscreen mode

A partial index on (tenant_id, missing_streak) WHERE is_deleted = FALSE supports the lookup. A simulator hook clears the omission between benchmark passes; production passes should be spaced across the provider's lag window. Two misses are stronger evidence, not certainty: persistent lag can still cause a false delete. Without a lag bound, require review. See the quarantine strategy.

5. Abort suspicious sweeps

Before deletion, assert_deletion_safety_bound() compares candidate deletes with eligible active rows. The default max_delete_ratio is 0.20. After the counts are queried, the core guard is (messages shortened):

if eligible_count == 0:
    return
if seen_staged == 0 and eligible_count > 0:
    raise MassDeletionAbortedError("Scan returned 0 records; sweep aborted")
ratio = candidates_to_delete / eligible_count
if ratio > max_delete_ratio:
    raise MassDeletionAbortedError("Deletion ratio exceeds safety limit")
Enter fullscreen mode Exit fullscreen mode

The transaction rolls back; the sweep is marked aborted and staging is cleared. The 20% threshold catches large omissions, not all partial scans: a 15% omission can pass. The fetcher also aborts on non-200 responses, empty pages with has_more=True, unsorted or duplicate IDs, and cursor mismatches. It raises IncompleteSweepError. See assert_deletion_safety_bound() and fetch_keyset_pages_fail_closed().

Scope and reproduction

This is deterministic fault injection, not a production load test. In-process HTTPX excludes network latency, provider rate limits, and production traffic. Repeated runs measure timings, not incident probabilities. A snapshot cannot fix stale data, and the immediate second quarantine pass does not model a real delay.

Requirements: Python 3.12+, PostgreSQL 16, Docker Compose, and uv. Minimum dependencies: FastAPI 0.115+, HTTPX 0.27.2+, Psycopg 3.2+, tabulate 0.9+; uv.lock pins versions. Compose sets shared_buffers=256MB and work_mem=16MB. Use a disposable DATABASE_URL: the schema drops benchmark tables. The runner refuses destructive resets unless the database is allowlisted or ALLOW_UNSAFE_DB_RESET=1 is set. Host CPU/RAM minimums are unspecified. Then run:

docker compose -f .devcontainer/docker-compose.yml up -d db
uv sync --locked
uv run --locked pytest -v
uv run --locked python benchmarks/run_benchmark.py
Enter fullscreen mode Exit fullscreen mode

Choosing a strategy

Use incremental sync when the provider supplies a reliable deletion feed. For a strongly consistent source, combine keyset pagination, indexed staging, and epoch sealing if every write path fires the trigger. For lagging replicas, add quarantine and the ratio guard, spacing observations across the consistency window. Without a useful lag bound, require review.

Here, epoch sealing prevents local writer races but not replica lag; quarantine avoids injected false deletes at higher API and database cost. No local lock proves source completeness. Treat absence as a destructive decision: validate every page, state the assumptions, and abort when uncertain.

GitHub logo Hunter-debug00 / pg-api-reconciliation

Syncing 10,000 external API records into PostgreSQL 16 without race conditions or silent data loss. Reproducible benchmarks, advisory locks, and deletion safety guards.

Can You Safely Delete Rows from a Mutable API?

Seven PostgreSQL reconciliation strategies tested against a changing paginated source.

CI Python 3.12 PostgreSQL 16 License MIT

You sync subscriptions from a SaaS API into PostgreSQL. A customer is hard-deleted upstream, and your copy keeps them forever. So you scan the API, collect every ID you see, and delete the rest.

Then the scan misses an active customer, and you delete them too.

This repo reproduces that failure on purpose and compares seven ways of deciding a row is really gone. A FastAPI simulator plays the upstream API, PostgreSQL 16 holds the copy, and the data is 10,000 subscriptions across two tenants. Mutations hit the source while the scan is running, the same way every time. 32 tests, 20 repeated timing trials per strategy.

The problem

Incremental sync (GET /subscriptions?updated_after=...) catches new rows, edits and soft deletes. It cannot catch a hard delete, because a deleted…

Top comments (2)

Collapse
 
hunter-debug00 profile image
Hunter •

how your teams handle hard delete detection when a third-party REST API offers neither tombstones nor snapshot cursors?

Collapse
 
aryan_bulandi_4f767baf4a9 profile image
Aryan Bulandi •

Even without pagination ‘slippage’ there can be 4 incorrect deletions. I like using the quarantine area as a failsafe.
What is your normal period of time between double-checking and then permanently deleting?