Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
name: Test
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
services:
redis:
image: redis:7-alpine
ports: ['6379:6379']
options: --health-cmd "redis-cli ping" --health-interval 5s --health-retries 5
env:
SIDEKIQ_FIBER_TEST_REDIS_URL: redis://127.0.0.1:6379/0
steps:
- uses: actions/checkout@v4
- uses: ruby/setup-ruby@v1
with:
ruby-version: '3.4.10'
bundler-cache: true
- run: bundle exec rspec
3 changes: 1 addition & 2 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,4 @@ source "https://rubygems.org"

gemspec

gem "sidekiq", ">= 7.0"
gem "async", ">= 2.0"
gem "excon", "= 0.112.0"
207 changes: 44 additions & 163 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,188 +1,69 @@
# sidekiq-fiber
# sidekiq-fiber

Experimental capsule-level fiber execution for Sidekiq. Not yet validated for
production. No application performance claims follow from the standalone
`bench/throughput.rb` example: it bypasses Sidekiq, Redis, and Rails.

Fiber-based concurrency for IO-bound Sidekiq jobs.
## Supported runtime

If your jobs mostly wait on network calls — LLM APIs, HTTP requests, S3 — threads are the wrong tool. A thread blocks completely during IO. With 20 threads and 1500 queued jobs, you're processing 20 at a time and the rest sit idle.
CRuby 3.4, Sidekiq 8.0.10, Async 2.45.0, io-event 1.22.0, and
connection_pool 2.5.5. When present, ActiveRecord must be 8.1.3.1 and
Sidekiq Pro/Enterprise must both be 8.0.3. Compatibility checks reject other
loaded versions; commercial integration requires separate private tests.

This gem helps you solve this by using Ruby Fibers which take up a few kb per fiber and can help process 100s of fibers per thread.

## How it works

Normal Sidekiq:
```
Thread → fetch job → perform (blocks on IO) → fetch next
```

With sidekiq-fiber:
```
Thread → fetch job 1 → schedule as fiber → hits IO, suspends
→ fetch job 2 → schedule as fiber → hits IO, suspends
→ fetch job 3 → schedule as fiber → running
→ job 1 resumes (IO done) → completes → fetch job 4
```

One thread. Many concurrent fibers. No blocking.

## Requirements

- Ruby 3.2+
- Sidekiq 7.0+
- Jobs must use fiber-aware IO clients (see table below)

## Installation
Require the gem only in the dedicated worker process. Rails applications must
set `config.active_support.isolation_level = :fiber` before initialization.
The gem does not patch ActiveRecord connection ownership.

```ruby
gem "sidekiq-fiber"
```

## Usage

**1. Configure a dedicated fiber capsule**

```ruby
# config/initializers/sidekiq.rb
require "sidekiq-fiber"

Sidekiq.configure_server do |config|
config[:fiber_concurrency] = 50 # max concurrent fibers per thread

config.capsule("fiber") do |cap|
cap.concurrency = 20 # threads
cap.queues = ["llm_jobs", "api_calls"]
cap.processor_class = Sidekiq::Fiber::Processor
end
end
```

**2. Opt in per job**

```ruby
class MyLlmJob
include Sidekiq::Worker
include Sidekiq::Fiber::Worker # opt in — you are responsible for fiber-safe IO

def perform(id)
# Net::HTTP is fiber-aware in Ruby 3.2+ — yields during socket wait
response = Net::HTTP.get(URI("https://api.openai.com/..."))
process(response)
config.capsule("front") do |capsule|
capsule.queues = %w[front front_bulk]
capsule.concurrency = 16
Sidekiq::Fiber.configure(capsule, scheduler_threads: 1)
end
end
```

**3. Add the Web UI tab (optional)**
Capsule concurrency is the total number of in-flight jobs, not a multiplier
per scheduler thread. HTTP and database pools remain separately bounded.
Fetch follows the configured fetcher's queue priority; it does not preempt
running jobs. Every job on a selected capsule runs in a fiber, without markers
or fallback. Other capsules keep Sidekiq's normal manager.

```ruby
# config/routes.rb
require "sidekiq/fiber/web"

Sidekiq::Web.configure do |config|
config.register Sidekiq::Fiber::Web,
name: "sidekiq-fiber",
tab: "Fibers",
index: "fiber-stats",
root_dir: Gem.loaded_specs["sidekiq-fiber"].gem_dir
end
```
## Execution contract

## Fiber-safe IO
Each runner owns a fresh job fiber and an upstream processor instance. Sidekiq
retains middleware, retry, dead-job handling, and acknowledgment. Job bodies
must use scheduler-compatible I/O and must join any child work. Child fibers
inherit capsule and Redis routing, never checked-out connections.

