Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Cache

Some answers are expensive to build and change rarely: a list of 500 rows with their nested objects, a count over a large table. The cache plugin keeps such answers and sends them again without reading the database. In a real application, a list of 500 rows (594 KB) took 320 ms to read, and 1 ms to send from the cache.

The plugin has two parts:

  • a store, for your code: you keep values in it and read them back, as with Django’s cache.get and cache.set;
  • the answers of resources: the lists and retrieves of the resources you name are kept, and made stale automatically when a table they read is written.

Coming from Django: the store is Django’s cache framework (django.core.cache), with a memory backend and a Redis backend. The answers of resources replace cache_page and the per-view cache, with one big difference: you do not have to invalidate anything by hand. rind knows which tables an answer was read from, and it sees every write the application commits.

Turning it on

Turn on the cache feature of rind in your Cargo.toml, or cache-redis for a cache in Redis:

rind = { version = "…", features = ["cache-redis"] }

Then install the plugin in app(), and name the resources whose answers it keeps:

#![allow(unused)]
fn main() {
// sample/src/lib.rs
.with(
    rind::cache::Cache::from_env()
        .expect("RIND_CACHE_URL")
        .resource::<network_api::stations::StationResource>(std::time::Duration::from_secs(60)),
)
}

Cache::from_env() reads RIND_CACHE_URL:

  • not set, empty, or memory: the cache is in the process’s memory;
  • redis://host:port/db: the cache is in Redis, shared by every process of the application. This needs the cache-redis feature.

Any other value is an error.

With this setting, the railway keeps its stations’ answers for a minute:

GET /stations
HTTP/1.1 200 OK
etag: "3f2a…"
last-modified: Fri, 27 Nov 2026 10:00:00 GMT
cache-control: no-cache, must-revalidate
vary: Authorization
x-rind-cache: miss

The first request reads the database (x-rind-cache: miss). The next one, by the same user, within the minute, is sent from the cache (x-rind-cache: hit) unless a station was written in between.

Keeping values from your code

The plugin is a service, so code that runs in a request (an action, a hook, a loader) finds it with ctx.service:

#![allow(unused)]
fn main() {
let cache = ctx.service::<rind::cache::Cache>().unwrap();
let counts = cache
    .get_or_set("seat-counts", Duration::from_secs(600), async || count_seats(ctx).await)
    .await?;
}

get_or_set returns the value kept under "seat-counts" if there is one. Otherwise it runs the function, keeps its result for 10 minutes, and returns it. If the function fails, nothing is kept and the error is returned. The value is kept as JSON, so its type must implement Serialize and Deserialize.

The other methods are get, set and remove (for bytes), and their JSON forms get_json and set_json.

A cache never fails a request. When the store fails (Redis is down, for example), it answers as an empty store: get finds nothing, and set keeps nothing. The failure is logged as a warning under the target rind::cache, and /ready reports it (see Health).

The store can be in the process’s memory (Cache::memory(), up to 10,000 values), or in Redis (Cache::redis(url)). A store in memory is right for one process and for tests. A store in Redis is shared by every process of the application, so a value kept by one is found by the others.

Keeping the answers of resources

The cache keeps the lists and the retrieves of the resources it is told about, and the cached actions of those resources. It sends them again without reading the database.

There are two ways to tell it about a resource. In the application, as above, with .resource::<R>(ttl). Or on the resource itself, with options(..) (see Plugins):

#![allow(unused)]
fn main() {
// sample/crates/fleet/fleet-api/src/trains/views.rs
#[resource(
    model = Train,
    path = "trains",
    // …
    options(cache_ttl = 30, cache_by_mode)
)]
pub struct TrainResource;
}

cache_ttl is the time to live, in seconds. When the application and the resource both say something, the application wins.

Only answers with status 200 are kept. An export (?format=xlsx, ?format=csv) is never kept.

Who shares an entry

By default, an entry is for the user who asked, and for nobody else. Two users never share an entry, and anonymous users share one.

This is safe, but it means each user fills the cache for themselves. Some resources answer the same thing to every user that the same rule lets in: every signed-in user sees the same trains, for example. Such a resource can say so, with .resource_by_mode::<R>(ttl) in the application, or with options(cache_by_mode) on the resource. Its entries are then kept per rule (per mode, see Permissions), and shared by every user of that rule.

Be careful: this is rarely true. Two users of one mode often see different rows (each one sees their own reservations, for example). Use it only when the answers depend on nothing but the rule.

What makes an entry stale

A write to a table the answer was read from makes the entry stale. The tables an answer reads are the resource’s model’s table, and those of the outputs it nests: the Serializer derive lists them (Serializer::tables).

The cache learns of writes through its statement observer (see Plugins). So it sees every write the application commits, whoever wrote it: the resource itself, another resource, a hook, a job of the process. A write that is rolled back changes nothing.

The answer to a write is sent only once the entries it made stale are stale. So the client’s next read gets the new rows, never the old ones.

