Repository navigation
Reduce contention in the shared origin connection pool - #13806
Conversation
The shared session pool mutex was held across migrating a pooled origin connection to another thread and across closing sessions, which put socket and TLS work inside a lock every thread contends for. The lock now covers only the pool tables and handing a connection off: - Migration is split into a detach under the lock and an attach after it is released. - Sessions that cannot be pooled, time out, or are closed by the origin are closed after the lock is released. - A pool purge has each thread close its own sessions. This fixes three race conditions in the migration of a pooled origin connection, all present before this change: - The migrating thread stopped the old connection's EventIO while the owning thread could still be rescheduling that connection, having failed the try lock on its VIO mutex. The owning thread then used the stopped EventIO, which hit ink_assert(event_loop) in debug builds and dereferenced a null event loop with kqueue. EventIO::modify and EventIO::refresh now do nothing once stopped. - With kqueue, stopping an EventIO did not remove its registration, and a migrated socket is never closed. The old thread's kqueue could keep delivering events addressed to a connection that thread had since freed. Migration now removes the registration, and a refresh racing with the removal undoes its own add. - When creating the new connection failed, the old one was closed a second time, after the owning thread could already have freed or reused it. The session no longer refers to the old connection once it has been detached. The pooled_server_connections gauge also no longer drifts after a purge.
There was a problem hiding this comment.
Copilot review overview
🔵 Needs a closer look
Cross-thread connection lifetime and poller-registration changes warrant final human concurrency review despite the targeted tests.
Review effort: Balanced
Findings: None
What changed in this PR
Shortens shared origin-session pool locking while hardening cross-thread connection migration and purge behavior.
Changes:
- Splits connection migration into locked detach and unlocked attach phases.
- Defers session closure and distributes purges to connection-owning threads.
- Makes
EventIOmigration-safe, with targeted kqueue tests.
| File | Description |
|---|---|
src/proxy/http/HttpSessionManager.cc |
Refactors migration, purge, and deferred closure. |
src/iocore/net/UnixNetVConnection.cc |
Splits connection migration into detach and attach. |
src/iocore/net/unit_tests/test_EventIOMigration.cc |
Tests kqueue migration cleanup. |
src/iocore/net/ReadWriteEventIO.cc |
Ignores stale migrated events. |
src/iocore/net/P_UnixNetVConnection.h |
Defines migration state and APIs. |
src/iocore/net/EventIO.cc |
Adds race-safe stop and refresh behavior. |
src/iocore/net/CMakeLists.txt |
Registers the new unit test. |
include/proxy/http/HttpSessionManager.h |
Declares purge and deferred-close APIs. |
include/iocore/net/EventIO.h |
Makes event-loop state atomic. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
|
We tried this in production. I cherry-picked the commit onto our 10.2.x-based build and compared two identical hosts in the same pod: same hardware, same traffic mix, A window here is a 60-second interval in which we read each counter at the start and end on both hosts at the same moment, then divided the increase by the requests served in that interval. Per-request counters over 8 such paired windows, starting about an hour after the restarts, stock → patched:
In the access log, the share of origin requests that went out on an already-open connection rose from 75.0% to 76.8%, higher in all four 15-minute windows from the first hour after the restarts. Before the patch, with both hosts on the same build, the patched host actually opened slightly more origin connections than its partner. So the improvement isn't a quirk of that host. Client TTFB, origin wait, 5xx share and cache hit ratio didn't change outside noise. ATS CPU per request read about 3% lower on the patched host, but we have no same-build baseline for that window, so I wouldn't read anything into it in either direction. For comparison, you saw about 2% higher CPU with the patch. Stability: no crashes or restarts over about 1.5 hours in rotation, and |
bryancall
left a comment
There was a problem hiding this comment.
✅ Approve
I reviewed 2d0992006..15177a743 (9 files, +486/-131). I ran it on macOS (kqueue, clang TSan and ASAN+UBSan) and on Fedora 44 (epoll, clang TSan and gcc ASAN with LSan), and benchmarked release builds of base and head on Linux.
Verified: the migration races are real and this fixes them
With a global pool, 8 net threads, a parent and an origin that drops idle connections, base aborted on both platforms. On macOS it was 3 of 3 runs within about 400 requests: once on event_loop in EventIO::refresh, twice freeing a VC still on a ready list. On Linux TSan it was 3 of 3 within 9 s, the same event_loop assert from net_read_io.
Head ran clean:
- macOS: 76k requests under TSan and 110k under ASAN+UBSan (parent and TLS origin). Linux: 240k under TSan and 360k under gcc ASAN. No assert or sanitizer report,
migration_failure0, gauges back to 0 when idle. LSan's only report is a NetAccept leak at shutdown, identical at base. - On epoll the race still happens, and the null-loop return in
EventIO::modifyandrefreshis what makes it safe, as your comment atUnixNetVConnection.cc:1331says. Puttingink_assert(loop)back there aborts 3 of 3 atEventIO.cc:163(TSan binaryb40e7c67ea090471); restored, it is the original binary (e51b60bbb9011d59) and runs clean. - The base TSan races
EventIO::refresh/stopandConnection::close/moveare gone. The only TSan hit in new code isstop_for_migrationreadingfdagainst a later freelist reuse of that VC, which TSan cannot see through. - Both new kqueue tests pass. Each goes red when I revert its fix.
- Linux: ctest 1019/1019 at base and head. Of 21 related autests, 18 pass and 2 skip at both;
per_server_metric_enabledfails at both on a sandbox socket path that is too long and passes with a shorter one. - Benchmark, release builds, 4 and 5 interleaved passes: nothing worse by more than 5% outside the noise. Cache hit 653k against 652k RPS; global pool direct and through a parent within 1.3% RPS and 1% CPU per request.
Non-blocking: the purge no longer frees the triggering request's slot
bneradt's note at HttpSessionManager.cc:447 says the triggering request fails either way. In my test it didn't on base: the purge was synchronous, so the request that hit server_max_connections got through on its retry. Now its retries from HttpSM.cc:6003 all run before this thread's purge event. With max 1 and a pooled session to origin A, a request to origin B gets 200 on base and 502 here, after 3 parent retries are exhausted. With 4 threads it fails whenever the pooled session is on the same thread. It reproduces on Linux every time: 4 of 4 with 1 thread and 6 of 6 with 4 threads, against 200 at base. You could call purge_thread_keepalives() inline for the current thread in purge_keepalives (HttpSessionManager.cc:441). The gauge fix holds: in the same test, base drifted to pooled 3 against current 1.
Non-blocking: smaller items
- I agree with bneradt's request for an AuTest with a global and hybrid pool and a low
server_max_connections.test_EventIOMigration.cc:33is entirely kqueue, so Linux CI runs none of it (it compiles to an empty object on Fedora), and that AuTest would also catch the 502 above. - I agree with bneradt on
UnixNetVConnection.cc:1340. If you keep an abort there, log the errno and fd. The comment at :1335 also cites a repro that isn't in the tree. - The title says parent connections, but this covers every shared-pool origin connection.
Stop the EventIO before moving the socket out of the old VC during a migration. A failed removal from the old thread's poller aborted the process; with the VC still owning the socket and SSL object an ordinary close recovers instead, and the caller treats it as a migration failure. The epoll stop also ignores ENOENT, which a level triggered build hits on every migration because disabling the read side already removed the fd. purge_keepalives() closes the current thread's pooled connections before it returns and asks the other threads to close theirs. Without the inline close the request that hit the connection limit used up its retries before any thread ran its purge event, so it failed with a 502 where it used to succeed. Connections on other threads are closed when those threads next run, so a few more requests can fail at the limit than when the caller purged synchronously after getting the pool lock. Add an autest for the global and hybrid pools that reuses pooled origin connections across net threads and purges them at server_max_connections, checking that the request which purged succeeds and that the pooled connection gauge returns to zero. The kqueue unit tests compile to nothing on Linux, so the pool changes had no coverage in CI.
bryancall
left a comment
There was a problem hiding this comment.
✅ Approve
I reviewed 15177a743..f068f1f95 (8 files, +560/-29) against the whole PR. On Fedora 44 I built it with gcc ASAN and clang TSan and reran my earlier repros.
Fixed: every earlier ask
- The 502: my parent repro now gets 200 in 4 of 4 runs with 1 thread and 6 of 6 with 4.
- All five of bneradt's notes.
Verified by running it
pool_lockpasses 5 of 5.- I made the first
stop_for_migrationfail, with the debug assert removed as in release. Every request still got 200,migration_failurewas 1, both gauges returned to 0, and ASAN was clean. With the 15177a7 ordering it aborts. - Stress (global pool, 8 threads, parent): ASAN 3×60k and TSan 3×40k requests, no assert.
Non-blocking: the new test stays green without the inline purge
With purged_here = false at HttpSessionManager.cc:451 it still passes, and against the 15177a7 binary only the new "migrating session" log check fails. Another thread's purge event frees a slot before d-first's retries run out. A single-thread variant (exec_thread.limit: 1, max 1, sessions a-first, a-second, d-first) gets 502 3 of 3 at 15177a7 and 200 3 of 3 here. Worth adding.
Non-blocking: moving con after the stop loses an ordering
The event_loop.exchange in stop_for_migration used to follow ms.con.move and the options copy, which ordered them before the owning thread frees the VC. Now only closed does, a plain int behind an empty INK_WRITE_MEMORY_BARRIER (UnixNetVConnection.cc:1340-1350). TSan reports 34 Connection::close/move and 184 NetVCOptions races in detachForMigration over 3 runs. There are none at 15177a7, and none with only the move put back first. x86 hides it, but on arm64 the owner could close an fd the new VC owns. A release store after the copies, acquired by the owner before it frees the VC, would fix it.
Non-blocking: comments
EventIO.cc:208: epoll is always edge triggered (EventIO.h:35), so this ENOENT case can't be built.HttpSessionManager.h:155and.cc:444: the inline purge is skipped when the try lock fails.UnixNetVConnection.cc:1327still describes a delay that isn't in the tree.
bneradt
left a comment
There was a problem hiding this comment.
Reviewed f068f1f against the PR base, including the pool handoff, deferred closes, purge scheduling, and kqueue teardown. The earlier inline requests are addressed. I would fix the remaining migration publication race before merging; the inline comment follows up on the race Bryan already identified in his latest review.
Validation: a native standalone harness compiled this revision's EventIO.cc with minimal platform-header stubs. Open-pipe filter teardown, stopped modify/refresh, and 2,000 concurrent stop/refresh rounds passed in both optimized and ASan/UBSan builds. This checks EventIO rather than the complete VC/session lifetime. I did not run a full ATS build or AuTests; this worktree has no configured build.
Stopping the event loop before moving the socket left only a plain store of closed between the move and the owning thread's free, which reads closed in process_ready_list without a lock. On a weakly ordered CPU the owner could close the fd the new VC now owns. Make closed atomic so the store releases the move and the owner's load acquires it. Add a single net thread variant of the pool_lock autest that fails without the inline purge, and drop comments describing an epoll build and a test delay that do not exist.
do_io_close() decides whether to free the VC inline by reading the NetHandler mutex holder. A migration closes the VC from another thread while the owning thread locks and unlocks that mutex, so TSan reports the read as a race. Only a NetHandler's own thread ever holds its mutex, so checking the thread first keeps the result the same and lets a foreign thread skip the read.
bneradt
left a comment
There was a problem hiding this comment.
Re-reviewed 26024f1, focusing on f068f1f..26024f1 and checking the fixes against the pool/migration paths in the full PR. No remaining actionable findings from me.
The atomic NetEvent::closed addresses my previous P1: the default sequentially consistent store in do_io_close() and load in process_ready_list() provide the release/acquire ordering needed before the owning thread reclaims the old VC. I also checked the existing field uses, including the explicit .load() for the diagnostic's variadic argument. The owning-thread check before reading the NetHandler mutex holder avoids the foreign-thread read during migration. The single-thread replay now covers the inline purge case that the four-thread tests could miss.
Validation: reran the standalone harness against this revision's EventIO.cc, with minimal platform-header stubs: open-pipe kqueue filter teardown, stopped modify/refresh, and 2,000 concurrent stop/refresh rounds passed in both optimized and ASan/UBSan builds. Python syntax, all three replay YAML files, and git diff --check passed. All 14 reported GitHub/Jenkins checks are green, including the four AuTest shards and OSX. I did not independently run the full ATS build, AuTests, or a VC migration sanitizer workload.
|
@traeak, could we use “origin connections” in the title and opening paragraph? Suggested title:
Suggested description: With global and hybrid origin connection pools, the shared session pool mutex was held while migrating pooled connections between net threads and closing sessions. This put socket and TLS work inside a lock shared by the net threads, increasing contention when reusing origin connections. Limit the shared pool lock to session lookup, table updates, and detaching a connection for transfer. Attach migrated connections and close removed sessions after releasing the lock. This applies to pooled connections to origin servers and parent proxies. The change also fixes migration lifetime and event-registration races:
When Add kqueue unit tests and The existing performance measurements could stay below this description as a separate results paragraph. |
|
changed the PR title and description. |
bryancall
left a comment
There was a problem hiding this comment.
✅ Approve
I re-reviewed f068f1f95..26024f1ca (7 files, +154/-15) against the whole PR.
Fixed: the migration handoff ordering
closed is now atomic, and the store in do_io_close() is the last thing detachForMigration() does, so the moved socket and copied state are published before the owning thread can free the old VC.
Fixed: the single-thread purge test
pool_lock_single_thread.replay.yaml is the variant I asked for, with one net thread and server_max_connections: 1. Without the inline purge that setup got 502 on my runs.
Fixed: comments
The epoll ENOENT case, the try-lock wording in purge_keepalives, and the delay that wasn't in the tree are all done.
Nit: UnixNetVConnection.cc:272
reenable() can try-lock nh->mutex from another thread, so "only the owning thread ever holds it" overstates things, though the deferred close is still safe.
Nit: NetEvent.h:90-96
The comment on closed says stores release and loads acquire, but every access uses the default operators, which are sequentially consistent. That gives the ordering, but a reader will look for explicit memory_order_release/acquire. It also only mentions 1, while do_io_close(alerrno) stores -1.
* Shorten the session pool lock for origin connections The shared session pool mutex was held across migrating a pooled origin connection to another thread and across closing sessions, which put socket and TLS work inside a lock every thread contends for. The lock now covers only the pool tables and handing a connection off: - Migration is split into a detach under the lock and an attach after it is released. - Sessions that cannot be pooled, time out, or are closed by the origin are closed after the lock is released. - A pool purge has each thread close its own sessions. This fixes three race conditions in the migration of a pooled origin connection, all present before this change: - The migrating thread stopped the old connection's EventIO while the owning thread could still be rescheduling that connection, having failed the try lock on its VIO mutex. The owning thread then used the stopped EventIO, which hit ink_assert(event_loop) in debug builds and dereferenced a null event loop with kqueue. EventIO::modify and EventIO::refresh now do nothing once stopped. - With kqueue, stopping an EventIO did not remove its registration, and a migrated socket is never closed. The old thread's kqueue could keep delivering events addressed to a connection that thread had since freed. Migration now removes the registration, and a refresh racing with the removal undoes its own add. - When creating the new connection failed, the old one was closed a second time, after the owning thread could already have freed or reused it. The session no longer refers to the old connection once it has been detached. The pooled_server_connections gauge also no longer drifts after a purge. * Address review: stop before detaching, test the shared pool Stop the EventIO before moving the socket out of the old VC during a migration. A failed removal from the old thread's poller aborted the process; with the VC still owning the socket and SSL object an ordinary close recovers instead, and the caller treats it as a migration failure. The epoll stop also ignores ENOENT, which a level triggered build hits on every migration because disabling the read side already removed the fd. purge_keepalives() closes the current thread's pooled connections before it returns and asks the other threads to close theirs. Without the inline close the request that hit the connection limit used up its retries before any thread ran its purge event, so it failed with a 502 where it used to succeed. Connections on other threads are closed when those threads next run, so a few more requests can fail at the limit than when the caller purged synchronously after getting the pool lock. Add an autest for the global and hybrid pools that reuses pooled origin connections across net threads and purges them at server_max_connections, checking that the request which purged succeeds and that the pooled connection gauge returns to zero. The kqueue unit tests compile to nothing on Linux, so the pool changes had no coverage in CI. * Order the migration handoff before the owner frees the VC Stopping the event loop before moving the socket left only a plain store of closed between the move and the owning thread's free, which reads closed in process_ready_list without a lock. On a weakly ordered CPU the owner could close the fd the new VC now owns. Make closed atomic so the store releases the move and the owner's load acquires it. Add a single net thread variant of the pool_lock autest that fails without the inline purge, and drop comments describing an epoll build and a test delay that do not exist. * Check the owning thread before the NetHandler mutex holder on close do_io_close() decides whether to free the VC inline by reading the NetHandler mutex holder. A migration closes the VC from another thread while the owning thread locks and unlocks that mutex, so TSan reports the read as a race. Only a NetHandler's own thread ever holds its mutex, so checking the thread first keeps the result the same and lets a foreign thread skip the read. (cherry picked from commit 62a082d) [10.2.x: registered only test_EventIOMigration.cc (test_NetHandler.cc is master-only) and used master's Uranium pool_lock_*.test.yaml conversions in place of the AuTest files.]
* Shorten the session pool lock for origin connections The shared session pool mutex was held across migrating a pooled origin connection to another thread and across closing sessions, which put socket and TLS work inside a lock every thread contends for. The lock now covers only the pool tables and handing a connection off: - Migration is split into a detach under the lock and an attach after it is released. - Sessions that cannot be pooled, time out, or are closed by the origin are closed after the lock is released. - A pool purge has each thread close its own sessions. This fixes three race conditions in the migration of a pooled origin connection, all present before this change: - The migrating thread stopped the old connection's EventIO while the owning thread could still be rescheduling that connection, having failed the try lock on its VIO mutex. The owning thread then used the stopped EventIO, which hit ink_assert(event_loop) in debug builds and dereferenced a null event loop with kqueue. EventIO::modify and EventIO::refresh now do nothing once stopped. - With kqueue, stopping an EventIO did not remove its registration, and a migrated socket is never closed. The old thread's kqueue could keep delivering events addressed to a connection that thread had since freed. Migration now removes the registration, and a refresh racing with the removal undoes its own add. - When creating the new connection failed, the old one was closed a second time, after the owning thread could already have freed or reused it. The session no longer refers to the old connection once it has been detached. The pooled_server_connections gauge also no longer drifts after a purge. * Address review: stop before detaching, test the shared pool Stop the EventIO before moving the socket out of the old VC during a migration. A failed removal from the old thread's poller aborted the process; with the VC still owning the socket and SSL object an ordinary close recovers instead, and the caller treats it as a migration failure. The epoll stop also ignores ENOENT, which a level triggered build hits on every migration because disabling the read side already removed the fd. purge_keepalives() closes the current thread's pooled connections before it returns and asks the other threads to close theirs. Without the inline close the request that hit the connection limit used up its retries before any thread ran its purge event, so it failed with a 502 where it used to succeed. Connections on other threads are closed when those threads next run, so a few more requests can fail at the limit than when the caller purged synchronously after getting the pool lock. Add an autest for the global and hybrid pools that reuses pooled origin connections across net threads and purges them at server_max_connections, checking that the request which purged succeeds and that the pooled connection gauge returns to zero. The kqueue unit tests compile to nothing on Linux, so the pool changes had no coverage in CI. * Order the migration handoff before the owner frees the VC Stopping the event loop before moving the socket left only a plain store of closed between the move and the owning thread's free, which reads closed in process_ready_list without a lock. On a weakly ordered CPU the owner could close the fd the new VC now owns. Make closed atomic so the store releases the move and the owner's load acquires it. Add a single net thread variant of the pool_lock autest that fails without the inline purge, and drop comments describing an epoll build and a test delay that do not exist. * Check the owning thread before the NetHandler mutex holder on close do_io_close() decides whether to free the VC inline by reading the NetHandler mutex holder. A migration closes the VC from another thread while the owning thread locks and unlocks that mutex, so TSan reports the read as a race. Only a NetHandler's own thread ever holds its mutex, so checking the thread first keeps the result the same and lets a foreign thread skip the read. (cherry picked from commit 62a082d) [10.2.x: registered only test_EventIOMigration.cc (test_NetHandler.cc is master-only) and used master's Uranium pool_lock_*.test.yaml conversions in place of the AuTest files.]
|
Cherry-picked to the 10.2.x branch as v10.2.2 for the 10.2.2 release. |
With global and hybrid origin connection pools, the shared session pool mutex was held while migrating pooled connections between net threads and closing sessions. This put socket and TLS work inside a lock shared by the net threads, increasing contention when reusing origin connections.
Limit the shared pool lock to session lookup, table updates, and detaching a connection for transfer. Attach migrated connections and close removed sessions after releasing the lock. This applies to pooled connections to origin servers and parent proxies.
The change also fixes migration lifetime and event-registration races:
When server_max_connections triggers a purge, each net thread closes its own pooled connections outside the shared pool lock. The calling thread closes its sessions immediately if it can acquire the pool lock; other threads purge when they process their events. This can leave the connection count at the limit briefly and cause additional requests to fail compared with the previous synchronous purge. Removing sessions through the normal pool bookkeeping also fixes drift in pooled_server_connections after a purge.
Add kqueue unit tests and ATSReplayTest coverage for cross-thread reuse with global and hybrid pools, plus a single-thread test that checks the request triggering a purge succeeds on retry. The replay tests also check that the pooled and current connection gauges return to zero.