Skip to content
David Ciulla edited this page Nov 7, 2026 · 2 revisions

Cache

Laravex provides a unified cache API backed by a GenServer in Laravex.Cache.Manager. Four store drivers are supported: array, file, database, and redis.


Configuration

Cache settings live in config/cache.exs. The active store is selected by the cache.default key (overridable by CACHE_STORE):

%{
  "default" => Laravex.Env.get("CACHE_STORE", "database"),
  "prefix"  => Laravex.Env.get("CACHE_PREFIX", "laravex-cache-"),
  "stores" => %{
    "array"    => %{"driver" => "array"},
    "file"     => %{"driver" => "file"},
    "database" => %{"driver" => "database"},
    "redis"    => %{"driver" => "redis", "connection" => "cache"}
  }
}
Driver Description
array In-process ETS-backed memory store. Data is lost when the application restarts.
file Writes Erlang term binaries under storage/framework/cache/data/. Key names are hex-encoded.
database Reads and writes to the cache table (created by the included migration). Falls back to array if the table does not exist.
redis Stores entries in Redis via RESP over :gen_tcp. Keys are prefixed with cache.prefix.

Basic Usage

The Laravex.Cache.Manager module is the cache facade. All key arguments are automatically coerced to strings.

Storing Values

# Store for N seconds
Laravex.Cache.Manager.put("key", "value", 3600)

# Store forever (no TTL)
Laravex.Cache.Manager.put("key", "value")
Laravex.Cache.Manager.forever("key", "value")

# Only store if the key is missing; returns true if stored, false if it already existed
Laravex.Cache.Manager.add("key", "value", 600)

Storing Multiple Values

# Store a map of key/value pairs with an optional shared TTL
Laravex.Cache.Manager.put_many(%{"a" => 1, "b" => 2}, 300)

Retrieving Values

# Returns nil when the key is missing or expired
Laravex.Cache.Manager.get("key")

# Returns the default when the key is missing or expired
Laravex.Cache.Manager.get("key", "default")

# Retrieve and immediately remove (pull)
value = Laravex.Cache.Manager.pull("key")
value = Laravex.Cache.Manager.pull("key", "default_if_missing")

# Retrieve multiple keys at once
Laravex.Cache.Manager.many(["key_a", "key_b", "key_c"])
# => %{"key_a" => value_or_nil, "key_b" => value_or_nil, …}

# Check existence
Laravex.Cache.Manager.has?("key")   # => true | false

Removing Values

# Delete a single key
Laravex.Cache.Manager.forget("key")

# Clear the entire cache
Laravex.Cache.Manager.flush()

Incrementing / Decrementing

# Increment by 1 (or by amount)
Laravex.Cache.Manager.increment("visitors")
Laravex.Cache.Manager.increment("visitors", 5)

# Decrement by 1 (or by amount)
Laravex.Cache.Manager.decrement("seats")
Laravex.Cache.Manager.decrement("seats", 2)

If the key does not exist the starting value is treated as 0 before the operation is applied.


Remember

remember/3 retrieves an item from the cache; if the item does not exist, it executes the given closure, stores the result, and returns it.

users = Laravex.Cache.Manager.remember("users", 3600, fn ->
  App.Models.User.all()
end)

If the value is already cached and has not expired, the closure is not called.

# remember_forever — never expires
config_map = Laravex.Cache.Manager.remember_forever("app_config", fn ->
  App.Config.load_all()
end)

Flexible Cache (Stale-While-Revalidate)

flexible/3 implements a stale-while-revalidate strategy: return the cached value immediately while asynchronously refreshing it in the background once it becomes stale.

# Cache is fresh for 60 s, stale-but-served for up to 120 s
Laravex.Cache.Manager.flexible("trending_posts", [60, 120], fn ->
  App.Blog.trending()
end)

Arguments are [fresh_seconds, stale_seconds]. After fresh_seconds the value is served from cache while a background Task refreshes it. After stale_seconds the closure is called synchronously.


Process-Level Memoization

memo/2 caches the result in the current process dictionary — no GenServer round-trip, no serialisation. Useful for per-request values:

# Called multiple times in the same request but computed only once
Laravex.Cache.Manager.memo("current_user_permissions", fn ->
  load_permissions(current_user)
end)

Locks

The lock API provides a lightweight mutex for coordinating access across concurrent requests.

# Create a lock (name, TTL in seconds)
lock = Laravex.Cache.Manager.lock("process_report", 60)

# Try to acquire (returns true if acquired, false if already held)
if Laravex.Cache.Manager.get_lock(lock) do
  # critical section
  Laravex.Cache.Manager.release(lock)
end

# Block until acquired or timeout (seconds); returns true/false
acquired = Laravex.Cache.Manager.block(lock, 10)

Note: The lock implementation uses the cache store internally. With the array or database driver it is not atomic across multiple BEAM processes/nodes — it is a best-effort lock. Redis provides stronger guarantees (single-threaded RESP, SET NX EX).


TTL Reference

TTL is specified in seconds.

Laravex.Cache.Manager.put("token", token, 600)       # 10 minutes
Laravex.Cache.Manager.put("config", map, 3600)       # 1 hour
Laravex.Cache.Manager.put("app_key", key)            # no expiry (forever)

Expired entries are evaluated lazily — they are removed when the key is next read.


Helper Access

The cache/0 helper in Helpers returns Laravex.Cache.Manager:

import Laravex.Support.Helpers

cache().put("featured_posts", posts, 600)
cache().get("featured_posts")
cache().remember("stats", 300, fn -> compute_stats() end)

Database Store

When using the database driver, the cache table must exist. The migration is included at database/migrations/0001_01_01_000001_create_cache_table.ex. Run it with:

./artisan migrate

The cache table has three columns: key, value (Erlang term encoded as Base64), and expiration (Unix timestamp, 0 for no expiry).

If the cache table is missing at runtime, the manager silently degrades to the array driver rather than raising.


Redis Store

When using the redis driver, Laravex connects over plain TCP (:gen_tcp) using the RESP protocol — no Hex dependencies required.

Configure the Redis connection in config/database.exs under the redis key:

# .env
CACHE_STORE=redis
REDIS_HOST=127.0.0.1
REDIS_PORT=6379

Entries are stored as Base64-encoded Erlang terms with an EX TTL passed to SET. Keys are prefixed with cache.prefix (default laravex-cache-).

Known limitations: no TLS, no Cluster, no password auth over the wire in the current transport layer.


Cache in the Task Scheduler

The Task-Scheduling without_overlapping guard uses Laravex.Cache.Manager internally to implement a distributed mutex. The cache key follows the pattern schedule:overlap:{name}.


See Also

Clone this wiki locally