返回资讯中心
外部精选
软件工程
#开发者实时流

Postgres FDW: Pushdown is a negotiation

Postgres extensions add functionality that Postgres itself does not include. Examples include PostGIS for geospatial data, pgvector for embeddings, and TimescaleDB for time-series. Via extensions the Postgres ecosystem …

Hacker News 最新saisrirampur2026/10/15 · 2026/10/1530 分钟阅读

以下正文同步自 Hacker News 最新,版权归原站所有,已转换为易读排版。

Postgres extensions add functionality that Postgres itself does not include. Examples include PostGIS for geospatial data, pgvector for embeddings, and TimescaleDB for time-series. Via extensions the Postgres ecosystem distributes new functionality; just CREATE EXTENSION to hook into Postgres internals, and thereafter the user mostly forgets about it.

Foreign Data Wrapper extensions, also known as “FDW”s, teach Postgres how to read (and sometimes write) data outside of Postgres. Simply declare a foreign table:

1CREATE FOREIGN TABLE events (...) 2SERVER my_clickhouse OPTIONS (table 'events');

Copy command

Then SELECT * FROM events resembles a query against any other table. Internally, Postgres asks the FDW to fetch the data from elsewhere.

pg_clickhouse, the FDW we maintain, fetches data from ClickHouse. While people often rely on the unified data stack — Postgres for transactional data and ClickHouse for analytics — pg_clickhouse executes SQL queries on both systems. As we worked on it for the past 6 months, we found that a single question drives most of the engineering work: how much of a query do we send across the wire as SQL versus how many rows do we drag back as data?

That question encompasses the meaning of pushdown: how much work can we “push down” to the remote service? The answer seems simple: “send everything!” — the WHERE clause, the GROUP BY, the LIMIT. But a closer examination reveals the complexity: Some clauses we can send. Some we can almost send — if we rewrite them. Some we used to send but stopped, because they returned the wrong results. And some clauses can never be sent by any FDW, regardless of the engineering one throws at them.

We’ve found the process of making these determinations highly iterative.

To demonstrate, let’s examine the impact of that iteration on a single query: what gets pushed down, what doesn't, and how we continuously modified the code in response to the question.

The goal is to illuminate the inner workings of an FDW for people who’ve heard of FDWs but don’t know how they work in detail. Whether you're a Postgres user curious about ClickHouse, a ClickHouse user curious about Postgres, or someone thinking about writing an FDW yourself, we hope you find this exercise edifying.

This query ranks the busiest web events in the last week for the US, UK, and DE, by country and event name. It reports volume, unique users, premium share, p95 latency, and each event’s rank by country, returning the top 100 rows overall to provide a small snapshot and avoid streaming raw events.

1SELECT 2 u.country, 3 e.event_name, 4 count() AS n, 5 count(DISTINCT e.user_id) AS unique_users, 6 count() FILTER (WHERE e.properties->>'tier' = 'premium') AS premium_count, 7 percentile_cont(0.95) WITHIN GROUP (ORDER BY e.duration_ms) AS p95_ms, 8 ROW_NUMBER() OVER (PARTITION BY u.country ORDER BY count(*) DESC) AS rank_in_country 9FROM events_ch e JOIN users_ch u USING (user_id) 10WHERE e.ts >= now() - interval '7 days' 11 AND u.country IN ('US', 'UK', 'DE') 12 AND e.properties->>'platform' = 'web' 13GROUP BY u.country, e.event_name 14ORDER BY n DESC 15LIMIT 100;

Copy command

events_ch and users_ch are foreign tables backed by ClickHouse. With every clause in this query pushed down, it returns 100 rows in roughly 80 ms.

If a single clause fails to push down, the query takes minutes. We built support for pushing down the window function, the percentile, the JSON access, and the FILTER aggregate; but each was, at some earlier point, not yet pushed down. When an operation cannot be pushed down, the rest of the query can't push down either; rows that should have been aggregated remotely must stream back to Postgres so it can aggregate them locally. The wire ends up carrying tens to hundreds of millions of rows instead of 100.

