Using Automatic Role Switching
Instead of manually switching all Active Record queries, it’s possible to automatically send them to the replica. The Active Record feature automatic role switching,[348] which runs as a middleware from Rails 6.0 onward, provides that functionality.
How does it work? Automatic role switching identifies incoming HTTP requests by their verb. HTTP requests that are GET and HEAD requests are always read-only types. This means that Active Record can send queries for those requests to the reading role. Other HTTP request verbs (POST, PUT, DELETE, or PATCH) always go to the writer role.
Automatic role switching has some caveats to be aware of. For requests related to individual resources, Active Record checks the creation ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access