GCP Data & Backend Engineer Guide: Idempotent ELT Pipelines & Dead-Letter Queues
Data pipelines that ingest partner API feeds, financial settlement files, or e-commerce catalog updates fail silently when upstream schemas drift or partial network retries insert duplicate rows into analytics tables. As a backend engineer and GCP data engineer, I architect idempotent ELT pipelines with strict Pydantic/Arrow schema contracts, PostgreSQL `ON CONFLICT` / BigQuery `MERGE` upserts, and dead-letter quarantine tables.
1. Row-Level Schema Quarantine & High-Speed PostgreSQL COPY Staging
A single malformed record in a 50,000-row partner feed must never abort the entire nightly batch—nor should it be silently dropped. We validate each row against a versioned schema contract, route invalid rows with their raw payload and validation error to a `etl_quarantine_records` table, and bulk-upsert valid rows via a temporary staging table:
# etl/batch_upserter.py
import io
import csv
from decimal import Decimal
from pydantic import BaseModel, ValidationError
from django.db import connection, transaction
class PartnerCatalogRow(BaseModel):
sku_id: str
merchant_id: str
unit_price_minor: int
currency: str
updated_at_iso: str
def ingest_partner_catalog_batch(raw_rows: list[dict], batch_id: str) -> dict[str, int]:
valid_rows: list[PartnerCatalogRow] = []
quarantined: list[tuple[str, str, str]] = []
for idx, raw in enumerate(raw_rows):
try:
valid_rows.append(PartnerCatalogRow.model_validate(raw))
except ValidationError as exc:
quarantined.append((batch_id, str(raw), exc.json()))
with transaction.atomic(), connection.cursor() as cursor:
cursor.execute('''
CREATE TEMP TABLE tmp_catalog_stage (
sku_id VARCHAR(64),
merchant_id VARCHAR(64),
unit_price_minor BIGINT,
currency VARCHAR(3),
updated_at_iso TIMESTAMPTZ
) ON COMMIT DROP;
''')
buf = io.StringIO()
writer = csv.writer(buf)
for r in valid_rows:
writer.writerow([r.sku_id, r.merchant_id, r.unit_price_minor, r.currency, r.updated_at_iso])
buf.seek(0)
cursor.copy_expert("COPY tmp_catalog_stage FROM STDIN WITH (FORMAT CSV)", buf)
cursor.execute('''
INSERT INTO catalog_items (sku_id, merchant_id, unit_price_minor, currency, updated_at)
SELECT sku_id, merchant_id, unit_price_minor, currency, updated_at_iso
FROM tmp_catalog_stage
ON CONFLICT (merchant_id, sku_id) DO UPDATE
SET unit_price_minor = EXCLUDED.unit_price_minor,
currency = EXCLUDED.currency,
updated_at = EXCLUDED.updated_at
WHERE EXCLUDED.updated_at >= catalog_items.updated_at;
''')
return {"ingested": len(valid_rows), "quarantined": len(quarantined)}
2. Monotonic Timestamp Guards Against Out-of-Order Replays
Notice the `WHERE EXCLUDED.updated_at >= catalog_items.updated_at` predicate in the `ON CONFLICT DO UPDATE` clause: if an older historical file is re-run out of order during a backfill, it cannot overwrite fresher production prices.