Pushdown looks like a feature, but it’s really an agreement between two SQL grammars, revised for every Postgres release. This explains why the pg_clickhouse release notes often look like corrections: revoking incorrect array-function pushdown, adding safer functions like levenshtein and soundex, and respecting planner invariants like EvalPlanQual even when the remote could move faster.

An FDW does not send the original Postgres query to the remote database; doing so causes errors where the SQL dialects differ. But ideally, It also does not pull every row back unless it has to (as simple FDWs like file_fdw do), because although the results would be correct, execution would be slow.

Postgres does not directly decide that a scan, join, aggregate, sort, or limit can be executed in ClickHouse. Instead, it asks the FDW to contribute foreign paths to the planner via the FDW planning callbacks. pg_clickhouse registers these planning callbacks:

1routine->GetForeignRelSize = clickhouseGetForeignRelSize; 2routine->GetForeignPaths = clickhouseGetForeignPaths; 3routine->GetForeignPlan = clickhouseGetForeignPlan; 4routine->GetForeignJoinPaths = clickhouseGetForeignJoinPaths; 5routine->GetForeignUpperPaths = clickhouseGetForeignUpperPaths;

Copy command

GetForeignPaths, GetForeignJoinPaths, and GetForeignUpperPaths tell the planner what can be pushed down. If the planner selects one of those paths, GetForeignPlan builds the plan and generates the ClickHouse SQL.

These callbacks are just entry points; pg_clickhouse’s callback functions verify that each clause or expression can be translated without changing the result. Of course it started out quite simple: just a few clauses and expressions inherited from the original fork from postgres_fdw. Thus pg_clickhouse initially pushed down count() but not count() FILTER (...), couldn’t push down percentile_cont or JSON predicates like properties->>'platform': because it did not know how.

Thus, pushdown is not a yes/no decision for a whole query, but constitutes a series of smaller decisions: does Postgres expose the hook, can pg_clickhouse translate the expression, and can ClickHouse execute it with the same meaning?

To answer the question, "why doesn’t X push down?" let’s look at one realistic query and walk it through everything pg_clickhouse has shipped. Same query, seven steps. Each step pushes down more to ClickHouse; Postgres must evaluate what remains after pulling back the rows it needs to do so.

Each step examines the same query. Lines marked ✓ push down at that step; lines marked ✗ remain local. Each step also marks a real date in our history, when the relevant pushdown landed in the codebase, or when we expect to ship it. Each step demonstrates what the query plan looked like as of that date.

Inherited from the original clickhouse_fdw via initial port e5035bc (October 2, 2025). Available in pg_clickhouse since v0.1.0 (December 9, 2025).

The starting point is deliberately small: pg_clickhouse only pushes down predicates it can translate with confidence. Comparisons like >=, membership checks like IN, and simple timestamp arithmetic are safe to push down because Postgres and ClickHouse have clear equivalents for them. In other words, those filters run in ClickHouse rather than collecting all the rows to evaluate in Postgres.

1SELECT 2 u.country, -- ✗ 3 e.event_name, -- ✗ 4 count() AS n, -- ✗ 5 count(DISTINCT e.user_id) AS unique_users, -- ✗ 6 count() FILTER (WHERE e.properties->>'tier' = 'premium') AS …, -- ✗ 7 percentile_cont(0.95) WITHIN GROUP (ORDER BY e.duration_ms) AS …, -- ✗ 8 ROW_NUMBER() OVER (PARTITION BY u.country ORDER BY count(*)) AS … -- ✗ 9FROM events_ch e -- ✓ scan only 10 JOIN users_ch u USING (user_id) -- ✗ 11WHERE e.ts >= now() - interval '7 days' -- ✓ 12 AND u.country IN ('US','UK','DE') -- ✓ 13 AND e.properties->>'platform' = 'web' -- ✗ 14GROUP BY u.country, e.event_name -- ✗ 15ORDER BY n DESC -- ✗ 16LIMIT 100 -- ✗

