Every data engineering team eventually builds the same Rube Goldberg machine by accident: a fragile Python script calling cursor.execute("INSERT INTO ...") inside a for loop, crashing halfway through a CSV or API sync, leaving half-written rows behind, and requiring manual cleanup every Friday evening.
You do not need Airflow, Kafka, and Snowflake just to synchronize Stripe events, ERP exports, and product telemetry into a clean analytical schema. Python paired with PostgreSQL is more than capable of moving millions of records reliably—provided you design the pipeline for bulk throughput, idempotency, and clean failure recovery from day one.
Think in Stages: Extract, Validate, Stage, Merge
Reliable pipelines separate network I/O from database writes and isolate bad records before they reach production tables. Structure each run into four distinct phases:
- Extract incrementally from the source API, S3 bucket, or upstream database using a persisted watermark (
updated_at, cursor token, or sequence ID). - Validate and normalize in memory (types, currencies, UTC timestamps, required keys), diverting malformed payloads into a dead-letter table.
- Bulk load into a staging table using PostgreSQL
COPY, bypassing per-row SQL parsing and index overhead. - Merge atomically from staging into the target table and advance the watermark inside a single transaction.
Loading Method Benchmarks: Why Row-by-Row Fails
How you push bytes into PostgreSQL dictates pipeline runtime more than Python loop speed itself.
| Loading Strategy | Relative Speed | Transaction Safety | Network Overhead | When to Use |
|---|---|---|---|---|
ORM .save() / Single INSERT |
Very Slow | Simple | 1 round-trip per row | User forms, low-volume webhooks (< 50 rows) |
Batched executemany / Multi-row VALUES |
Moderate | Good | 1 round-trip per 500 rows | Medium batches (1k–20k rows) |
psycopg COPY FROM STDIN -> Staging -> MERGE |
Fastest | Atomic when merged in one TX | Minimal binary/text stream | Production ETL (10k–50M+ rows) |
As highlighted in the PostgreSQL performance documentation, COPY avoids repeated parse, plan, and WAL round-trips, making it an order of magnitude faster than individual INSERT statements.
Building an Idempotent Python + psycopg 3 Pipeline
Let's walk through a concrete pattern using psycopg (v3) that survives network timeouts and mid-batch crashes without duplicating data.
1. Watermark and Dead-Letter Schema
Create lightweight operational tables alongside your target analytics table so every run is observable and resumable:
CREATE TABLE pipeline_watermarks (
pipeline_name TEXT PRIMARY KEY,
last_cursor TEXT NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE pipeline_dead_letters (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
pipeline_name TEXT NOT NULL,
raw_payload JSONB NOT NULL,
error_message TEXT NOT NULL,
failed_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
2. Stream Clean Rows via COPY and Merge Atomically
Instead of inserting directly into the final indexed table, stream validated rows into a temporary staging table (ON COMMIT DROP), then run a single set-based upsert and watermark update inside one transaction.
from dataclasses import dataclass
from datetime import datetime, timezone
import json
import psycopg
@dataclass(frozen=True)
class CleanOrder:
external_id: str
workspace_id: int
total_cents: int
currency: str
updated_at: datetime
def validate_record(raw: dict) -> CleanOrder:
if not raw.get("id") or int(raw.get("total_cents", -1)) < 0:
raise ValueError("Missing external id or negative total_cents")
return CleanOrder(
external_id=str(raw["id"]),
workspace_id=int(raw["workspace_id"]),
total_cents=int(raw["total_cents"]),
currency=str(raw["currency"]).upper()[:3],
updated_at=datetime.fromisoformat(raw["updated_at"]).astimezone(timezone.utc),
)
def sync_orders(dsn: str, raw_records: list[dict], new_cursor: str) -> dict[str, int]:
clean_rows: list[CleanOrder] = []
bad_rows: list[tuple[str, str]] = []
for item in raw_records:
try:
clean_rows.append(validate_record(item))
except (ValueError, KeyError, TypeError) as exc:
bad_rows.append((json.dumps(item), str(exc)))
with psycopg.connect(dsn) as conn:
with conn.cursor() as cur:
if bad_rows:
cur.executemany(
"""
INSERT INTO pipeline_dead_letters (pipeline_name, raw_payload, error_message)
VALUES ('orders_sync', %s::jsonb, %s)
""",
bad_rows,
)
if clean_rows:
cur.execute("""
CREATE TEMP TABLE stg_orders (
external_id TEXT,
workspace_id BIGINT,
total_cents BIGINT,
currency CHAR(3),
updated_at TIMESTAMPTZ
) ON COMMIT DROP;
""")
with cur.copy(
"COPY stg_orders (external_id, workspace_id, total_cents, currency, updated_at) FROM STDIN"
) as copy:
for row in clean_rows:
copy.write_row((
row.external_id,
row.workspace_id,
row.total_cents,
row.currency,
row.updated_at,
))
cur.execute("""
INSERT INTO fact_orders (external_id, workspace_id, total_cents, currency, updated_at)
SELECT external_id, workspace_id, total_cents, currency, updated_at
FROM stg_orders
ON CONFLICT (external_id) DO UPDATE SET
total_cents = EXCLUDED.total_cents,
currency = EXCLUDED.currency,
updated_at = EXCLUDED.updated_at
WHERE fact_orders.updated_at <= EXCLUDED.updated_at;
""")
cur.execute(
"""
INSERT INTO pipeline_watermarks (pipeline_name, last_cursor, updated_at)
VALUES ('orders_sync', %s, NOW())
ON CONFLICT (pipeline_name) DO UPDATE SET
last_cursor = EXCLUDED.last_cursor,
updated_at = NOW();
""",
(new_cursor,),
)
conn.commit()
return {"loaded": len(clean_rows), "dead_lettered": len(bad_rows)}
Look closely at the guard WHERE fact_orders.updated_at <= EXCLUDED.updated_at on the upsert. If an out-of-order replay or webhook backfills older state, PostgreSQL ignores the stale overwrite automatically. And if the database drops mid-COPY, the temporary table disappears, the watermark does not advance, and the next scheduled run cleanly picks up from the exact prior cursor.
Avoiding Operational Pitfalls in Production
Once the core loader works, four production habits keep the pipeline from waking you up at 3:00 AM:
- Overlap your watermark window: Upstream systems commit transactions out of timestamp order. Subtract a 5-to-15-minute safety lookback from
last_cursoron each run; yourON CONFLICTmerge guarantees idempotency while catching late-committing rows. - Prevent overlapping cron runs: Wrap the job in a PostgreSQL advisory lock (
SELECT pg_try_advisory_lock(88421)) or Redis distributed lock so a slow 20-minute backfill never collides with the next 5-minute trigger. - Cap memory with generators: Stream API pages or CSV chunks through Python generators (
yield) in slices of 5,000–10,000 rows rather than holding 2 million dicts in RAM. - Alert on silence, not just exceptions: A pipeline that exits
0every hour because an upstream credential quietly expired and returned zero rows is worse than a loud crash. Emit row counts and run durations to metrics or Redis health keys and alert when ingested volume drops unexpectedly.
If your pipeline feeds customer-facing analytics or replaces brittle spreadsheets inside an older application, combining clean Python ingestion with custom web application development or legacy system modernization keeps your reporting reliable end-to-end.
Ship Production Data Pipelines With SmitDev
Whether you need to unify scattered SaaS APIs, replace fragile manual CSV imports, or build an internal warehouse on PostgreSQL, SmitDev builds lean, observable pipelines that your existing engineering team can actually maintain.
We offer predictable $1,999/month dedicated delivery, $55/day full-time engineering blocks (8–9 hours/day), and scoped sprint support through our hourly developer model for teams across the USA, UK, Europe, UAE, Australia, and Singapore.
Have messy data sources or brittle sync scripts holding back your reporting? Get in touch via our contact page and let's architect a clean Python and PostgreSQL pipeline.