Keep BigQuery federation from overloading PostgreSQL
In brief
Use BigQuery federation for narrow, occasional PostgreSQL reads. Move repeated historical reporting to an analytical copy.
- Inspect the PostgreSQL plan. A small result can still require a large scan.
- Restrict the connection's database role and verify which instance serves the reads.
A chart can return ten rows after PostgreSQL scans a large part of an orders table. Sending that query through BigQuery leaves the scan in PostgreSQL and gives the report another route into the operational database.
We’d use federation for a narrow, infrequent read whose source cost is understood. Repeated historical reporting should usually read an analytical copy.
The decision turns on the PostgreSQL work the report causes and how often that work runs. That includes dashboard interactions and retries.
We mean BigQuery’s EXTERNAL_QUERY path into Cloud SQL or AlloyDB for PostgreSQL, against a database that already serves an operational workload worth protecting.
Follow the query across the boundary
EXTERNAL_QUERY sends SQL in the source database’s dialect, receives its result, and exposes that result to the surrounding BigQuery query. A PostgreSQL aggregation written inside the function runs in PostgreSQL. A later join to a warehouse table runs on the returned data in BigQuery.
BigQuery can automatically push some filters and column selection into the remote read. Documented query-shape and expression restrictions apply.
BigQuery doesn’t push joins, aggregates, ordering, or LIMIT through this function. Inspect the plan: an outer date filter may never have reached the source query.
For a report that needs one customer’s September order count, put the whole request in the remote SQL:
SELECT customer_id, order_count
FROM EXTERNAL_QUERY(
'projects/demo-warehouse/locations/europe-west1/connections/reporting_pg',
'''
SELECT customer_id, COUNT(*) AS order_count
FROM reporting.orders
WHERE customer_id = 42
AND booked_on >= DATE '2026-09-01'
AND booked_on < DATE '2026-10-01'
GROUP BY customer_id
'''
);The example assumes integer customer IDs and a date column. PostgreSQL computes the requested count. BigQuery receives that compact result. Whether PostgreSQL finds those rows cheaply depends on its plan for the data distribution and the available indexes.
Compare this with a remote query that groups every customer for the same month and applies customer_id = 42 only after receiving the result. Both can produce the same displayed row from different remote work and different transferred results.
Moving a predicate into the remote SQL by hand must preserve its meaning, especially when joins, null handling, collations, or time zones are involved.
The fully qualified connection path removes any doubt about which project’s connection is used. The function also doesn’t preserve ordering from the remote query. Any required final order belongs in the outer query.
Inspect the source plan without inventing a benchmark
Take the remote SQL to the database owner. Start with an estimated PostgreSQL plan on a suitable test system. Check how it finds the customer/date range and how many rows it expects to process.
Use EXPLAIN ANALYZE only as an intentional execution test, because it runs the statement and adds profiling work. A representative test can show actual rows and buffer work, but a small synthetic table won’t reproduce production cache behavior or contention.
Correlate the report’s BigQuery job with source evidence. Cloud SQL and AlloyDB federation annotate the remote SQL with the BigQuery project and job identifier. When source logging is enabled and its logs are kept, that comment connects a warehouse request to the statement that reached PostgreSQL.
During an approved workload test, watch application latency alongside database CPU, I/O waits, and lock waits. Cloud SQL query insights can break down load by database, user, and query when it’s enabled and your edition and instance configuration support it. Use whatever observability the target offers. Include a replica when that’s where federation runs.
Before the dashboard gains more consumers, record its acceptable source duration, rows or buffer work, invocation rate, and effect on operational requests.
Bound who can send the work
The BigQuery connection contains database credentials. Everyone allowed to use it reads PostgreSQL as that connection’s database role, with that role’s grants. Give that role only the approved reporting reads. Restrict connection use to the intended callers.
Federated SQL must be read-only. An expensive read can still consume the source’s resources. A broad privileged credential also exposes more data than the report needs. Keep the database role limited even though the product rejects DML through this query path.
Use a reviewed remote query shape. If an application varies the dates or customer, validate and safely construct that remote statement. A BigQuery value parameter doesn’t bind values inside a quoted PostgreSQL SQL string. Don’t give an ordinary report interaction unrestricted control of the remote SQL text.
Agree on source-side limits with the database owner. PostgreSQL’s statement_timeout only bounds statement execution inside PostgreSQL, and role or database defaults can apply it to new sessions.
Confirm the effective value through the connection itself before relying on it. A changed default doesn’t reach existing sessions. Verify that the connector honors the limit, and separately bound concurrent report requests and retries.
A dashboard refresh can issue several queries at once, and several viewers can repeat them. Count that fan-out. Stagger scheduled refreshes, cap parallel work at the caller, and stop repeated retries when the source is unhealthy. Accept slower report responses when that’s what it takes to stay within the database budget.
Check the read target and freshness
For recurring federation that’s still justified, evaluate separate read capacity. An AlloyDB connection can target a primary or a read instance. Verify the configured target instead of assuming a connection named reporting_pg selects an isolated reader.
A Cloud SQL read replica holds a lagging copy of the primary’s state. Long analytical reads can conflict with replay or add to replication lag.
Monitor replay behavior. Define how old a result may be before the report should refuse it or label it stale.
The query location must match its BigQuery connection location, and the source must be in a supported region for that location. For a single-region query, that means the same region. Check these prerequisites before diagnosing an incompatible location as a performance problem.
Also define which moment the joined result describes. A live operational read joined to yesterday’s warehouse dimension mixes two points in time. If the report needs a reproducible period close, an analytical release may fit better than a live source lookup.
Move the repeated work when its live cost stops earning its place
BigQuery’s on-demand federation charge is based on data returned by the external query, so the bill says nothing about the PostgreSQL work required to produce it. Nor can the maximum-bytes-billed control protect the source: federation doesn’t support it.
Choose an analytical copy when broad reads repeat, dashboard growth makes source demand hard to bound, or source maintenance keeps making the report unavailable. State the allowed data age and how the report behaves when refresh fails. The copy needs ingestion and validation before it can take over those reads.
Before switching, compare representative outputs through both paths. PostgreSQL UUIDs need a supported representation, numerics can exceed BigQuery’s default numeric range, and timestamps with and without time zones map differently. A transfer that changes those values can make a faster report wrong.
Keep federation for the selective exceptions that still need it.
Once the copy has taken over, remove the retired report’s ability to send broad remote queries. Then verify through source evidence that its scheduled reads have stopped.
More in this domain: Operations
Browse allAllocate shared BigQuery reservation costs without inventing query prices
Charge purchased BigQuery capacity to the teams that requested it. Divide agreed shared costs by measured usage.
Plan regional recovery for a single-region service
Rehearse a full restore outside the primary region. Consider a warm standby if restoration can't meet the recovery time or data-loss target.
Cloud SQL vs. AlloyDB for PostgreSQL: what earns the migration
Start with Cloud SQL for a modest PostgreSQL application. Test AlloyDB when its read scaling, storage, or columnar engine addresses a measured need.
An alert is not a notification
Send a notification when awareness is enough. Create an operational alert when someone owns a decision.
Why alert feedback should be structured first
Collect a structured response first and leave room for an optional note.
Related patterns
AlloyDB managed connection pooling: when we'd trust it over PgBouncer
Replace PgBouncer with AlloyDB managed pooling when the application fits its pooling mode and operators can still diagnose waits and reconnects.
Managed connection pooling in Cloud SQL: when it helps and when it complicates things
Try Cloud SQL managed pooling when connection bursts exhaust sessions while PostgreSQL still has capacity to do the work.
How we diagnose and fix a "too many connections" incident for Cloud Run + Postgres
When PostgreSQL runs out of connections, limit new connection attempts and capture session state before it disappears.
Why Cloud Run + Postgres needs a connection budget
Budget PostgreSQL connections across the whole Cloud Run fleet.