Skip to content

Commit 8c778d1

Browse files
committed
Add reset_tenant_on_checkin config option to skip redundant USE statements in shared pool mode
Every shared-pool query currently issues two USE roundtrips — one on checkin (reset to fallback) and one on checkout (switch to tenant). Since switch_tenant_database already has a fast-path no-op when the connection is already on the right tenant, we can skip the checkin reset and let consecutive same-tenant checkouts resolve with just two string comparisons and zero IO. The checkout callback still validates the tenant on every checkout, so tenant safety is maintained. Defaults to true to preserve existing behavior.
1 parent 0478416 commit 8c778d1

2 files changed

Lines changed: 16 additions & 0 deletions

File tree

‎lib/active_record/tenanted/railtie.rb‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,21 @@ class Railtie < ::Rails::Railtie
4646
# Defaults to false in development and test environments, and true in all other environments.
4747
config.active_record_tenanted.log_tenant_tag = !Rails.env.local?
4848

49+
# Set this to false to skip the USE statement that resets connections to the
50+
# fallback database on checkin in shared pool mode. When false, connections
51+
# preserve their tenant database across checkout/checkin cycles, and the
52+
# checkout callback switches only when the next checkout targets a different
53+
# tenant. This eliminates most USE roundtrips in the per-query connection
54+
# lifecycle.
55+
#
56+
# The checkout callback (apply_current_tenant) validates the tenant on every
57+
# checkout regardless of this setting, so tenant safety is maintained.
58+
#
59+
# Only applies when shared_pool: true is set in database.yml.
60+
#
61+
# Defaults to true (always reset on checkin).
62+
config.active_record_tenanted.reset_tenant_on_checkin = true
63+
4964
# Set this to override the default tenant name used in development and test environments.
5065
#
5166
# This is the default tenant name used by database tasks and in the Rails console. In both

‎lib/active_record/tenanted/shared_pool.rb‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ def apply_current_tenant
4747

4848
def reset_to_fallback
4949
return unless shared_pool?
50+
return unless Rails.application.config.active_record_tenanted.reset_tenant_on_checkin
5051

5152
db = @config[:untenanted_database]
5253
internal_execute("USE #{quote_table_name(db)}", "TENANT RESET", allow_retry: false)

0 commit comments

Comments
 (0)