Caching Strategy
flAPI's caching layer is built on DuckLake, a snapshot-based table format over DuckDB. A cache is not a per-request memo with a TTL: it is a table that a populate template writes on a schedule and that your endpoint's serving template reads on every request.
Think of a DuckLake cache like a versioned ledger: every refresh commits a new snapshot, the latest snapshot serves the API in milliseconds, and old snapshots are pruned by a retention policy you control.
This page explains why and when. The step-by-step setup, with runnable examples, is the Caching Setup guide.
Why Cache in DuckLake?
Data warehouses like BigQuery, Snowflake, and SAP are optimized for analytical workloads, not API serving:
| Requirement | Warehouse | API Serving |
|---|---|---|
| Latency | 2-10 seconds | < 5 ms |
| Concurrency | Low (10-100) | High (1000s) |
| Query Pattern | Few large queries | Many small queries |
| Frequency | Periodic | Continuous |
A DuckLake cache gives you warehouse-quality SQL with serving-tier latency, plus:
- Snapshot isolation: readers always see a whole snapshot, never a half-finished refresh.
- Predictable cost: the warehouse is queried once per schedule, not once per request.
- Time travel: a serving template can read any retained snapshot with
AT (VERSION => n)orAT (TIMESTAMP => t). - Three refresh modes: full, append and merge, inferred from your config.
- Retention: old snapshots expire by count or age, and their files are deleted.
How a Cache Works
- The populate template (
cache.template-file) runs verbatim, in one transaction, and must write the table itself (CREATE OR REPLACE TABLE … AS,INSERT INTO, orMERGE INTO). A failed refresh changes nothing. - The serving template (
template-source) reads{{cache.catalog}}.{{cache.schema}}.{{cache.table}}. The schema defaults tocache. - A request never triggers a refresh. Refreshes come from warm-up at startup, the scheduler (on by default),
flapii cache refresh, write endpoints withinvalidate-on-write/refresh-on-write, or a one-shotflapi cache refreshin a pipeline. - Without
template-file, the serving SQL itself is materialised (a full refresh every time, startup warns). Always declaretemplate-file.
Choosing a Refresh Mode
There is no mode: or strategy: key. The mode is inferred from cursor and primary-key:
| You declare | Mode | Populate template | Good for |
|---|---|---|---|
no cursor | full | CREATE OR REPLACE TABLE … AS SELECT … | small tables, anything cheap to recompute |
cursor only | append | INSERT rows past the watermark | append-only data: events, logs, readings |
cursor + primary-key | merge | single-action MERGE on the key | mutable rows: customers, orders |
The template sees the mode as {{params.cacheMode}} and the watermark as {{cache.previousSnapshotTimestamp}}, which is max(<cursor>) over the cached rows. Incremental templates need a {{^cache.previousSnapshotTimestamp}} branch that builds the table from the whole source on the first run (and after --full).
Start with full. Go incremental when a refresh gets too slow, and pick the mode by what your source can tell you:
- Rows are only ever added → append. Watch for late rows below the watermark.
- Rows change → merge on a primary key, with an
updated_atcursor. - Rows are deleted → flAPI does not detect deletes. Model them in the data (an
is_deletedflag ordeleted_atcolumn that bumps the cursor) and handle them in the populate template, or rebuild with a full refresh. The setup guide shows both patterns.
Cost Math
An illustrative example, not a price quote: a 50,000-requests/day workload against BigQuery, assuming $0.05 per refresh query (a 10 GB scan; check your own pricing), for one instance that refreshes:
| Refresh schedule | Daily cost | Monthly cost |
|---|---|---|
| Every 5 minutes | $14.40 | $432 |
| Every 15 minutes | $4.80 | $144 |
| Every hour | $1.20 | $36 |
| Every 6 hours | $0.20 | $6 |
| Daily | $0.05 | $1.50 |
Direct access for the same workload costs $2,500/day. Caching trades freshness for cost in a predictable way.
Two things multiply that bill:
- Replicas. N instances that each keep their own cache run N schedulers and N times the populate queries. One writer with read-only replicas (
ducklake.read-only: trueover a shared catalog) keeps it at one. - Restarts. With the default
warmup: always, every restart and cold start re-runs every populate query.warmup: if-emptyon persistent storage serves what is already there.
As a rule of thumb: warehouse queries per day ≈ (instances that refresh) × 24 h / schedule per cache, plus restarts × caches when warmup is always. Disk ≈ table size × retained snapshots for a full refresh; an incremental refresh adds only its delta.
Snapshots, Retention and Audit
retention.keep-last-snapshotskeeps the N most recent snapshots;retention.max-snapshot-agedrops snapshots older than e.g.14d. Set them per cache or once underducklake.retention.- Retention runs after every refresh (and on
flapii cache gc <path>): it expires old snapshots, then deletes the data files no kept snapshot can still see. Without a policy, snapshots and files grow forever. - Retained snapshots are exactly what time travel can reach. An expired or unknown snapshot answers
404 snapshot_not_found; a timestamp in the future400 snapshot_in_future.rollback-windowanddelete-handlingare deprecated and have no effect. - The audit table
<catalog>.audit.sync_eventsrecords every refresh:sync_type(full,append,merge, or a maintenance run:garbage_collection,compaction,drop_table),status(successorerror),message,rows_affected,snapshot_idandduration_ms. Read it withflapii cache audit <path>.
Staleness Is Silent
A failing refresh does not take the endpoint offline. It keeps serving the last snapshot, and /health answers 200 with "status":"degraded" and a stale list, so a load balancer will not notice. Watch data_age_seconds per cache in flapii metrics and alert when it exceeds about twice the schedule. The setup guide lists every signal.
When to Use DuckLake Caching
Ideal
- High-frequency reads of moderately fresh data (dashboards, AI tool calls).
- Backends with per-query cost (BigQuery, Snowflake, SAP).
- Workloads that benefit from snapshot isolation (audit, reproducibility).
Not Ideal
- Sub-second freshness: refresh overhead is too high.
- Single-query workloads: no amortization.
- Datasets that don't fit on the flAPI host's disk (or object storage behind
ducklake.data-path). - Per-caller results that depend on who asks: the cache table is shared by every request.
Next Steps
- Caching Setup Guide: build a cache step by step, then run it in production
- DuckLake Refresh Modes: the three modes side by side
- How It Works: the 3-step flAPI process
- Architecture Deep Dive: where the cache sits in the server
- BigQuery Example: a complete caching implementation