Reviewer · Caching
Bounded, validated caching
Treat every cache as an optimization that must never compromise correctness or memory safety. When adding or extending a cache: 1. Bound its growth. Caches that key on every tenant/window/run (or that extend TTL via a "refresh" instead of re-validating against the source) can grow unbounded and risk OOM, e.g. a per-tenant map that keeps every scanned index...
Treat every cache as an optimization that must never compromise correctness or memory safety. When adding or extending a cache:
-
Bound its growth. Caches that key on every tenant/window/run (or that extend TTL via a “refresh” instead of re-validating against the source) can grow unbounded and risk OOM, e.g. a per-tenant map that keeps every scanned index run in memory for the life of the process. Always impose a hard limit (entry count or byte size), expose a metric for current size, and provide a way to disable the cache. Avoid “refresh” operations that merely extend TTL without re-checking the source — they let stale entries live indefinitely and mask real staleness (e.g. a lagging index that would otherwise self-correct on expiry).
-
Don’t let a cache hit skip validation that the non-cached path performs. If a miss normally checks existence, length, or freshness of the underlying data, a hit must do the same (or the check must be proven unnecessary). This matters most before destructive or correctness-critical operations — read straight from the source (bypass the cache) rather than trust a value that may be seconds-to-minutes stale, e.g. don’t rely on a cached file listing when deciding what to delete after compaction.
-
Make the cache key capture everything that affects the cached value. If a response’s content depends on a mode/feature flag, header, or other request attribute, that attribute must be part of the cache key — otherwise a narrowed or degraded result computed under one mode gets served to requests in a different mode. When in doubt, either include the flag in the key or skip caching for that path entirely. Similarly, prefer deriving cache lookup inputs from a single upstream source of truth rather than recomputing them downstream, to avoid divergent results (“poisoning”) across rollout boundaries.
Example of a key that silently drops a correctness-relevant input:
// Bad: cache key ignores the request mode, so a narrowed/dry-run result
// can be served later to a live request with different semantics.
key := fmt.Sprintf("%s:%s:%d:%d:%d", tenant, query, step, interval, split)
// Good: encode every input that changes the cached value's meaning.
key := fmt.Sprintf("%s:%s:%d:%d:%d:%s", tenant, query, step, interval, split, mode)