Avoid replica connection checkout/checkin for every read query - #298
Conversation
|
Hello @bmak-lightspeed. Thanks for the contribution. Can you share benchmarks that support your claim, for documentation purposes? |
|
Hi @mateuscruz, Sorry for the delay (I was on vaca). DisabledI don't have benchmarks, but here's picture of a flame graph of a request when this patch is NOT enabled. You can see that every read query makes a "PG active? probe" query which translates to a Normally queries sent to the PG gem create a span, but since the query is just
(I had to redact some info)
EnabledWhen this change is enabled you can see that only the first read query incurs the checkout cost: Fwiw this change does assume the user is using Rails which automatically returns the connection back to the pool after each request / job. This could be a separate adapter if we want to also maintain support for non Rails web frameworks. |
6f37bdc to
6f862a6
Compare
|
fwiw I'd like to backfill this into the v9 stable branch if possible |
|
@bmak-lightspeed what Ruby and Rails versions is your project running on? |
a765d5f to
2c518b3
Compare
|
Ugh. Github does not sign rebased commits anymore. @bmak-lightspeed can you rebase locally? |
2c518b3 to
5042486
Compare
|
Just force pushed with your fix. |
|
@bmak-lightspeed some unit tests need to be fixed there.
I can backport it. |
5042486 to
4be5c8e
Compare
|
As far as I can tell the tests seem to run fine now, but there's some issue with the coverage report. I believe that is unrelated to the change. |


We migrated from Makara to this project, but we found that reads were considerably slower than Makara.
After looking at the code we realized that PrimaryReplicaProxy currently checks out and checks in a replica connection for every read query. Each checkout can cause Active Record to verify the connection by issuing a
;query, adding unnecessary database round trips and latency.Use
replica_pool.connectionorreplica_pool.lease_connectioninstead, allowing Rails to manage connection cleanup and check-in at the end of the request or Sidekiq job. This follows the same mechanism Rails uses when obtaining the primary connection, leveraging Rails' existing primary-connection check-in behavior to automatically check in the replica connection as well.This avoids per-query connection verification while preserving existing connection-pooling behavior and significantly improves read-heavy request performance.