Skip to content

Commit 4e6339c

Browse files
Reap a tenant connection pool only once no thread is using it
Reaping a pool to stay under max_connection_pools went through remove_connection_pool, which disconnects the pool forcibly and takes a connection away from the thread that has it checked out, even in the middle of a transaction. The rows that transaction had already written stayed committed. A pool is now emptied with ConnectionPool#disconnect, which raises instead, and removed only while its locks are held and only if the connection handler still has that same pool. A pool in use is skipped and reaped by a later lookup once it is idle. A model's with_connection, lease_connection and connection retry a checkout that fails because the pool was reaped after they looked it up, until the pool's checkout_timeout has passed. A model's schema cache does the same, staying with the tenant and role it was got in. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent d5afa75 commit 4e6339c

6 files changed

Lines changed: 395 additions & 9 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22

33
## next / unreleased
44

5+
### Fixed
6+
7+
- Reaping a connection pool to stay under `max_connection_pools` no longer takes a connection away from a thread that is using it. Before, a thread in the middle of a transaction could lose its connection after it had written part of the transaction, and the part already written stayed committed. A pool that is in use is now skipped and reaped by a later lookup once it is idle, so `max_connection_pools` can be exceeded while pools are in use. When a pool is reaped between a model's `with_connection`, `lease_connection`, `connection` or `schema_cache` looking it up and using it, the call is retried with the tenant's new pool, for up to the pool's `checkout_timeout`. Code that holds on to a pool object itself, from `connection_pool`, can still raise `ActiveRecord::ConnectionNotEstablished` if that pool is reaped, before any SQL runs, as it could before.
8+
59
## v0.9.0 / 2026-10-19
610

711
### Security

