Skip to content

PostgreSQL Foreign Data Wrappers in production

Use postgres_fdw and friends to query external systems from PostgreSQL — connection management, predicate pushdown, transaction semantics, and where FDWs fall over.

Foreign Data Wrappers turn an external data source into a Postgres table you can SELECT, JOIN, and (sometimes) write through. postgres_fdw is the most common — query another Postgres instance as if it were local — but the SQL/MED interface also supports MySQL, SQLite, MongoDB, Kafka, file-based wrappers, and HTTP endpoints via third-party extensions. This article covers what FDWs actually do under the hood, when they pay off, and the operational traps that bite in production.

How to verify

Confirm the wrapper is installed and a foreign server is connected:

psql -c "SELECT * FROM pg_extension WHERE extname LIKE '%fdw%';"
psql -c "SELECT srvname, srvtype, srvoptions FROM pg_foreign_server;"
psql -c "SELECT * FROM pg_user_mappings;"
psql -c "EXPLAIN (VERBOSE, ANALYZE) SELECT * FROM remote.orders WHERE id = 42;"

The EXPLAIN VERBOSE output for a remote table shows a Foreign Scan node with the actual remote SQL — that is where you confirm pushdown is happening.

What’s happening

A foreign data wrapper is a Postgres extension that exposes the SQL/MED API: a set of C callbacks that translate Postgres query plans into operations on a remote system. postgres_fdw opens a libpq connection to the remote Postgres, generates remote SQL from the parts of the plan it can push down (WHERE clauses, aggregates since PG 11, joins between two foreign tables on the same server, ORDER BY and LIMIT), executes it, and streams rows back into the local executor.

The crucial concept is pushdown. If the planner decides a filter can be evaluated remotely, the remote server does the work and ships fewer rows. If it can’t — usually because the filter references a function the remote doesn’t recognise, or mixes a local and remote table — Postgres pulls the whole foreign table down and filters locally. That is the path to a 4-hour query.

Transactions span the foreign server: every transaction that touches a foreign table opens a remote transaction. That remote transaction is held open until the local commits or rolls back. Connection pooling and idle-in-transaction timeouts on the remote side matter here.

The procedure

  1. Install the wrapper and create the server:

    CREATE EXTENSION postgres_fdw;
    
    CREATE SERVER warehouse
      FOREIGN DATA WRAPPER postgres_fdw
      OPTIONS (host 'warehouse.internal', port '5432', dbname 'analytics',
               fetch_size '10000', extensions 'pg_trgm');
    
    CREATE USER MAPPING FOR app_user
      SERVER warehouse
      OPTIONS (user 'app_reader', password 'use-pgpass-file-instead');

    fetch_size controls the cursor batch size; the default of 100 is much too low for analytic queries — 10,000 is a sensible baseline. extensions tells the planner which extensions exist on the remote so it can push down operators from them.

  2. Import schema rather than CREATE FOREIGN TABLE by hand:

    IMPORT FOREIGN SCHEMA public LIMIT TO (orders, customers, products)
      FROM SERVER warehouse INTO remote;

    This generates foreign tables that match the remote definitions. Re-run after schema changes; an out-of-sync foreign table produces confusing errors.

  3. Pin connection options that matter:

    ALTER SERVER warehouse OPTIONS (
      SET fetch_size '20000',
      SET use_remote_estimate 'true',
      SET async_capable 'true',
      SET keep_connections 'true'
    );

    use_remote_estimate = true runs EXPLAIN on the remote for every plan — pricier but produces dramatically better local plans. async_capable (PG 14+) lets the local planner start multiple remote queries in parallel for partitioned-table foreign joins.

  4. For write workloads, set updatable = true and treat the remote as if it were local — but pin your transaction discipline:

    BEGIN;
    INSERT INTO remote.orders SELECT * FROM staging.orders;
    COMMIT;

    Each statement holds the remote transaction open. Bulk loads through FDW are slower than COPY-via-network; for terabyte writes, use logical replication or a streaming ETL instead.

  5. Use analyze on foreign tables. Without local stats, the planner falls back to default_statistics_target heuristics and gets every join order wrong. Schedule ANALYZE remote.* nightly.

  6. Pool the remote side. Each backend that uses a foreign server opens its own libpq connection; 200 backends with FDW queries open 200 remote connections. Run PgBouncer in front of the remote and let keep_connections = true reuse them.

Common pitfalls

  • A WHERE clause that uses a local function (my_extension.encrypt(col) = 'x') won’t push down; the whole foreign table is dragged across the network.
  • JOINs across foreign servers don’t push down — Postgres pulls both sides and joins locally. Co-locate the data, or pre-join on one server and pull the result.
  • Stale pg_class rows on the remote (after DDL) cause relation does not exist errors until the foreign table is recreated; track DDL on the remote.
  • Transaction isolation is per-connection; SERIALIZABLE locally does not promote a foreign transaction to SERIALIZABLE automatically — set it via BEGIN ISOLATION LEVEL.
  • The default idle_in_transaction_session_timeout on the remote will kill long FDW transactions; coordinate timeouts between local and remote.

In the engagements we run, postgres_fdw is the right answer for ad-hoc cross-database queries and for operational backfills that don’t justify a full replication channel. For sustained high-volume integration we use logical replication instead. The operating discipline we apply — stats, pooling, timeouts, schema drift monitoring — is what keeps FDWs from becoming a quiet performance time-bomb. For a closer look at the operating model, see managed operations.