Copy command

At this point, only the base-table filters push down. The SQL translator (internally called a “deparser”) emits one remote scan for events with the timestamp predicate, and one remote scan for users with the country predicate. It sends these two separate queries to ClickHouse and collects the results. Everything that combines rows or changes their shape, including the join, grouping, aggregates, window function, sort, and limit, runs inside Postgres against those retrieved rows. Thus the wire must carry every matching events row from the last seven days, plus every matching users row, before Postgres can reduce the result to 100 rows.

The point is that even the simplest pushdown is already a translation problem: now() can be pushed down as now(), while interval '7 days' is translated as 7 * 86400. Those mappings live in src/custom_types.c, where pg_clickhouse records the expressions it knows how to translate safely for ClickHouse. The steps outlined below expand that vocabulary from base filters to joins, aggregates, windows, and limits.

Inner-JOIN deparse came from the original clickhouse_fdw, but the inherited cost estimates were placeholders, and the Postgres planner often pulled rows back to join locally rather than push. Commit b345682 (December 1, 2025) replaced them with row-count-based estimates and cost-based scans higher than join paths, so the planner reliably picks the pushed plan. Plus 6a297ec (Nov 13, 2025) for join_use_nulls outer-join semantics. All shipped in v0.1.0 (December 9, 2025).

At this step pg_clickhouse stops treating events_ch and users_ch as two independent remote scans. Since both tables live on the same ClickHouse server and the join condition has a ClickHouse equivalent, the FDW can ask ClickHouse to make the join before any joined rows cross the wire.

1SELECT ... -- ✗ (still) 2FROM events_ch e -- ✓ 3 JOIN users_ch u USING (user_id) -- ✓ joins push 4WHERE e.ts >= now() - interval '7 days' -- ✓ 5 AND u.country IN ('US','UK','DE') -- ✓ 6 AND e.properties->>'platform' = 'web' -- ✗ stays local 7GROUP BY u.country, e.event_name -- ✗ 8ORDER BY n DESC -- ✗ 9LIMIT 100 -- ✗

Copy command

The remote SQL is now roughly SELECT * FROM events ALL INNER JOIN users USING (user_id) WHERE …. The ALL keyword is deliberate: ClickHouse's default join can return only one matching row, while a Postgres inner join returns all matches. Emitting ALL INNER JOIN preserves Postgres semantics. The JSON predicate still cannot be translated at this point, so it is left out of the remote WHERE and applied locally to the returned rows.

Postgres enabled this kind of join pushdown in 9.6 (commit e4106b25287, 2016, Etsuro Fujita). Previously, FDWs had to hook deeper into the planner to accomplish join pushdown.

For our query, this single step reduces query time from roughly 30 minutes to 30 seconds, because the join filters rows before they leave the remote.

Also inherited via e5035bc. GROUP BY, basic aggregates (count, sum, min, max, avg), ORDER BY, and LIMIT all pushdown since v0.1.0 (December 9, 2025).

This step emphasizes result-shaping work: grouping rows, computing basic aggregates, sorting the grouped result, and applying the final limit. Postgres exposes these operations as “upper” planning stages, and the FDW can offer a remote version of each stage when the whole stage can be represented in ClickHouse. Aggregate pushdown arrived in Postgres 10 (commit 7012b132d07); ORDER BY and LIMIT pushdown followed in Postgres 12.

Still, at this point pg_clickhouse cannot push down all of the operations: The grouping stage must encompass the entire SELECT list, and it hasn’t been wired to push down three expressions:

Note that grouped pushdown is all-or-nothing for a given grouped result. So even though count(*), count(DISTINCT), GROUP BY, ORDER BY, and LIMIT are individually fine, the grouped part of this particular query still remains local.

1SELECT 2 u.countr

正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。

打开原文
去社区讨论 →