Connecting to BigQuery
This guide uses the bigquery extension, a DuckDB community extension. Thanks to its contributors.
BigQuery bills every query. An API that sends each request to BigQuery pays for each request, and waits seconds for each answer. flAPI's answer is to query BigQuery on a schedule, keep the result in a local DuckLake cache, and serve requests from the cache.
The extension
bigquery is a DuckDB community extension: built by third parties and published, signed by DuckDB, in its community repository. How you get it depends on how you run flAPI:
| You run | bigquery |
|---|---|
The -runtime Docker image (ghcr.io/datazoode/flapi:<tag>-runtime) | pre-installed |
The default Docker image, a release archive, or pip install flapi-io | downloaded by INSTALL on first start |
| A host without network access | pre-install with flapi extensions install (see Extensions) |
Setup
project-name: marketing-api
template:
path: ./sqls
environment-whitelist:
- '^GCP_PROJECT$'
connections:
lakehouse:
init: |
INSTALL bigquery FROM community;
LOAD bigquery;
ATTACH 'project={{env.GCP_PROJECT}}' AS bq (TYPE bigquery, READ_ONLY);
properties:
dataset: analytics
initruns once, at startup.{{env.GCP_PROJECT}}is substituted there because environment variables are substituted in the whole YAML file;{{ conn.* }}is not rendered insideinit.propertiesare what templates see as{{{ conn.* }}}. Here a template reads tables asbq.{{{ conn.dataset }}}.<table>.- The
ATTACHmakes BigQuery datasets look like schemas.bigquery_scan('project.dataset.table')reads one table without attaching, andbigquery_query('project', 'SELECT ...')runs SQL in BigQuery as written.
Authentication
The extension uses Google Application Default Credentials:
# Service account (production)
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json
# Your own account (development)
gcloud auth application-default login
The extension reads GOOGLE_APPLICATION_CREDENTIALS itself, so it needs no whitelist entry, and flAPI needs no credentials property. On Google Cloud, a metadata server provides the credentials. Give the service account read access to the datasets you serve and nothing more.
Live query or cache?
Live query
url-path: /orders
total-count: false # no extra COUNT(*) query per page
request:
- field-name: since
field-in: query
required: true
validators:
- type: date
template-source: orders.sql
connection: [lakehouse]
SELECT order_id, customer_id, total, order_date
FROM bq.{{{ conn.dataset }}}.orders
WHERE order_date >= '{{{ params.since }}}'
ORDER BY order_date DESC
since is outside any section and has a date validator, so it is bound as a parameter; the validator also rejects anything that is not a date with 400 before any SQL is rendered.
A paginated GET runs your query and, when the page is full, a SELECT COUNT(*) over it for total_count: two billed queries per page. total-count: false drops the count query for clients that only page forward.
With a cache (recommended)
The populate template runs on the schedule and writes the cache table; the serving template reads only the cache.
url-path: /campaigns
request:
- field-name: country
field-in: query
required: false
validators:
- type: string
regex: '^[A-Z]{2}$'
template-source: campaigns.sql
connection: [lakehouse]
cache:
enabled: true
table: campaigns_cache
schema: analytics
schedule: 60m
template-file: campaigns_cache.sql
CREATE OR REPLACE TABLE {{cache.catalog}}.{{cache.schema}}.{{cache.table}} AS
SELECT campaign_id, campaign_name, country,
SUM(clicks) AS total_clicks,
SUM(revenue) AS total_revenue
FROM bq.{{{ conn.dataset }}}.campaigns
WHERE date >= CURRENT_DATE - INTERVAL 30 DAY
GROUP BY ALL
SELECT *
FROM {{cache.catalog}}.{{cache.schema}}.{{cache.table}}
WHERE 1=1
{{#params.country}}
AND country = '{{{ params.country }}}'
{{/params.country}}
ORDER BY total_revenue DESC
The project needs a ducklake: block for the cache catalog; see Caching.
Incremental refresh
For a large append-only table, declare a cursor and load only the rows past the watermark. The first run has no watermark, so the template must also create the table:
cache:
enabled: true
table: events_cache
schedule: 15m
cursor:
column: event_ts
type: timestamp
template-file: events_cache.sql
{{^cache.previousSnapshotTimestamp}}
CREATE OR REPLACE TABLE {{cache.catalog}}.{{cache.schema}}.{{cache.table}} AS
SELECT event_id, user_id, event_type, event_ts
FROM bq.{{{ conn.dataset }}}.events
WHERE event_ts >= CURRENT_DATE - INTERVAL 90 DAY;
{{/cache.previousSnapshotTimestamp}}
{{#cache.previousSnapshotTimestamp}}
INSERT INTO {{cache.catalog}}.{{cache.schema}}.{{cache.table}}
SELECT event_id, user_id, event_type, event_ts
FROM bq.{{{ conn.dataset }}}.events
WHERE event_ts > TIMESTAMP '{{{cache.previousSnapshotTimestamp}}}';
{{/cache.previousSnapshotTimestamp}}
With a cursor, {{cache.previousSnapshotTimestamp}} is max(event_ts) over the rows already cached. Filter on the table's partitioning column in BigQuery, so each refresh scans only the new partitions.
Cost comparison
An illustrative scenario. Check BigQuery's current pricing for your region and edition before you rely on the numbers.
Requirements: 10,000 API calls per day; each query scans data worth $0.05.
Live (every call queries BigQuery):
10,000 queries × $0.05 = $500/day ≈ $15,000/month
(up to twice that with the COUNT(*) per full page)
Response time: seconds
Cached (hourly refresh):
24 refreshes × $0.05 = $1.20/day ≈ $36/month
Response time: milliseconds, from the local cache
Best practices
- Cache anything called often. Use a live query only when the data must be current and traffic is low.
- Pre-aggregate in the populate template. A cache of daily totals per country is smaller and faster than a copy of the raw table.
- Match the schedule to the business. Every 15 minutes for operational dashboards, hourly for reporting, daily for analytics.
- Filter on partition columns in every populate template.
- Quote names, bind values.
{{{ conn.dataset }}}is pasted as text from your config; request values belong in bound parameters or behind strict validators.
Troubleshooting
- The server does not start, error at the
ATTACH. The extension could not authenticate or the project does not exist. CheckGOOGLE_APPLICATION_CREDENTIALSin the server's environment and the service account's roles. INSTALL bigqueryfails on an offline host. Pre-install it withflapi extensions install --config flapi.yaml --dir <dir>and pointFLAPI_EXTENSION_DIRECTORYat that directory.- A request returns
500with only arequest_id. The BigQuery error is in the server log under that id; see Observability. - Costs higher than expected. Look for live endpoints with
total-counton, and for populate templates without a partition filter.
Next steps
- Caching Setup: refresh modes, schedules, the
ducklake:block - BigQuery Caching example: a complete project
- Connections Overview: live vs cache, failure modes
- Snowflake: the other billed warehouse