‎GUIDE.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -287,7 +287,7 @@ production:
287287
max_connection_pools: 20
288288
```
289289
290-
Active Record Tenanted will reap the least-recently-used connection pools when this limit is surpassed. Developers are encouraged to tune this parameter with care, since setting it too low may lead to increased request latency due to frequently re-establishing database connections, while setting it too high may consume precious file descriptors and memory resources.
290+
Active Record Tenanted will reap the least-recently-used connection pools when this limit is surpassed. A pool that a thread is using is not reaped, because that would take its connection away, possibly in the middle of a transaction. So while more pools than the limit are in use the process holds more pools than the limit, and the extra pools are reaped when a later lookup finds them idle. Nothing reaps them on a schedule. Developers are encouraged to tune this parameter with care, since setting it too low may lead to increased request latency due to frequently re-establishing database connections, while setting it too high may consume precious file descriptors and memory resources.
291291
292292
293293
### 2.4 Configuring the Connection Class

‎lib/active_record/tenanted/lru.rb‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,10 @@ def pop
3737
def keys
3838
@data.keys
3939
end
40+
41+
def delete(key)
42+
@data.delete(key)
43+
end
4044
end
4145

4246
Lru = LRU

‎lib/active_record/tenanted/subtenant.rb‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ def tenanted_subtenant_of
2020
klass
2121
end
2222

23-
delegate :current_tenant, :connection_pool, to: :tenanted_subtenant_of
23+
delegate :current_tenant, :connection_pool, :with_connection, :lease_connection, :connection, :schema_cache, to: :tenanted_subtenant_of
2424
end
2525

2626
prepended do

‎lib/active_record/tenanted/tenant.rb‎

Lines changed: 173 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,8 @@ def connection_pool(schema_version_check: true) # :nodoc:
308308
pool = retrieve_connection_pool(strict: true)
309309
end
310310
end
311+
312+
reap_connection_pools(keep: [ current_tenant, current_role ])
311313
end
312314

313315
pool
@@ -316,6 +318,58 @@ def connection_pool(schema_version_check: true) # :nodoc:
316318
end
317319
end
318320

321+
# A thread that got a pool just before it was reaped finds it closed when it checks out a
322+
# connection. If that happens before the block has run, the checkout is tried again with the
323+
# tenant's current pool until checkout_timeout has passed since the first failure.
324+
def with_connection(prevent_permanent_checkout: false, &block) # :nodoc:
325+
checked_out = false
326+
retry_on_reaped_connection_pool(-> { checked_out }) do |pool|
327+
pool.with_connection(prevent_permanent_checkout: prevent_permanent_checkout) do |connection|
328+
checked_out = true
329+
block.call(connection)
330+
end
331+
end
332+
end
333+
334+
def lease_connection # :nodoc:
335+
retry_on_reaped_connection_pool { |pool| pool.lease_connection }
336+
end
337+
338+
# Rails' connection looks the pool up again. An error from that pool is retried only if it
339+
# is the reaped pool's own error, untagged, rather than one Rails tagged with another pool.
340+
def connection # :nodoc:
341+
retry_on_reaped_connection_pool { super }
342+
end
343+
344+
# Rails binds a schema cache to the pool it came from, so a model that loads its columns
345+
# through a pool that has just been reaped would fail. This one is bound to the same pool,
346+
# and if that pool turns out to have been reaped it moves to the tenant's new pool and
347+
# retries like with_connection. Schema reads have no side effects.
348+
def schema_cache # :nodoc:
349+
pool = connection_pool
350+
return pool.schema_cache unless pool.is_a?(ActiveRecord::ConnectionAdapters::ConnectionPool)
351+
352+
ReapedPoolRetryingSchemaCache.new(self, pool)
353+
end
354+
355+
class ReapedPoolRetryingSchemaCache # :nodoc:
356+
def initialize(model, pool)
357+
@model = model
358+
@pool = pool
359+
end
360+
361+
def method_missing(name, ...)
362+
@model.send(:retry_on_reaped_connection_pool, pool: @pool) do |pool|
363+
@pool = pool
364+
pool.schema_cache.public_send(name, ...)
365+
end
366+
end
367+
368+
def respond_to_missing?(name, include_private = false)
369+
@pool.schema_cache.respond_to?(name, include_private)
370+
end
371+
end
372+
319373
def tenanted_root_config # :nodoc:
320374
ActiveRecord::Base.configurations.resolve(tenanted_config_name.to_sym)
321375
end
@@ -356,21 +410,133 @@ def retrieve_connection_pool(strict:)
356410
connection_handler.retrieve_connection_pool(connection_specification_name, role:, shard:, strict:).tap do |pool|
357411
if pool
358412
tenanted_connection_pools[[ shard, role ]] = pool
359-
reap_connection_pools
413+
reap_connection_pools(keep: [ shard, role ]) unless CONNECTION_POOL_CREATION_LOCK.owned?
360414
end
361415
end
362416
end
363417

364-
def reap_connection_pools
365-
while tenanted_connection_pools.size > tenanted_root_config.max_connection_pools
366-
info, _ = *tenanted_connection_pools.pop
367-
shard, role = *info
418+
# Reaps the least recently used pools until the process is back at max_connection_pools. A
419+
# pool that a thread is using, or whose locks are held, is skipped and reaped by a later call,
420+
# so the limit can be exceeded meanwhile. The caller's own pool is kept.
421+
def reap_connection_pools(keep:)
422+
tenanted_connection_pools.keys.each do |shard, role|
423+
break if tenanted_connection_pools.size <= tenanted_root_config.max_connection_pools
424+
next if [ shard, role ] == keep
425+
426+
# The connection handler, not this list, says which pool the tenant has now.
427+
pool = connection_handler.retrieve_connection_pool(connection_specification_name, role:, shard:)
428+
429+
if pool.nil?
430+
forget_removed_connection_pool([ shard, role ])
431+
elsif reap_connection_pool(pool)
432+
Rails.logger.info " REAPED [tenant=#{shard} role=#{role}] Tenanted connection pool reaped to limit total connection pools"
433+
end
434+
end
435+
end
436+
437+
# Removes a pool from the connection handler if no thread is using it, and returns whether
438+
# it did.
439+
#
440+
# remove_connection_pool takes a connection away from the thread that has it checked out,
441+
# even in the middle of a transaction. So the pool is emptied first with disconnect, which
442+
# raises rather than do that, and is removed while its lock is held, so that no thread can
443+
# check out a connection in between. The reaper lock is taken first, as Rails' reaper takes
444+
# it; every other lock is only tried, so this never waits on a thread that waits on it.
445+
def reap_connection_pool(pool)
446+
# Rails takes the reaper lock before the pool's lock, never after.
447+
return false if pool.mon_owned?
448+
449+
pool.reaper_lock do
450+
return false unless pool.mon_try_enter
451+
452+
begin
453+
return false if pool.discarded? || connection_pool_in_use?(pool)
454+
455+
# A connection that another thread is still opening is not in stat. disconnect waits
456+
# for it, up to twice the checkout timeout, and raises if it is then in use. While it
457+
# waits it lets go of the pool's lock, so check again once it returns.
458+
pool.disconnect
459+
return false if connection_pool_in_use?(pool) || pool.stat[:connections] > 0
460+
461+
remove_idle_connection_pool(pool)
462+
rescue ActiveRecord::ExclusiveConnectionTimeoutError
463+
false
464+
ensure
465+
pool.mon_exit
466+
end
467+
end
468+
end
469+
470+
# Removes the pool, which the caller has emptied and holds the locks of, unless the
471+
# connection handler now has another pool for the tenant. New tenant pools are only
472+
# registered under CONNECTION_POOL_CREATION_LOCK, and PoolConfig#disconnect! takes the
473+
# pool config's lock before the reaper lock, so both are only tried.
474+
def remove_idle_connection_pool(pool)
475+
return false unless pool.pool_config.mon_try_enter
476+
477+
begin
478+
return false unless CONNECTION_POOL_CREATION_LOCK.try_lock
479+
480+
begin
481+
current = connection_handler.retrieve_connection_pool(connection_specification_name, role: pool.role, shard: pool.shard)
482+
return false unless current.equal?(pool)
483+
484+
tenanted_connection_pools.delete([ pool.shard, pool.role ])
485+
connection_handler.remove_connection_pool(connection_specification_name, role: pool.role, shard: pool.shard)
486+
true
487+
ensure
488+
CONNECTION_POOL_CREATION_LOCK.unlock
489+
end
490+
ensure
491+
pool.pool_config.mon_exit
492+
end
493+
end
494+
495+
# Drops the entry for a pool that was removed from the connection handler by other means,
496+
# unless a new pool for the tenant has been registered since.
497+
def forget_removed_connection_pool(key)
498+
return unless CONNECTION_POOL_CREATION_LOCK.try_lock
499+
500+
begin
501+
shard, role = key
502+
unless connection_handler.retrieve_connection_pool(connection_specification_name, role:, shard:)
503+
tenanted_connection_pools.delete(key)
504+
end
505+
ensure
506+
CONNECTION_POOL_CREATION_LOCK.unlock
507+
end
508+
end
368509

369-
connection_handler.remove_connection_pool(connection_specification_name, role:, shard:)
370-
Rails.logger.info " REAPED [tenant=#{shard} role=#{role}] Tenanted connection pool reaped to limit total connection pools"
510+
# Yields the tenant's pool. If the pool turns out to have been reaped before a connection
511+
# was checked out, yields the tenant's new pool, until checkout_timeout has passed since the
512+
# first failure. started tells whether the caller's own work has begun. A pool of a tenant
513+
# or role other than the current one is never replaced.
514+
def retry_on_reaped_connection_pool(started = -> { false }, pool: connection_pool)
515+
deadline = nil
516+
begin
517+
yield pool
518+
rescue ActiveRecord::ConnectionNotEstablished => error
519+
# Rails tags an error from opening a connection with its pool. An error from another
520+
# pool than this one is not about this pool being reaped.
521+
raise if error.connection_pool && !error.connection_pool.equal?(pool)
522+
raise if started.call || !connection_pool_reaped?(pool) || pool.shard.to_s != current_tenant.to_s || pool.role != current_role
523+
deadline ||= Process.clock_gettime(Process::CLOCK_MONOTONIC) + pool.checkout_timeout
524+
raise if Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline
525+
pool = connection_pool
526+
retry
371527
end
372528
end
373529

530+
def connection_pool_reaped?(pool)
531+
pool.is_a?(ActiveRecord::ConnectionAdapters::ConnectionPool) &&
532+
!connection_handler.retrieve_connection_pool(connection_specification_name, role: pool.role, shard: pool.shard).equal?(pool)
533+
end
534+
535+
def connection_pool_in_use?(pool)
536+
stat = pool.stat
537+
stat[:busy] > 0 || stat[:waiting] > 0
538+
end
539+
374540
def log_tenant_tag(tenant_name, &block)
375541
if Rails.application.config.active_record_tenanted.log_tenant_tag
376542
Rails.logger.tagged("tenant=#{tenant_name}", &block)

0 commit comments

Comments
 (0)