Senior Track Roadmap

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
Free preview · Lesson 1 3 min read

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 lessons
Type to start searching...