Skip to content

PERF-6638 Use a shared MongoClient across all worker threads - #41

Open
blink1073 wants to merge 3 commits into
mongodb-labs:productionfrom
blink1073:PERF-6638
Open

PERF-6638 Use a shared MongoClient across all worker threads#41
blink1073 wants to merge 3 commits into
mongodb-labs:productionfrom
blink1073:PERF-6638

Conversation

@blink1073

@blink1073 blink1073 commented Jun 16, 2026

Copy link
Copy Markdown
Member

Jira Ticket: PERF-6638

Whats Changed:

Use a shared MongoClient across all worker threads for the MongoDB driver instead of creating one client per worker process.

  • Added THREAD_SAFE = False sentinel to AbstractDriver; MongodbDriver opts in with THREAD_SAFE = True
  • MongodbDriver stores the client at the class level with reference counting so it is created once and closed only after the last worker finishes
  • tpcc.py uses ThreadPoolExecutor instead of multiprocessing.Pool when the driver is thread-safe; all other drivers continue using multiprocessing unchanged
  • Thundering-herd delay in loaderFunc is preserved for multiprocessing drivers and skipped for thread-safe drivers
  • Requires free-threaded Python (3.13t+) with the GIL disabled; without it, ThreadPoolExecutor cannot run Python threads in true parallel and the shared-client approach provides no throughput benefit over multiprocessing

Patch testing results:

Benchmarked on Atlas M40 (MongoDB 8.0, us-east-1), 50 warehouses, 50 clients, 60 s runs, 3 runs per variant, using Python 3.14.6 free-threaded (GIL disabled).

Three variants compared: baseline (production + pymongo 4.17.0), PERF-6638 (this PR + pymongo 4.17.0), and PERF-6638 + PYTHON-5272 (this PR + pymongo 4.18.0.dev0 with TLS session caching).

Run baseline (tpmC) PERF-6638 (tpmC) PERF-6638 + PYTHON-5272 (tpmC)
1 5918 6013 6297
2 5591 6613 6539
3 6143 6360 6416
Average 5884 6329 6417
vs baseline +7.6% +9.1%

Related PRs: PYTHON-5272 Implement TLS session resumption for connections

Switch the MongoDB driver from creating one MongoClient per worker to a
single shared client managed at the class level. Workers now run as
threads (ThreadPoolExecutor) instead of separate processes when the
driver declares THREAD_SAFE=True, allowing genuine client sharing via
PyMongo's built-in thread-safe connection pool.

Other drivers are unaffected and continue to use multiprocessing.Pool.
@blink1073
blink1073 marked this pull request as ready for review June 16, 2026 12:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant