How the cache works¶
A cache stores the result of expensive work, such as a database query, an API call, or rendered HTML, under a key. Later requests look up the key first. If a value is stored there, the lookup is a hit, and the request skips the work. If not, the lookup is a miss: the request does the work and stores the result for the next request.
This page explains the model behind mankai-cache: the cache component, entries and their lifetime, stores, and when caching helps. To set up the cache, see the mankai-cache reference. To try it, follow Cache your first view fragment.
The cache component¶
The cache is a component in your app's container. You register it once with a provider in
config/providers/cache.rb, and Hanami builds one Mankai::Cache instance and registers it as
"cache". Any class that needs it adds include Deps["cache"], the same way it gets a repository
or the logger.
Because the cache is a component, the code that uses it doesn't know where entries live. The provider chooses the store, the default lifetime, and the serializer. You can change those settings per environment, or replace the cache for one object in a test, without changing the code that caches.
Entries and fetch¶
Each stored value is an entry. An entry holds the encoded value, an optional expiry time, and an
optional version. The cache turns your key into a string, so ["books", 1] becomes "books/1".
With a namespace, it adds a prefix, such as "bookshelf:books/1".
Most code uses fetch, which combines a read and a write. The following diagram shows what fetch
does with a key:
fetch(key) { block }
│
├─ entry found, not expired, same version ──► return the stored value (hit)
│
└─ no entry, expired, or other version ─────► run the block ──► store ──► return the value (miss)
On a hit, the block doesn't run. On a miss, the block's result is stored and returned.
What you can cache¶
The cache stores a copy of the value, encoded by a serializer. The default :marshal serializer
handles plain data, such as strings, numbers, arrays, hashes, and times, and instances of your own
named classes. It can't store the structs that Hanami repositories return, because ROM builds their
classes at runtime. Cache book.to_h instead of book.
Because the cache stores a copy, changing a value that you read doesn't change the cached entry.
How entries stop producing hits¶
A stored entry stops producing hits in the following cases:
- It reaches its expiry time, set with
expires_inorexpires_at. - You read it with a different version. Versions let one key replace its value when the underlying data changes, without deleting anything first.
- The store evicts it to free space, or deletes it during cleanup.
- You delete it.
An expired entry isn't necessarily gone from the store. The cache checks expiry when it reads, and each store decides when to remove old data.
When a popular entry expires, many requests can miss at the same time and all recompute the value.
This is called a cache stampede. The race_condition_ttl option of fetch lets one caller
recompute the value while the others keep getting the old one for a few seconds.
Stores¶
A store keeps the encoded entries; the cache does everything else. mankai-cache includes three stores, and mankai-cache-sql adds a fourth:
- The memory store keeps entries inside one process. Each Puma worker has its own memory store, so a value that one worker writes is invisible to the others. Entries disappear when the process restarts.
- The file store keeps one file per entry. Every process on one machine shares it, and entries survive restarts. It deletes old files only when you run cleanup.
- The SQL store keeps entries in a database table. Every process and server that uses the database shares it, and it deletes the oldest entries in the background.
- The null store keeps nothing, so every read misses. It turns caching off without changing code.
The trade-off is between speed and reach. The memory store is the fastest but the most isolated. The SQL store is shared most widely, but each read is a database query. For a comparison table, see Stores. To pick one, see Choose a store and serializer.
Application caching and HTTP caching¶
mankai-cache caches the work that produces a value or a view fragment inside your app. HTTP caching
is different: the browser or a proxy reuses a whole response. Hanami already supports HTTP caching
on responses with cache_control, expires, and fresh(etag:, last_modified:).
Use HTTP caching when a client can reuse the whole response. Use mankai-cache when the app can reuse an expensive query, API call, or rendered fragment while it builds a response.
When to use the cache¶
The cache helps when all of the following are true:
- The same expensive result is requested repeatedly.
- A slightly old value is acceptable.
- The result isn't specific to one user, or the key includes the user.
Avoid the cache in the following cases:
- The data must be exact on every read.
- The value is cheap to compute.
- One user's private output would be stored under a key that other users read.
- Every write must invalidate the entry, and you can't encode that in the key.
A cache miss must still produce a correct result. The cache is an optimization, not a source of truth.
What's next¶
- Cache data and views: cache values and view fragments, build keys, and invalidate entries.
- Choose a store and serializer: pick a store for each environment.
- mankai-cache reference: every method and setting.