- OCaml 100%
cache #
Immutable in-memory TTL caches with explicit time and entropy inputs. The
optional cache-eio package supplies synchronized shared access, clocks,
randomness and compute-on-miss IO.
The core decides expiry and jitter. Entries written together receive varied
lifetimes to spread recomputation. get returns both the next state and a
value; an expired lookup removes the binding from that next state. Prior
snapshots remain unchanged. Nothing runs in the background.
Installation #
$ opam install cache cache-eio
Pure usage #
let empty = Cache.String.v ~base_ttl:60. ~jitter:0.2 ()
let full = Cache.String.set empty ~now:0. ~sample:0.5 "user:42" "Alice"
let next, value = Cache.String.get full ~now:10. "user:42"
Time is finite seconds from a common clock. A uniform sample in [0,1)
produces a TTL of base_ttl * (1 + jitter * (sample - 0.5)). The defaults
are 60 seconds and width 0.2, giving lifetimes from 54 up to 66 seconds.
base_ttl must be finite and nonnegative; fractional jitter is in [0,2].
A zero TTL expires immediately. Expiry is exact: a binding is live only
while now < expires_at.
remove, gc ~now and clear return fresh snapshots. stats ~now returns
(total, valid) including expired retained entries in the total. Retaining an
old snapshot keeps its entries alive in memory until that snapshot is released.
Shared Eio usage #
See the executable Eio example for shared-cache setup.
Link cache-eio for Cache_eio. Its operations acquire time and entropy and
install the core result under an exclusive mutex. Queries that can expire
entries also take the exclusive lock. get_or_compute runs computation outside
the lock: concurrent misses may each compute, and the last store wins.
Other key types #
Keys use the standard ordered-map contract:
module Int_cache = Cache.Make (Int)
let int_cache () = Int_cache.v ~base_ttl:300. ~jitter:0.1 ()
Cache_eio.Make (Int) supplies the corresponding shared adapter.
Cost #
The core uses persistent Map.Make storage: lookups and updates take
O(log C) key comparisons for C entries; comparison cost depends on key size.
An expiry sweep visits every entry. Snapshot updates share unchanged map
branches. Measure adapter lookup allocation at 100 and 1000 clients with:
$ dune exec bench/expiry.exe
Licence #
ISC. See LICENSE.md.