Classic caching has a blind spot: somebody always pays the cold-miss tax first.
LRU, LFU, and short TTL caches are purely reactive:
- Monday, 9:00 AM: Engineers open weekly SLO dashboards, and the first viewer stares at a spinner.
- 1st of the month: Finance kicks off heavy 30-day rollups against a completely cold cache.
- 2:00 AM alert: The on-call responder drills through p99 latency, DB pool wait time, and pod restarts — hitting a cold storage scan at every click.
Meanwhile, many data and observability systems already record a query audit log: who ran what, when, and how long it took.
The obvious question is: instead of waiting for a miss, how do you predict what users are about to ask for and warm the cache ahead of them?
When I sat down to design this, the three most obvious approaches each had clear production trade-offs:
-
Caching (or auto-refreshing) the "last used" query (wasteful or stale on sliding windows):
- Plain last-used caching still leaves the first viewer cold after any idle gap (overnight, weekends, or monthly reports) — and in time-series systems where queries ask for
[now - 1h, now], the exact cache key shifts every few seconds, turning "the same chart" into a cache miss two minutes later. - Refresh-ahead on last-used queries (continuously re-running recently seen queries in the background) fixes the sliding window, but can't tell a daily standup dashboard apart from a one-off ad-hoc query — so it burns backend CPU refreshing tabs the user already closed, while still failing to anticipate the next chart they haven't clicked yet.
- Plain last-used caching still leaves the first viewer cold after any idle gap (overnight, weekends, or monthly reports) — and in time-series systems where queries ask for
Static cron warmers (too rigid): Replaying top historical queries on a fixed timer is simple, but brittle. When a team edits a dashboard, month-end arrives, or an incident starts, a static schedule keeps warming yesterday's queries while missing what users need right now.
-
Sending audit logs straight to an LLM (too costly and risky):
- Calling an LLM every minute to rediscover repeating calendar habits wastes tokens and adds seconds of latency.
- Letting an LLM synthesize raw SQL or PromQL risks syntax errors — or worse, accidental high-cardinality queries that overload storage.
- Without a feedback loop, any predictor silently degrades as user behavior shifts, turning prefetching into background load amplification.
While working on observability tooling, I wanted to build an engine-agnostic predictive cache — an architecture you can drop in front of any PromQL, ClickHouse, DuckDB, or SQL analytics engine.
Below is the architecture that came out of it: fast online math for routine habits, a closed-menu LLM for incidents, and a control loop that throttles and re-learns when accuracy drops.
Classic Caching vs. Intelligent Prefetching
| Dimension | Classic Cache (Last-Used / Refresh-Ahead / Cron) | Intelligent Self-Learning Prefetcher |
|---|---|---|
| Trigger | Reactive on last query or fixed timer | Predictive (calendar rhythms + next-click chains + live events) |
Sliding [now - 1h] windows | Either misses as now advances or blindly refreshes closed tabs | Bucket-aligned warming only when a query is actually predicted |
| What gets prioritized | Most recently or frequently fetched | Highest expected latency saved (P(needed) × query_cost) |
| When habits change | Serves misses or warms stale queries | Detects hit-rate drop, throttles itself, re-learns, validates in shadow mode |
| During an outage | Blind to alerts and deployments | Event LLM wakes up on alerts/deploys and warms likely drill-downs |
Architecture: Split Habits from Surprises (The Two-Brain Hybrid)
Routine human schedules and surprise production incidents have completely different shapes. Rather than forcing one model to handle both, split prediction into two specialized brains behind a single safety-bounded executor:
- Brain 1 (Fast Habit Engine, pure Go, $0 token cost): Runs every few minutes (and on live clicks). Learns time-of-day, day-of-week, month-start/month-end spikes, and next-click chains in milliseconds.
- Brain 2 (Event LLM, pluggable local or cloud): Sleeps during normal traffic. Wakes up only on non-routine events — an alert firing, a deployment, an anomalous first query, or a sudden drop in Brain 1's hit rate.
1. Turn Raw Audit Logs into Canonical Templates
Raw query logs are noisy. Two users viewing a "Last 1 Hour" chart ten seconds apart send different start and end timestamps, different whitespace, and sometimes reordered filters.
Before hashing or storing audit metadata, normalize every query into a canonical template:
- Parse the AST (e.g., PromQL or SQL AST): sort filter predicates/label matchers deterministically so
{b="2", a="1"}and{a="1", b="2"}become identical. - Snap timestamps into relative window buckets: strip absolute
start/endtimes and snapend - startto canonical buckets (60s,300s,900s,3600s,21600s,86400s,604800s). - Scrub high-cardinality & sensitive literals: replace UUIDs and long hex trace IDs with
<ID>, and redact tokens/emails so templates generalize across sessions and stay safe for prompts.
template := normalizeQueryTemplate(rawQuery) windowSec := snapWindowSec(end.Sub(start)) templateHash := sha256Hex16(endpoint, template, windowSec, stepSec) Also align incoming and prefetched query timestamps to a time-bucket grid (15s for <= 1h windows, 60s for <= 24h, 300s for > 24h). Without bucket alignment, a prefetch executed at 09:00:02 will miss a user request arriving at 09:00:09.
Compliance tip: If your audit log is append-only or cryptographically hash-chained, keep high-churn ML feedback (
issued,hit,expired,skipped) in a separate short-TTL table or log stream rather than mutating audit rows.
2. Brain 1: Online Math Beats LLMs for Routine Habits
You don't need a neural network or an LLM to learn that Monday mornings and month-ends look different from Saturday nights. Brain 1 builds a compact per-tenant state from four signals:
- Slot weights (
day_of_week : hour_of_day): captures daily standups and weekly reviews. - Calendar boundary multipliers:
monday,weekend,month_start(days 1–3), andmonth_end(last 3 days of the month). - Exponential recency decay: every historical execution is weighted by: >
w = 2^(-Δt / H)
With a default half-life H = 14 days, last week matters far more than a month ago — and shrinking H gives us an instant "forget old habits" knob when drift occurs.
- 1st-order Markov transitions ("Next-Click" prediction): tracks
P(query B within 60s | query A). Even during an unscheduled investigation, the moment an engineer runs Query A, Brain 1 immediately prefetches their top likely follow-up queries.
Rank by Expected Latency Saved — Not Popularity
A lightweight health check (up or SELECT 1) might run 1,000 times an hour in 4 ms. Prefetching it wastes cache memory for negligible benefit. Filter out queries below a latency floor (e.g., 50 ms) and rank candidates by expected time saved:
score := probability * tpl.AvgDurationMs * costPenalty A query with a 50% chance of running that takes 900 ms (score = 450) beats a query with a 95% chance that takes 20 ms (score = 19).
3. Brain 2: Closed-Menu Grounding (Zero Hallucinated Queries)
When CheckoutHighLatency pages on-call right after a deployment, calendar history won't help — semantic context matters. That's where an LLM adds real value, provided you constrain its output space.
Instead of asking the LLM to write raw PromQL or SQL, give it a closed menu:
- Input:
- Redacted event context (
trigger: "alert_firing",alert_name,affected_service, calendar flags). - Its last 10 prediction misses (
predictedvs.actualqueries users ran). - Up to 40 real candidate templates (
id, normalized query text,avg_duration_ms) observed historically for that tenant.
- Redacted event context (
- Output: strict JSON picking only candidate
ids from that menu.
var validated []Candidate for _, item := range parsed.Predictions { // Unknown IDs are dropped immediately if tpl, ok := candidateByID[item.ID]; ok { validated = append(validated, tpl) } } Why closed-menu grounding works well in practice:
- No syntax or cardinality accidents: every candidate ID maps to a real, previously observed query.
- Small local models are sufficient: ranking 40 IDs in JSON is much simpler than generating complex query dialects from scratch, so a self-hosted local model handles it reliably (with optional fallback to an external API in hybrid mode).
4. Treat Prefetching as a Closed-Loop Control System
Every predictor eventually drifts — services get renamed, dashboards change, traffic patterns shift. What separates an adaptive prefetcher from a blind cache warmer is continuous feedback and self-throttling.
Tag every prefetched cache entry (prefetched = true):
- First user read (
hitCount == 0) → count a Prefetch Hit and addexecDurationMsto Saved Latency. - TTL expiry or LRU eviction with
hitCount == 0→ count an Expired Unused prefetch and addexecDurationMsto Wasted Work.
Run a lightweight Drift Watcher over rolling 15-minute windows with a four-state machine:
When precision drops:
- Throttle immediately (
DRIFT_THROTTLED): cut the prefetch budget (20 → 5) so inaccurate predictions don't compete with live user traffic. - Re-learn fast: snapshot the current model revision (so rollback is one call), drop Brain 1's decay half-life from
14 daysto2 daysto shed stale habits, and inject the newest misses into Brain 2's prompt memory. - Earn trust back in
SHADOW_RECOVERY: log what the updated model would prefetch and score it against incoming live queries without executing backend queries. Only restore full active warming after two consecutive passing windows (>= 55%precision).
Pair this with a hard backpressure circuit breaker (bounded worker semaphore + checking active backend load before every job). Prefetching is opportunistic — whenever storage is under pressure, prefetching should step aside immediately.
5. Match Storage Tiers to Data Lifecycles (Why Raft KV != L2 Cache)
A predictive prefetcher manages three very different kinds of state, and putting them in the same store creates avoidable friction:
- Evaluated Query Blobs (Lifespan: 30s–5m, High Churn)
- Cache evaluated responses (2–100 KiB JSON/protobuf), never raw unaggregated time-series scans.
- L1: Byte-bounded in-memory LRU inside each query node (capped by total MiB and max entry KiB so one large response cannot evict hundreds of small dashboard panels).
- L2 (for multi-replica clusters): Use an ephemeral in-memory store like Valkey (
--maxmemory-policy allkeys-lru --save "" --appendonly no) rather than a Raft-backed or versioned KV store. Consensus quorum,fsync, and retained version manifests on 30-second disposable blobs add write amplification and share blast radius with control-plane metadata. Valkey is BSD 3-Clause under the Linux Foundation, avoiding licensing issues, and a fail-open RESP2 client (AUTH,PING,GET,SET ... EX) takes ~250 lines of dependency-free Go.
- Learned Model State (Lifespan: Weeks, KB–MB, Low Churn)
- Brain 1's weight table, Brain 2's recent-miss ring, and drift snapshots do belong in a durable, versioned KV store (or versioned disk snapshots) so pods survive restarts and can roll back a bad model update cleanly.
- Tenant & Permission Scope (Lifespan: Every Request)
- Bake
tenant + RBAC visible_scopes + filter_contextdirectly into both the cache key and the predictor'sscope_hash. A prefetcher must evaluate queries through the exact same authorization scope as a live user — never as a global superuser warming a shared key.
- Bake
6. Make the Cache Observable
A prefetcher you can't inspect is impossible to tune. Expose three signals from day one:
- Response headers (
X-Cache-Status: hit_prefetch | hit_normal | miss,X-Cache-Tier: l1 | l2) so the UI can display aPrefetchedpill directly on panels. - Separate Prometheus metrics for
hit_normalvs.hit_prefetch,saved_latency_seconds_totalvs.wasted_latency_seconds_total, and currentdrift_state. - A live stats view showing Brain 1 vs. Brain 2 precision and the top templates saving real wall-clock time.
Wrapping Up
Moving beyond reactive LRU and last-used caching doesn't require handing your query engine over to an unconstrained LLM. A practical division of labor gets you much further:
- Let decayed statistics + Markov transitions handle routine schedule and click-chain traffic at zero token cost.
- Wake up a local-first LLM only when alerts, deployments, or behavioral drift break the routine — and lock it to a closed menu of real query templates.
- Wrap both in a drift-aware control loop with shadow-mode recovery and backpressure circuit breakers so prefetching only spends backend capacity when it is demonstrably helping users.
(If you want to browse a working Apache-2.0 implementation of these components in Go and Python, the code is on GitHub.)