You're responsible for using fiber-aware clients. Blocking IO freezes the whole thread.
Ruby's `Fiber#raise` does not honor `Thread.handle_interrupt`. Shutdown is
therefore injected only into job bodies, never fetch, middleware accounting,
retry handling, or acknowledgment. ConnectionPool checkout/checkin are also
protected. Jobs must not rely on additional thread interrupt masks.

| Client | Fiber-aware in Ruby 3.2? |
|---|---|
| `Net::HTTP` | ✅ Yes — via fiber scheduler |
| `Faraday` (net-http adapter) | ✅ Yes |
| `HTTParty` | ✅ Yes (uses Net::HTTP) |
| `ActiveRecord` queries | ✅ Yes — with our connection pool patch |
| `Typhoeus` | ❌ No — uses libcurl |
Quiet stops fetching. At the deadline, the supervisor invokes the configured
fetcher's recovery, requests interruption at safe job boundaries, and allows
up to three seconds for cleanup. The owning Sidekiq process must then exit;
this is not an in-process restart interface. Delivery remains at least once.

### ActiveRecord connection pool
Standard Sidekiq work/busy and processed/failed reporting use distinct
process-qualified runner identities and Sidekiq's periodic publication. There
is no custom dashboard or per-job custom Redis statistics.

sidekiq-fiber patches `ActiveRecord::ConnectionPool` to use `Fiber.current` as the connection cache key instead of `Thread.current`. Each fiber gets its own connection slot.
## Verification

Keep this in mind when sizing your DB pool:

