-
-
Notifications
You must be signed in to change notification settings - Fork 0
feat(process): add async/fiber execution mode for workers #112
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
477bb88
feat(process): add async/fiber execution mode for workers
mhenrixon 24d5667
fix(ci): resolve rubocop offenses and rename command
mhenrixon 792877a
fix: address PR review feedback
mhenrixon 1d15fc7
fix(streams): handle IOError on listener shutdown gracefully
mhenrixon 4a6f016
fix(test): GC before allocation leak test for Ruby 3.3 stability
mhenrixon 865422f
fix(streams): log and reconnect on unexpected IOError in listener
mhenrixon 6ffa884
fix(test): scope allocation leak test to lib/pgbus/ files only
mhenrixon File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
File renamed without changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,130 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| # Connection Pool Benchmark | ||
| # Measures peak active Postgres connections under varying concurrency | ||
| # for ThreadPool vs AsyncPool execution modes. | ||
| # | ||
| # REQUIRES: PGBUS_DATABASE_URL environment variable | ||
| # | ||
| # Usage: | ||
| # PGBUS_DATABASE_URL=postgres://user@localhost/pgbus_test ruby benchmarks/connection_pool_bench.rb | ||
|
|
||
| require "json" | ||
| require "securerandom" | ||
| require "concurrent" | ||
| require "pgbus" | ||
| require "pg" | ||
|
|
||
| DATABASE_URL = ENV.fetch("PGBUS_DATABASE_URL") do | ||
| warn "PGBUS_DATABASE_URL not set. This benchmark requires a real PostgreSQL database." | ||
| warn "Example: PGBUS_DATABASE_URL=postgres://user@localhost:5432/pgbus_test ruby benchmarks/connection_pool_bench.rb" | ||
| exit 1 | ||
| end | ||
|
|
||
| Pgbus.configure do |c| | ||
| c.logger = Logger.new(IO::NULL) | ||
| c.queue_prefix = "pgbus_connbench" | ||
| c.default_queue = "default" | ||
| c.stats_enabled = false | ||
| c.database_url = DATABASE_URL | ||
| end | ||
|
|
||
| def monitor_connection(url) | ||
| PG.connect(url) | ||
| end | ||
|
|
||
| def count_active_connections(conn, prefix = "pgbus_connbench") | ||
| pattern = "%#{prefix}%" | ||
| result = conn.exec_params( | ||
| "SELECT count(*) FROM pg_stat_activity " \ | ||
| "WHERE application_name LIKE $1 OR query LIKE $1", | ||
| [pattern] | ||
| ) | ||
| result[0]["count"].to_i | ||
| rescue PG::Error => e | ||
| warn "Connection count query failed: #{e.message}" | ||
| 0 | ||
| end | ||
|
|
||
| def update_peak(peak, current) | ||
| old = peak.value | ||
| peak.compare_and_set(old, current) if current > old | ||
| end | ||
|
|
||
| def measure_peak_connections(mode:, capacity:, tasks:, monitor_conn:) | ||
| pool = if mode == :threads | ||
| Pgbus::ExecutionPools::ThreadPool.new(capacity: capacity) | ||
| else | ||
| Pgbus::ExecutionPools::AsyncPool.new(capacity: capacity) | ||
| end | ||
|
|
||
| peak = Concurrent::AtomicFixnum.new(0) | ||
| done = Concurrent::CountDownLatch.new(tasks) | ||
|
|
||
| # Monitor thread samples pg_stat_activity during the benchmark | ||
| stop_monitoring = Concurrent::AtomicBoolean.new(false) | ||
| monitor = Thread.new do | ||
| while stop_monitoring.false? | ||
| current = count_active_connections(monitor_conn) | ||
| update_peak(peak, current) | ||
| sleep 0.01 | ||
| end | ||
| end | ||
|
|
||
| tasks.times do | ||
| pool.post do | ||
| # Simulate a real job: query the database | ||
| conn = PG.connect(DATABASE_URL) | ||
| conn.exec("SELECT pg_sleep(0.01)") | ||
| conn.close | ||
| done.count_down | ||
| rescue PG::Error | ||
| done.count_down | ||
| end | ||
| end | ||
|
|
||
| done.wait(30) | ||
| stop_monitoring.make_true | ||
| monitor.join(2) | ||
|
|
||
| pool.shutdown | ||
| pool.wait_for_termination(10) | ||
|
|
||
| peak.value | ||
| end | ||
|
|
||
| puts "=" * 70 | ||
| puts "Connection Pool Benchmark" | ||
| puts "Database: #{DATABASE_URL.sub(%r{//[^@]+@}, "//***@")}" | ||
| puts "=" * 70 | ||
|
|
||
| monitor_conn = monitor_connection(DATABASE_URL) | ||
|
|
||
| configs = [ | ||
| { mode: :threads, capacity: 5, tasks: 20 }, | ||
| { mode: :threads, capacity: 10, tasks: 40 }, | ||
| { mode: :threads, capacity: 25, tasks: 100 }, | ||
| { mode: :async, capacity: 50, tasks: 200 }, | ||
| { mode: :async, capacity: 100, tasks: 400 } | ||
| ] | ||
|
|
||
| header = ["Mode", "Capacity", "Tasks", "Peak Connections"] | ||
| puts format("\n%-12s %-10s %-8s %-20s", *header) | ||
| puts "-" * 55 | ||
|
|
||
| configs.each do |cfg| | ||
| peak = measure_peak_connections( | ||
| mode: cfg[:mode], | ||
| capacity: cfg[:capacity], | ||
| tasks: cfg[:tasks], | ||
| monitor_conn: monitor_conn | ||
| ) | ||
| puts format("%-12s %-10d %-8d %-20d", cfg[:mode], cfg[:capacity], cfg[:tasks], peak) | ||
| sleep 1 # let connections drain between runs | ||
| end | ||
|
|
||
| monitor_conn.close | ||
|
|
||
| puts "\nExpected: async mode should show significantly fewer peak connections" | ||
| puts "than thread mode, regardless of fiber capacity." | ||
| puts "\nDone." | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,167 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| require_relative "bench_helper" | ||
|
|
||
| # Execution Pool Benchmark | ||
| # Compares ThreadPool vs AsyncPool throughput, latency, and memory. | ||
| # | ||
| # Usage: | ||
| # ruby benchmarks/execution_pool_bench.rb | ||
|
|
||
| CAPACITIES = [10, 50].freeze | ||
|
|
||
| def build_thread_pool(capacity) | ||
| Pgbus::ExecutionPools::ThreadPool.new(capacity: capacity) | ||
| end | ||
|
|
||
| def build_async_pool(capacity) | ||
| Pgbus::ExecutionPools::AsyncPool.new(capacity: capacity) | ||
| end | ||
|
|
||
| # --- 1. No-op throughput (scheduling overhead) --- | ||
|
|
||
| puts "=" * 70 | ||
| puts "1. No-op throughput — scheduling overhead (IPS)" | ||
| puts "=" * 70 | ||
|
|
||
| CAPACITIES.each do |cap| | ||
| Benchmark.ips do |x| | ||
| x.config(warmup: 2, time: 5) | ||
|
|
||
| x.report("ThreadPool(#{cap}) no-op") do | ||
| pool = build_thread_pool(cap) | ||
| done = Concurrent::CountDownLatch.new(cap) | ||
| cap.times { pool.post { done.count_down } } | ||
| done.wait(10) | ||
| pool.shutdown | ||
| pool.wait_for_termination(5) | ||
| end | ||
|
|
||
| x.report("AsyncPool(#{cap}) no-op") do | ||
| pool = build_async_pool(cap) | ||
| done = Concurrent::CountDownLatch.new(cap) | ||
| cap.times { pool.post { done.count_down } } | ||
| done.wait(10) | ||
| pool.shutdown | ||
| pool.wait_for_termination(5) | ||
| end | ||
|
|
||
| x.compare! | ||
| end | ||
| puts | ||
| end | ||
|
|
||
| # --- 2. I/O-bound throughput (fiber advantage zone) --- | ||
|
|
||
| puts "=" * 70 | ||
| puts "2. I/O-bound throughput — sleep(0.01) simulating DB I/O" | ||
| puts "=" * 70 | ||
|
|
||
| CAPACITIES.each do |cap| | ||
| Benchmark.ips do |x| | ||
| x.config(warmup: 1, time: 5) | ||
|
|
||
| x.report("ThreadPool(#{cap}) I/O") do | ||
| pool = build_thread_pool(cap) | ||
| done = Concurrent::CountDownLatch.new(cap) | ||
| cap.times do | ||
| pool.post do | ||
| sleep(0.01) | ||
| done.count_down | ||
| end | ||
| end | ||
| done.wait(10) | ||
| pool.shutdown | ||
| pool.wait_for_termination(5) | ||
| end | ||
|
|
||
| x.report("AsyncPool(#{cap}) I/O") do | ||
| pool = build_async_pool(cap) | ||
| done = Concurrent::CountDownLatch.new(cap) | ||
| cap.times do | ||
| pool.post do | ||
| sleep(0.01) | ||
| done.count_down | ||
| end | ||
| end | ||
| done.wait(10) | ||
| pool.shutdown | ||
| pool.wait_for_termination(5) | ||
| end | ||
|
|
||
| x.compare! | ||
| end | ||
| puts | ||
| end | ||
|
mhenrixon marked this conversation as resolved.
|
||
|
|
||
| # --- 3. Memory overhead --- | ||
|
|
||
| puts "=" * 70 | ||
| puts "3. Memory overhead — 1000 tasks" | ||
| puts "=" * 70 | ||
|
|
||
| [10, 50].each do |cap| | ||
| puts "\n--- Capacity: #{cap} ---" | ||
|
|
||
| %i[threads async].each do |mode| | ||
| report = MemoryProfiler.report do | ||
| 100.times do | ||
| pool = if mode == :threads | ||
| build_thread_pool(cap) | ||
| else | ||
| build_async_pool(cap) | ||
| end | ||
| done = Concurrent::CountDownLatch.new(cap) | ||
| cap.times { pool.post { done.count_down } } | ||
| done.wait(10) | ||
| pool.shutdown | ||
| pool.wait_for_termination(5) | ||
| end | ||
| end | ||
|
|
||
| puts "\n#{mode.upcase} pool (#{cap} capacity × 100 iterations):" | ||
| puts " Total allocated: #{report.total_allocated_memsize} bytes" | ||
| puts " Total retained: #{report.total_retained_memsize} bytes" | ||
| puts " Allocated objects: #{report.total_allocated}" | ||
| puts " Retained objects: #{report.total_retained}" | ||
| end | ||
| end | ||
|
|
||
| # --- 4. Latency percentiles --- | ||
|
|
||
| puts "\n#{"=" * 70}" | ||
| puts "4. Latency percentiles — single task completion time" | ||
| puts "=" * 70 | ||
|
|
||
| SAMPLES = 500 | ||
|
|
||
| %i[threads async].each do |mode| | ||
| pool = mode == :threads ? build_thread_pool(5) : build_async_pool(5) | ||
| latencies = [] | ||
|
|
||
| SAMPLES.times do | ||
| start = Process.clock_gettime(Process::CLOCK_MONOTONIC) | ||
| done = Concurrent::Event.new | ||
| pool.post { done.set } | ||
| done.wait(5) | ||
| elapsed = (Process.clock_gettime(Process::CLOCK_MONOTONIC) - start) * 1_000_000 # microseconds | ||
| latencies << elapsed | ||
| end | ||
|
|
||
| pool.shutdown | ||
| pool.wait_for_termination(5) | ||
|
|
||
| latencies.sort! | ||
| p50 = latencies[(SAMPLES * 0.50).to_i] | ||
| p95 = latencies[(SAMPLES * 0.95).to_i] | ||
| p99 = latencies[(SAMPLES * 0.99).to_i] | ||
|
|
||
| puts "\n#{mode.upcase} pool latency (#{SAMPLES} samples):" | ||
| puts " p50: #{p50.round(1)} µs" | ||
| puts " p95: #{p95.round(1)} µs" | ||
| puts " p99: #{p99.round(1)} µs" | ||
| puts " min: #{latencies.first.round(1)} µs" | ||
| puts " max: #{latencies.last.round(1)} µs" | ||
| end | ||
|
|
||
| puts "\nDone." | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.