Snowflake Integration
This guide uses the snowflake extension, a DuckDB community extension. Thanks to its contributors.
Snowflake bills warehouse time. An API that wakes a warehouse for every request pays for that, and waits for it. flAPI's answer is the same as for BigQuery: query Snowflake on a schedule, keep the result in a local DuckLake cache, and serve requests from the cache.
What you need
- A Snowflake account and a read-only user (see Security).
- The
snowflakeextension. A community extension, installed by theinitbelow on first start (installed_from: community, signed by DuckDB). - The ADBC Snowflake driver, a native library you install on the host yourself (
libadbc_driver_snowflake.soon Linux). Neither flAPI nor any flAPI image ships it.
With flAPI v26.11.25 the extension installs and the secret below is accepted. Without the driver, startup stops at the ATTACH with IO Error: ADBC Snowflake driver (...) not found, followed by the places it searched. Querying a live account is not verified; check the table names against your account.
Setup
project-name: sales-api
template:
path: ./sqls
environment-whitelist:
- '^SF_(ACCOUNT|USER|PASSWORD)$'
connections:
dwh:
init: |
INSTALL snowflake FROM community;
LOAD snowflake;
CREATE OR REPLACE SECRET sf_dwh (TYPE snowflake, ACCOUNT '{{env.SF_ACCOUNT}}',
USER '{{env.SF_USER}}', PASSWORD '{{env.SF_PASSWORD}}',
DATABASE 'ANALYTICS', WAREHOUSE 'COMPUTE_WH');
ATTACH '' AS sf (TYPE snowflake, SECRET sf_dwh, READ_ONLY);
export SF_ACCOUNT=xy12345.us-east-1 SF_USER=flapi_reader SF_PASSWORD='...'
flapi -c flapi.yaml
initruns once, at startup; theATTACHconnects right away, so a wrong account or password stops the server.{{env.NAME}}is the only substitution that works, and every name must matchtemplate.environment-whitelist.${SF_PASSWORD}stays literal text.initis not a template:{{ conn.* }}inside it is not rendered.CREATE SECRETkeeps the password in memory. Do not writeCREATE PERSISTENT SECRET: it stores the password unencrypted in~/.duckdb/stored_secrets.- Rotating the password needs a restart, because only
initcreates the secret.
Serve from a cache
url-path: /sales/daily
request:
- field-name: category
field-in: query
required: false
validators:
- type: string
regex: '^[A-Za-z _-]{1,50}$'
template-source: daily_sales.sql
connection: [dwh]
cache:
enabled: true
table: daily_sales_cache
schedule: 6h
template-file: daily_sales_cache.sql
CREATE OR REPLACE TABLE {{cache.catalog}}.{{cache.schema}}.{{cache.table}} AS
SELECT sale_date, product_category,
SUM(revenue) AS total_revenue,
COUNT(DISTINCT customer_id) AS unique_customers
FROM sf.PUBLIC.SALES
WHERE sale_date >= CURRENT_DATE - INTERVAL 90 DAY
GROUP BY ALL
SELECT *
FROM {{cache.catalog}}.{{cache.schema}}.{{cache.table}}
WHERE 1=1
{{#params.category}}
AND product_category = '{{{ params.category }}}'
{{/params.category}}
ORDER BY sale_date DESC
The serving template reads only the cache table, so a request never wakes the warehouse. The project needs a ducklake: block; see Caching. No LIMIT in the serving template: GET endpoints are paginated, and ?limit= / ?offset= belong to the pagination.
Incremental refresh
For mutable rows, declare a primary-key and a cursor (merge mode). The first run has no watermark, so the template bootstraps the table:
cache:
enabled: true
table: orders_cache
schedule: 15m
primary-key: [order_id]
cursor:
column: updated_at
type: timestamp
template-file: orders_cache.sql
{{^cache.previousSnapshotTimestamp}}
CREATE OR REPLACE TABLE {{cache.catalog}}.{{cache.schema}}.{{cache.table}} AS
SELECT order_id, customer_id, status, total, updated_at
FROM sf.PUBLIC.ORDERS;
{{/cache.previousSnapshotTimestamp}}
{{#cache.previousSnapshotTimestamp}}
MERGE INTO {{cache.catalog}}.{{cache.schema}}.{{cache.table}} AS t
USING (
SELECT order_id, customer_id, status, total, updated_at
FROM sf.PUBLIC.ORDERS
WHERE updated_at >= TIMESTAMP '{{{cache.previousSnapshotTimestamp}}}'
) AS s
ON t.order_id = s.order_id
WHEN MATCHED THEN UPDATE SET customer_id = s.customer_id, status = s.status,
total = s.total, updated_at = s.updated_at
WHEN NOT MATCHED THEN INSERT *;
{{/cache.previousSnapshotTimestamp}}
Tiered schedules
Give each endpoint the freshness it needs, and no more:
# sqls/sales_today.yaml - hot data
cache: {enabled: true, table: sales_today, schedule: 5m, template-file: sales_today_cache.sql}
# sqls/sales_monthly.yaml - warm data
cache: {enabled: true, table: sales_monthly, schedule: 6h, template-file: sales_monthly_cache.sql}
# sqls/sales_yearly.yaml - cold data
cache: {enabled: true, table: sales_yearly, schedule: 7d, template-file: sales_yearly_cache.sql}
Cost comparison
An illustrative scenario. Snowflake credit prices depend on edition, region and contract; plug in your own numbers.
Scenario: 10,000 API calls per day, an X-Small warehouse.
Live (every call reaches the warehouse): the warehouse barely suspends, so it bills most of the day, and every call waits for it to resume after an idle period.
Cached (4 refreshes a day, 5 minutes each):
4 × 5 min = 20 warehouse minutes per day
API serving: from the local cache, no warehouse time
The saving is the difference between a warehouse that runs all day and one that runs twenty minutes.
Best practices
- Use the smallest warehouse that finishes the refresh in acceptable time, set in the secret's
WAREHOUSE. - Pre-aggregate in the populate template, or in a Snowflake view the populate template reads.
- Filter by time in every populate template, so a refresh scans only recent data.
- Select only the columns you serve.
- Schedule refreshes for when the data changes, not more often.
Security
Read-only user
-- In Snowflake
CREATE ROLE FLAPI_READER;
GRANT USAGE ON WAREHOUSE COMPUTE_WH TO ROLE FLAPI_READER;
GRANT USAGE ON DATABASE ANALYTICS TO ROLE FLAPI_READER;
GRANT USAGE ON SCHEMA ANALYTICS.PUBLIC TO ROLE FLAPI_READER;
GRANT SELECT ON ALL TABLES IN SCHEMA ANALYTICS.PUBLIC TO ROLE FLAPI_READER;
GRANT SELECT ON FUTURE TABLES IN SCHEMA ANALYTICS.PUBLIC TO ROLE FLAPI_READER;
CREATE USER flapi_reader PASSWORD = '...' DEFAULT_ROLE = FLAPI_READER;
GRANT ROLE FLAPI_READER TO USER flapi_reader;
Keep READ_ONLY on the ATTACH as well.
Network policy
-- In Snowflake: only flAPI's egress addresses may log in as this user
CREATE NETWORK POLICY flapi_access
ALLOWED_IP_LIST = ('203.0.113.10/32', '198.51.100.20/32');
ALTER USER flapi_reader SET NETWORK_POLICY = flapi_access;
One process per trust boundary
Every template of a flAPI process can use every secret and attachment of that process. If two teams must not read each other's Snowflake data, run two flAPI processes with two users.
Troubleshooting
ADBC Snowflake driver (...) not foundat startup. Install the driver on the host; the message lists where it looked.- Startup stops at the
ATTACHwith an authentication error. Check the three environment variables in the server's environment, and that the account identifier includes the region where Snowflake requires it. environment variable SF_PASSWORD ... not whitelisted. Add a matching pattern undertemplate.environment-whitelist.- Slow refreshes. Pre-aggregate in a Snowflake view, filter by date, or move to an incremental cursor.
- High costs despite caching. Look for endpoints that are not cached, and for schedules shorter than the data's real change rate.
Migration from direct access
- Add flAPI in front with the connection above and live endpoints, to get the API shape right.
- Add a cache to every endpoint that is called often (
schedule,template-file). - Watch the warehouse. In Snowflake,
SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORYfiltered onUSER_NAME = 'FLAPI_READER'shows what flAPI still sends.
Next steps
- Caching Setup: refresh modes and schedules
- BigQuery: the other billed warehouse
- Connections Overview: live vs cache, failure modes
- DuckDB Snowflake Extension: upstream docs