Skip to content

Simplify `LoadBalancer::Session` usage patterns

Problem

Currently LoadBalancer::Session defines a number of usage patterns:

  • use_primary!
  • ignore_writes
  • use_replicas_for_read_queries
  • fallback_to_replicas_for_ambiguous_queries

The usage of these methods starts to become ambigious due to multitude of them and their effect on session and outside of the current execution context. For example, some of them are used to solve a very specific single-use pattern (fallback_to_replicas_for_ambiguous_queries).

We should have a single way of making a decision and a way to stick it through life-cycle of execution. This becomes important, as we also might want to indicate what kind of operations are allowed in a given execution context: #328525 (closed).

Proposal

Remove these methods, and instead rely on a concept similar to transaction, where we nest the execution and each nesting extends or inherits the session ensuring that leaves everything in a clean state outside of this execution. Rails already does that so extent with https://github.com/rails/rails/blob/75ac626c4e21129d8296d4206a1960563cc3d4aa/activerecord/lib/active_record/middleware/database_selector.rb#L60-L68 as described in #330466 (closed). We should avoid re-inventing this very specific usage as this will make it harder to support well many databases.

class Session
  def self.transaction(read_write: false|true) do
    ...
  end
end

Example here: !57477 (closed).

Edited by Kamil Trzciński