makara icon indicating copy to clipboard operation
makara copied to clipboard

Makara doesn't switch to slave when using AR.connection directly

Open bogdan opened this issue 8 years ago • 2 comments

Here you can see that reads are from slave when using model methods... but not connection itself:

production >> SlaveUtils.read_from_slave { User.first }
  [slave/1] User Load (0.6ms)  SELECT  `users`.* FROM `users` ORDER BY `users`.`id` ASC LIMIT 1
production >> SlaveUtils.read_from_slave { User.connection.select_all('show processlist') }
  [master/1] (1.4ms)  show processlist
production >> 
``

bogdan avatar Feb 17 '17 13:02 bogdan

This is unrelated to using model methods vs connection methods. You're comparing two different SQL statements. Makara decides which queries to send where based on whether they need the primary db or can use a replica. The SHOW query falls back to the primary connection since it doesn't match any of the regexps.

To verify: If you do a SELECT on the connection first, it'll pick a replica connection and a subsequent SHOW PROCESSLIST should stick to the same connection.

jeremy avatar Mar 02 '17 19:03 jeremy

Thanks for clarification. I am not sure I got it at 100%.

Should I do it like this:

production >> SlaveUtils.read_from_slave { c = User.connection; c.select_all('SELECT  `users`.* FROM `users` LIMIT 1'); c.select_all('show processlist'); nil }
  [slave/1] (0.7ms)  SELECT  `users`.* FROM `users` ORDER BY `users`.`id` ASC LIMIT 1
  [master/1] (1.3ms)  show processlist
=> nil

bogdan avatar Mar 03 '17 10:03 bogdan