Database architecture: role-switch
This course examines automatic role switching in Rails, the database_selector setting that routes each request to the primary or to a replica. It covers the middleware's three parts: a context that remembers, a resolver that decides, and the wiring between them. The lessons explain why the HTTP verb decides what counts as a read and how the session stores a last-write timestamp. They show why prevent_writes makes a GET that writes fail every time. They also cover choosing the delay from measured lag and replacing the default policy.
What you'll learn
- ✓How the database_selector middleware divides work between a context, a resolver and the wiring
- ✓Why GET and HEAD count as reads, and how to find GET requests that write
- ✓How the session timestamp protects read-your-own-writes and where that protection ends
- ✓Why prevent_writes: true on both read paths makes a GET that writes fail every time
- ✓How to choose the delay from the maximum replication lag during the busiest hour
- ✓When to replace the resolver or context, or use explicit connected_to blocks instead
One line of configuration
Automatic role switching is turned on by a single line, and the size of that line is misleading: it changes which database every request in the application talks to.
Read the full lesson free →Curriculum
7 lessonsOne line of configuration
One configuration line installs middleware with a context, a resolver and wiring that route every request.
The verb is the signal
The resolver treats GET and HEAD as reads, so GET requests that write must be audited first.
The session remembers
The session stores one last-write timestamp, which protects a user's own writes but not other users' writes.
prevent_writes is the part people miss
Both read paths set prevent_writes, so a GET that writes fails every time, even without a replica.
Choosing the delay
The delay claims replication lag never exceeds it, so pick it from the maximum measured lag.
Replacing the policy
Custom resolvers, custom contexts or explicit connected_to blocks can replace the default verb and session policy.
Putting it together
A recap of the whole policy and a challenge to implement the resolve decision, including prevent_writes.