Note: the derive lists the model’s table and the nested outputs’ tables only. A field computed by a loader (#[computed(..)]) or by an annotation (#[annotated(..)]) may read other tables, and a write to those does not make the entry stale. Give such a resource a short time to live, or make the entries stale yourself with clear_table (below).

How it works. Each table has a generation in the store: a counter, raised on each write to the table. The key of an entry holds the generations of the tables it read. When a write raises a generation, the key that an answer would now have is a new one, so every entry that read the table becomes unreachable, in every process that shares the store. The cache does not have to search for the old entries: they simply expire.

What the cache cannot see

The cache does not see a write made by another program, or by SQL that rind did not run. The time to live bounds how long such an answer stays stale. You can also tell the cache yourself:

  • cache.clear_table(database, table) says that a table changed, as a write would;
  • cache.clear(), or the command cache-clear, makes every answer stale.
$ cargo run -p sample -- cache-clear
The cache's answers are stale.

Code that writes a table with hand-written SQL can also call db.wrote("table"): the observers, the cache among them, are then told on commit as for any other write.

Replicas

When the application reads on replicas (see Databases), an answer read on a replica just after a write to one of its tables may be old: the replica may not have the write yet. If the cache kept that answer, it would put the old rows back for everyone. So an answer read on a replica within 5 seconds of a write to one of its tables is sent, but not kept. Change the delay with Cache::replica_lag(duration).

The key of an entry

The key of an entry is made of:

  • the resource, and the operation (a list and an action of the same path have different keys);
  • the object, for a retrieve;
  • the query parameters, in a fixed order: ?page=1&ordering=name and ?ordering=name&page=1 share one entry;
  • who asks: the user, or the rule with cache_by_mode;
  • the generations of the tables it read.

Actions

A GET action that says cached (#[action(GET, cached)], see Actions) is kept as a list is, under its own name: the get_flags action of the Flags behaviour, for example. No other action is ever kept.

Asking for a fresh answer

A client sometimes wants an answer read from the database, not the cache’s. A request asks for it in one of two ways:

  • the header Cache-Control: no-cache (or Pragma: no-cache), which a browser sends on a hard reload;
  • the parameter no_cache, or nocache, with any value (?no_cache=1). This is easier to add to a link, or to a client’s parameters, than a header.
GET /stations?no_cache=1

The answer read takes the old one’s place in the cache, so the next request gets it from the cache: the first answer says x-rind-cache: refresh, and the next one hit.

The parameter is not part of the key. No filter may use the name no_cache or nocache: the FilterSet derive refuses it with a compile error. Asking for a fresh answer needs no permission: without a cache, every request reads the database anyway.

The OpenAPI document lists no_cache on every read the cache may keep.

Sending a 304 when nothing changed

A kept answer carries these headers:

  • ETag: a hash of the body;
  • Last-Modified: when the answer was read;
  • Cache-Control: no-cache, must-revalidate: the client must ask again each time, but may send what it has;
  • Vary: Authorization: the answer depends on who asks;
  • x-rind-cache: hit, miss or refresh.

A client that sends the ETag back, in If-None-Match, gets a 304 Not Modified with no body when the answer has not changed:

GET /stations
If-None-Match: "3f2a…"
HTTP/1.1 304 Not Modified

So a front end can ask every time, and is answered at once when nothing changed. Browsers do this by themselves.

ETag without a cache

rind::cache::ETags is a second, smaller plugin. It gives every list, every retrieve and every cached action an ETag, Cache-Control and Vary, and answers 304 to a client that sends the ETag back. It keeps nothing: the transfer is spared, not the work, since the answer is still built to compute its hash. It sends no Last-Modified and no x-rind-cache.

#![allow(unused)]
fn main() {
.with(rind::cache::ETags)
}

Where to put the cache among the plugins

The plugins’ hooks run in the order the plugins were given, the first outermost (see Plugins). When the cache answers from its store, the hooks given after it do not run for that call. Give the plugins that must see every call, such as the metrics and the usage log, before the cache.

Reference

VariableMeaningDefault
RIND_CACHE_URLmemory, or redis://host:port/db (needs cache-redis)memory
Cache::Meaning
from_env()memory, or Redis, as RIND_CACHE_URL says
memory()in the process’s memory, up to 10,000 values
redis(url)in Redis (feature cache-redis)
with_store(store)in a store of your own: a type that implements rind::cache::Store
.resource::<R>(ttl)keeps the answers of R for ttl, per user
.resource_by_mode::<R>(ttl)keeps the answers of R for ttl, per rule
.config::<R>(Config { ttl, by_mode })the same two, as a value
.prefix(prefix)the keys of the store start with prefix (rind: by default): for several applications in one Redis
.replica_lag(duration)how late a replica can be (5 s by default)
MethodMeaning
get(key), set(key, bytes, ttl), remove(key)a value of the application’s
get_json(key), set_json(key, &value, ttl)the same, as JSON
get_or_set(key, ttl, f)the value of key, or the one f makes, kept for ttl
clear_table(database, table)makes the answers that read table stale
clear()makes every kept answer stale
Resource optionMeaning
cache_ttl = 60keeps the answers for 60 seconds
cache_by_modeone entry per rule, not per user
CommandMeaning
cache-clearmakes every answer the cache keeps stale
Header sentValues
x-rind-cachehit, miss, refresh

The parameters that ask for a fresh answer are the constant rind::cache::FRESH_PARAMS: no_cache and nocache.