```
max DB connections = threads × fiber_concurrency
```sh
bundle exec rspec
```

If your DB pool is 100 and you have 20 threads, set `fiber_concurrency` to 5 or lower. The Web UI will warn you when you're over this limit

## Capacity planning

```
max concurrent fibers = capsule.concurrency × fiber_concurrency
max DB connections = capsule.concurrency × fiber_concurrency
peak memory (HTTP) ≈ max concurrent fibers × ~50KB per connection
```

## Benchmark

Measured on Ruby 3.2.2, MacBook Air M2.
**Thread model:** 20 threads, one job at a time (max 20 concurrent)
**Fiber model:** 20 threads × 50 fibers (max 1000 concurrent)

### Part 1 — sleep() simulation (fixed latency)

`sleep()` is fiber-scheduler aware in Ruby 3.2. In a thread it blocks completely. In a fiber it yields, so other fibers can run. Results are clean and predictable here.

| Scenario | Jobs | IO wait | Threads | Fibers | Speedup |
|---|---|---|---|---|---|
| Light | 50 | 0.1s | 0.32s | 0.10s | **3.0x** |
| Medium | 200 | 0.5s | 5.04s | 0.51s | **9.9x** |
| Heavy | 500 | 1.0s | 25.10s | 1.02s | **24.7x** |

### Part 2 — Real HTTP calls (variable latency)

Jobs make actual `Net::HTTP` requests to a local WEBrick server that responds after a random delay. Real socket IO. `Net::HTTP` in Ruby 3.2 hooks into the fiber scheduler — the socket read suspends the fiber and resumes it when data arrives.

| Scenario | Jobs | Latency range | Threads | Fibers | Speedup |
|---|---|---|---|---|---|
| Fast API | 50 | 0.05s–0.3s | 0.63s | 0.31s | **2.1x** |
| Medium API | 100 | 0.5s–2.0s | 7.64s | 2.06s | **3.7x** |
| LLM-like | 50 | 2.0s–8.0s | 16.40s | 7.84s | **2.1x** |
| **Real burst** | **1500** | **0.5s–2.0s** | **95.46s** | **17.44s** | **5.5x** |

### Inference

**Speedup scales with job_count / thread_count.** The more jobs you have relative to threads, the more fibers help. The Heavy scenario hits 24.7x because 500 jobs / 20 threads = 25 serial batches — fibers collapse that to 1. (Best usecase)

**The LLM-like scenario (50 jobs, 2-8s) is only 2.1x** because with 50 jobs and 1000 fiber slots, all 50 start immediately. Both approaches then wait for the slowest request (~8s). Fibers don't make requests faster — they stop threads from sitting idle during IO.

**The Real burst scenario (1500 jobs, 0.5-2.0s) is the honest one** — closest to high traffic production LLM workloads. Threads: 95s. Fibers: 17s. Threads process 20 at a time across 75 serial batches. Fibers process up to 1000 across 2 batches.

**Memory:** the Real burst run peaked at +52.9MB for fibers vs +3.3MB for threads. 1000 concurrent HTTP connections means 1000 open sockets with buffers and response objects in memory. Set `fiber_concurrency` based on your memory budget, not just throughput.

To reproduce:

```bash
bundle exec ruby bench/throughput.rb
```

## Web UI

The optional "Fibers" tab shows:

- **Global health** — active fibers, semaphore utilization, DB connection warning
- **Per-thread breakdown** — semaphore fill, throughput, blocking IO detection
- **In-flight fibers** — long-running fiber alerts (> 30s)

**Blocking IO detection:** if a thread has active fibers but zero completions for > 60 seconds, the UI flags it. This catches jobs accidentally using non-fiber-aware clients that freeze the whole thread.

## Design decisions

**Why a dedicated capsule, not mixed with normal jobs?**
Fiber and non-fiber jobs on the same processor share thread-level interrupt handling and connection pool state in ways that are subtle to reason about. A dedicated capsule makes the boundary structural and hence avoid accidental issues.

**Why the `async` gem for the event loop?**
The fiber scheduler interface in Ruby 3.2 has edge cases around IO readiness, timeout handling, and signal interrupts. `async` is battle tested and I didn't want to reinvent the wheel for this.

**Why patch `connection_cache_key` instead of a custom pool?**
The patch is 3 lines and uses the pool's designed extension point. A custom pool would duplicate hundreds of lines of connection management logic and diverge from ActiveRecord's battle-tested implementation.

**Why opt-in per job instead of per queue?**
Writing fiber-safe code requires deliberate choices about which IO clients you use. Making it explicit at the job class level enforces that — a queue declaration hides it. If you use a blocking client inside a fiber job, the whole thread stalls silently. Explicit opt-in helps the developers make accidental mistakes.
Boundary tests cover capacity, acknowledgment, protected shutdown phases,
connection handoff, and recovery. Before deployment, additionally verify real
Redis/SuperFetch, Rails transactions and executor cleanup, commercial
middleware, HTTPS timeouts, and equal-resource workload benchmarks.

## License

Expand Down
4 changes: 1 addition & 3 deletions demo/Gemfile
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
source "https://rubygems.org"

ruby "3.2.2"
ruby "3.4.10"

gem "sidekiq", "~> 7.0"
gem "async", ">= 2.0"
gem "sidekiq-fiber", path: ".."
gem "puma"
gem "rack"
Expand Down
10 changes: 0 additions & 10 deletions demo/config.ru
Original file line number Diff line number Diff line change
@@ -1,21 +1,11 @@
require "sidekiq"
require "sidekiq/web"
require "sidekiq-fiber"
require "sidekiq/fiber/web"
require "rack/session"

Sidekiq.configure_client do |config|
config.redis = { url: "redis://localhost:6379/0" }
end

Sidekiq::Web.configure do |config|
config.register Sidekiq::Fiber::Web,
name: "sidekiq-fiber",
tab: "Fibers",
index: "fiber-stats",
root_dir: File.expand_path("../web", __dir__)
end

use Rack::Session::Cookie,
secret: File.read(".session.key").strip,
same_site: true,
Expand Down
3 changes: 1 addition & 2 deletions demo/jobs.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
# Uses sleep() which is fiber-aware in Ruby 3.2+.
class FakeLlmJob
include Sidekiq::Job
include Sidekiq::Fiber::Worker

def perform(id, delay)
puts "[fiber] job #{id} started (will sleep #{delay}s)"
Expand All @@ -16,7 +15,7 @@ def perform(id, delay)
end
end

# A normal job with no fiber opt-in — runs inline on the thread.
# Runs on the processor selected by its queue's capsule.
class NormalJob
include Sidekiq::Job

Expand Down
7 changes: 2 additions & 5 deletions demo/worker.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,11 @@
Sidekiq.configure_server do |config|
config.redis = { url: "redis://localhost:6379/0" }

# fiber_concurrency controls max concurrent fibers per thread
config[:fiber_concurrency] = 20

# dedicated fiber capsule — separate from normal jobs
config.capsule("fiber") do |cap|
cap.concurrency = 2 # 2 threads × 20 fibers = 40 concurrent fiber jobs
cap.concurrency = 16
cap.queues = ["fiber"]
cap.processor_class = Sidekiq::Fiber::Processor
Sidekiq::Fiber.configure(cap, scheduler_threads: 1)
end
end

Expand Down
7 changes: 3 additions & 4 deletions lib/sidekiq-fiber.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
require "async"

require_relative "sidekiq/fiber/version"
require_relative "sidekiq/fiber/worker"
require_relative "sidekiq/fiber/processor"
require_relative "sidekiq/fiber/connection_pool_patch"
require_relative "sidekiq/fiber/manager_patch"
require_relative "sidekiq/fiber/supervisor"
require_relative "sidekiq/fiber/routing"
require_relative "sidekiq/fiber/compatibility"
Loading
Loading