Cache data and views¶
This guide shows how to cache the results of expensive work and view fragments, build keys that change when your data changes, and invalidate stale entries. For the full list of methods and options, see the mankai-cache reference.
Before you begin¶
Register the cache provider, as described in
Installation. The examples use Bookshelf as the
app module and assume a books relation with a repos.book_repo repository.
Cache the result of expensive work¶
-
Inject the cache into the class that does the work:
-
Wrap the work in
fetch, with a key and a lifetime in seconds. Return plain data, such as aHash, instead of a struct:
The first call runs the block and stores the result. Later calls return the stored value until it
expires. To expire an entry at a fixed time, pass expires_at: with a Time instead of
expires_in:. To skip storing nil, for example when a record isn't found, pass skip_nil: true.
For why structs can't be cached, see What you can cache.
Use a record as a key¶
To use a struct directly as a key, define cache_key on its struct class. To replace the entry
when the record changes, also define cache_version:
# app/structs/book.rb
module Bookshelf
module Structs
class Book < Bookshelf::DB::Struct
def cache_key = "books/#{id}"
def cache_version = updated_at.to_i
end
end
end
With these methods, cache.fetch(book) { ... } stores the entry under "books/1" for book 1. When
the book's updated_at changes, the version changes, so the next fetch misses and recomputes the
value. If you don't define cache_key, the cache raises Mankai::Cache::InvalidKeyError for a
struct key; build the key from its ID instead, such as ["books", book.id, book.updated_at].
For every type a key can contain, see Keys.
Cache a view fragment¶
-
Include
Mankai::Cache::ViewHelpersinapp/views/helpers.rb: -
Inject the cache into
app/views/context.rb: -
In a template, wrap the fragment in the
cacheview helper. Include a template version, the records that the fragment shows, and anything else the HTML depends on:<% books.each do |book| %> <%= cache ["v1", book, locale] do %> <%= render "books/card", book: book %> <% end %> <% end %>This example assumes that the view exposes
booksandlocale, and that theBookstruct definescache_keyandcache_version. -
When you change the fragment's markup, change the template version in the key, for example from
"v1"to"v2". The helper doesn't track template changes.
The helper accepts the same options as fetch, such as expires_in:. It stores entries under
"views/", so they don't collide with your own keys.
Invalidate entries¶
Choose the cheapest strategy that keeps results correct. The following table compares the strategies:
| Strategy | Use it when |
|---|---|
| Delete the key after a write | Writes are rare, and you know the key. |
Put updated_at or cache_version in the key |
The record changes often, and you can derive the key from it. |
| Change a version string in a fragment key | You changed the template, and the old HTML can be discarded. |
| Let the entry expire | A short window of stale data is acceptable. |
To delete an entry after a write, call delete with the same key that you cached it under:
To delete several entries, use delete_multi. cache.clear deletes every entry in the store,
including entries that other namespaces wrote, so don't use it to invalidate one feature's data.
Prevent stampedes on popular entries¶
When a popular entry expires, every request that misses it recomputes the value at the same time.
To let one request recompute while the others get the old value, pass race_condition_ttl: with a
few seconds:
Set race_condition_ttl a little longer than the block takes to run.
Read and write several entries at once¶
To fetch several entries in one call, use fetch_multi. The block runs once for each missing key,
and the result is a Hash in the order of the keys:
In this example, render_card stands for your own method that returns a String. With a store
that supports batches, such as the SQL store, fetch_multi reads all keys in one query.
Count events across processes¶
To keep a counter, use increment and decrement. Each call updates the value atomically and
returns the new Integer:
Whether a counter is shared across processes depends on the store. The SQL store locks the row, so counters are consistent across processes and servers. The file store holds a lock file, so counters are consistent on one machine. The memory store keeps a separate counter in each process.
Log cache hits and misses¶
The cache publishes an event for each operation. To log hits and misses, subscribe to the
:"mankai.cache.fetch" event in the provider's after(:start) callback:
# config/providers/cache.rb
require "mankai/cache"
Hanami.app.register_provider(:cache, from: :mankai_cache) do
configure do |config|
config.store = Hanami.env?(:test) ? :memory : :file
end
after(:start) do
target["notifications"].subscribe(:"mankai.cache.fetch") do |event|
payload = event.payload
target["logger"].debug(
"cache #{payload[:hit] ? "hit" : "miss"} #{payload[:key]} (#{payload[:time]}ms)"
)
end
end
end
For each fetch, the log shows whether it was a hit or a miss, the stored key, and how long the call took. For every event and
its payload, see Events.
What's next¶
- Choose a store and serializer: pick a store for each environment.
- Test the cache: test code that caches.
- mankai-cache reference: every method and option.