HomeBlogHow to Build a Data Pipeline...

Engineering Guide · 9 min read · October 31, 2026

How to Build a Data Pipeline Using Python and PostgreSQL

You do not need a heavy Spark cluster to move gigabytes of business data reliably. A disciplined Python and PostgreSQL pipeline built around incremental watermarks, COPY-based staging loads, idempotent merges, and dead-letter error isolation handles production workloads cleanly and stays easy to debug.

Author
Smit Desai
Published
October 31, 2026
Read time
9 min read
Topic
Data & Databases
Services
Custom Web · Mobile Apps · All Services

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:

  1. Extract incrementally from the source API, S3 bucket, or upstream database using a persisted watermark (updated_at, cursor token, or sequence ID).
  2. Validate and normalize in memory (types, currencies, UTC timestamps, required keys), diverting malformed payloads into a dead-letter table.
  3. Bulk load into a staging table using PostgreSQL COPY, bypassing per-row SQL parsing and index overhead.
  4. 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_cursor on each run; your ON CONFLICT merge 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 0 every 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.

Written by Smit Desai · Principal Full-Stack & FDSE

8+ years shipping production systems · 171 case studies · 300+ WordPress servers managed for Finland partners.

Next Steps and Recommended Resources

Next Steps · Recommended Resources

Pillar 1 · Infrastructure Proof

300+ WordPress & Cloud Server Fleet

From server-level management of 300+ WordPress sites for a Finland client to PostgreSQL query tuning (3,982 -> 52 queries).

Pillar 2 · Legacy Rescue

Upgrade Old Software (10 Hrs Free)

Audit bottlenecks, eliminate security vulnerabilities, and stabilize production servers—starting with 10 free engineering hours.

01 — Frequently asked questions

data & databases

Is Python fast enough for loading millions of rows into PostgreSQL?

Yes, provided you avoid row-by-row ORM inserts. Streaming cleaned records into a staging table via PostgreSQL COPY (using psycopg 3) and merging with set-based SQL routinely loads tens of thousands of rows per second.

Should I build a custom Python pipeline or adopt Airflow/Dagster right away?

If you have 3 to 10 scheduled jobs, start with clean modular Python scripts triggered by cron, systemd timers, or GitHub/worker queues plus structured logging. Adopt Dagster or Airflow once cross-job dependencies and backfills become hard to coordinate.

How do you make a PostgreSQL ETL pipeline safe to re-run after a crash?

Track high-watermarks in a metadata table inside the same transaction as the target merge, stage raw batches in temporary or unlogged tables, and use deterministic keys with ON CONFLICT DO UPDATE so retries never create duplicate records.

How should malformed API or CSV rows be handled in production pipelines?

Validate records with Pydantic or explicit schema checks before loading, and route invalid rows to a dead_letter_events table with the raw payload and error reason instead of aborting the entire batch.

03 — Have an engineering need?

hire the right expertise

Let's talk tech.

Deciding between an embedded forward deployed engineer or a senior full stack developer? Share your technical context and timeline.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.