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

Databases: primary and replicas

This chapter covers two needs. The first is to spread the reads of a busy application over replicas: read-only copies of the database that PostgreSQL keeps up to date. The second is to keep some tables in another database.

In Django, both go through the DATABASES setting and a database router, a class whose db_for_read and db_for_write methods choose a database for each query. rind has no router class. Instead:

  • each database is a Cluster: one primary, the server that is written, and its replicas;
  • a request that only reads goes to a replica, and a request that writes goes to the primary, automatically;
  • a model says which database its table is in, with #[model(database = "…")].

Reading on replicas

You build a Cluster from the primary, add its replicas, and give it to the application’s state:

#![allow(unused)]
fn main() {
use rind::api::Databases;
use rind::prelude::*;

let primary = Db::connect(&std::env::var("DATABASE_URL")?)?;
let replica = Db::connect(&std::env::var("REPLICA_URL")?)?;

let cluster = Cluster::new(primary).replica(replica);
let state = app.state_with(Databases::of(cluster));
}

app.state_with(..) is the state your web server is given (see The command line for a server of your own, with rind::cli::Cli::serve). The serve command of rind’s own server uses one database only, DATABASE_URL: to use replicas, you write that server yourself.

From then on, each request picks its server by itself:

  • A request that only reads (a GET) works on a replica. With several replicas, the requests take turns.
  • A request that writes (anything but a GET) works on the primary.
  • A replica refuses a write before it reaches the server: the query fails with a ReadOnly error. A bug cannot write to a replica by mistake.

Reading your own writes

A replica is always a little late: the primary sends it its changes, and applying them takes a moment. Most reads do not care. But a client that creates an object and then reads the list right after must find the new object in it.

rind handles this with a position: how far the primary’s log has got (PostgreSQL’s LSN, written like 16/B374D848).

  1. Every answer to a write carries the position the primary reached, in the header X-Db-Position.
  2. The client sends this header back with the requests that follow.
  3. A read that comes with a position goes to a replica only if that replica has caught up with it. Otherwise it goes to the primary.
POST /stations
201 Created
X-Db-Position: 16/B374D848
GET /stations
X-Db-Position: 16/B374D848

A client that sends nothing back is covered too, in part: the server remembers, per process, the position of each signed-in user’s last write, and sends that user’s reads to the primary until a replica has caught up. This memory is not shared between processes. Behind a load balancer, the next request may reach another process, so a client that must read its own writes should send the header back.

The header is only sent when the database has replicas: without them, nothing can be late. rind’s CORS lets a browser read it.

A read that must not be late

Sometimes a piece of code that runs in a reading request must see the latest data, for example to check a value just before it answers. It asks for the primary:

#![allow(unused)]
fn main() {
let db = ctx.primary()?;
}

ctx.primary() gives the primary of the default database, whatever the request does.

Several databases

A model says which database its table is in. Without it, the table is in the database named default:

#![allow(unused)]
fn main() {
#[derive(Model)]
#[model(table = "visits", database = "stats")]
pub struct Visit { … }
}

The application gives each database a name, and a Cluster:

#![allow(unused)]
fn main() {
let databases = Databases::new(db).with("stats", Cluster::new(stats).read_only());
let state = app.state_with(databases);
}

Databases::new(db) is the default database on a single server; Databases::of(cluster) is the same with replicas. .with(name, cluster) adds another database. .read_only() says that the application never writes this one: even its primary refuses writes.

In a handler, ctx.db is the default database. You ask for another one by its name:

#![allow(unused)]
fn main() {
let stats = ctx.database("stats").await?;
let visits = stats.all(&Query::<Visit>::new()).await?;
}

The database you get follows the same rule as the request: its primary for a request that writes, a replica otherwise.

A query on a model sent to another database than its own is refused before any SQL is sent: a WrongDatabase error. Asking for a database the application does not have is an error too.

Coming from Django: there is no .using("stats") on a query. The model knows its database, so the query cannot go to the wrong one; you choose only the Db you run it on.

What is not covered

  • A transaction covers one database. A transaction on the default database does not include the writes made with ctx.database("stats").
  • A relation does not cross databases. A foreign key, a nested field or a filter cannot join a table of another database.
  • Raw SQL is not checked. A query written as SQL text is not checked for its database, nor for being a write sent to a read-only server (PostgreSQL itself refuses a write on a replica).
  • The position is the default database’s. It says how far the default primary’s log has got, and means nothing to the replicas of another database. Do not count on reading your own writes there: ask for that database in a request that writes, or give it no replicas.
  • Migrations know one database. rind migrate applies every domain’s migrations to the database it is given, whatever database = "…" the models say.