Skip to main content

Snowflake Integration

Extension credit

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​

  1. A Snowflake account and a read-only user (see Security).
  2. The snowflake extension. A community extension, installed by the init below on first start (installed_from: community, signed by DuckDB).
  3. The ADBC Snowflake driver, a native library you install on the host yourself (libadbc_driver_snowflake.so on Linux). Neither flAPI nor any flAPI image ships it.
What is verified

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​

flapi.yaml
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
  • init runs once, at startup; the ATTACH connects right away, so a wrong account or password stops the server.
  • {{env.NAME}} is the only substitution that works, and every name must match template.environment-whitelist. ${SF_PASSWORD} stays literal text.
  • init is not a template: {{ conn.* }} inside it is not rendered.
  • CREATE SECRET keeps the password in memory. Do not write CREATE PERSISTENT SECRET: it stores the password unencrypted in ~/.duckdb/stored_secrets.
  • Rotating the password needs a restart, because only init creates the secret.

Serve from a cache​

sqls/daily_sales.yaml
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
sqls/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
sqls/daily_sales.sql
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 block
cache:
enabled: true
table: orders_cache
schedule: 15m
primary-key: [order_id]
cursor:
column: updated_at
type: timestamp
template-file: orders_cache.sql
sqls/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​

  1. Use the smallest warehouse that finishes the refresh in acceptable time, set in the secret's WAREHOUSE.
  2. Pre-aggregate in the populate template, or in a Snowflake view the populate template reads.
  3. Filter by time in every populate template, so a refresh scans only recent data.
  4. Select only the columns you serve.
  5. 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 found at startup. Install the driver on the host; the message lists where it looked.
  • Startup stops at the ATTACH with 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 under template.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​

  1. Add flAPI in front with the connection above and live endpoints, to get the API shape right.
  2. Add a cache to every endpoint that is called often (schedule, template-file).
  3. Watch the warehouse. In Snowflake, SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY filtered on USER_NAME = 'FLAPI_READER' shows what flAPI still sends.

Next steps​

🍪 Cookie Settings