Skip to main content

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:

RequirementWarehouseAPI Serving
Latency2-10 seconds< 5 ms
ConcurrencyLow (10-100)High (1000s)
Query PatternFew large queriesMany small queries
FrequencyPeriodicContinuous

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) or AT (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, or MERGE INTO). A failed refresh changes nothing.
  • The serving template (template-source) reads {{cache.catalog}}.{{cache.schema}}.{{cache.table}}. The schema defaults to cache.
  • A request never triggers a refresh. Refreshes come from warm-up at startup, the scheduler (on by default), flapii cache refresh, write endpoints with invalidate-on-write / refresh-on-write, or a one-shot flapi cache refresh in a pipeline.
  • Without template-file, the serving SQL itself is materialised (a full refresh every time, startup warns). Always declare template-file.

Choosing a Refresh Mode​

There is no mode: or strategy: key. The mode is inferred from cursor and primary-key:

You declareModePopulate templateGood for
no cursorfullCREATE OR REPLACE TABLE … AS SELECT …small tables, anything cheap to recompute
cursor onlyappendINSERT rows past the watermarkappend-only data: events, logs, readings
cursor + primary-keymergesingle-action MERGE on the keymutable 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_at cursor.
  • Rows are deleted → flAPI does not detect deletes. Model them in the data (an is_deleted flag or deleted_at column 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 scheduleDaily costMonthly 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: true over 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-empty on 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-snapshots keeps the N most recent snapshots; retention.max-snapshot-age drops snapshots older than e.g. 14d. Set them per cache or once under ducklake.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 future 400 snapshot_in_future. rollback-window and delete-handling are deprecated and have no effect.
  • The audit table <catalog>.audit.sync_events records every refresh: sync_type (full, append, merge, or a maintenance run: garbage_collection, compaction, drop_table), status (success or error), message, rows_affected, snapshot_id and duration_ms. Read it with flapii 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​

🍪 Cookie Settings