Fibers and Async
suggest changeRuby offers multiple concurrency models: operating system threads (Thread), isolated parallel actors (Ractor), and cooperative coroutines (Fiber). Since Ruby 3.0, the introduction of the Fiber Scheduler and the modern Async ecosystem has transformed Ruby into a formidable platform for high-throughput, non-blocking asynchronous I/O.
1. What Are Fibers?
A Fiber is a lightweight, cooperative concurrency primitive managed entirely in user space by the Ruby runtime.
Fibers vs. Threads
| Feature | Thread |
Fiber |
|---|---|---|
| Scheduling | Preemptive (managed by VM / OS) | Cooperative (yields control explicitly or via scheduler) |
| Context Switching | Higher overhead; requires OS / VM synchronization | Negligible overhead (sub-microsecond) |
| Memory Consumption | ~1 MB stack per thread | ~16 KB initial stack per fiber |
| Concurrency Scale | Hundreds or low thousands | Tens of thousands or hundreds of thousands |
2. Basic Fiber Usage: resume and yield
A Fiber does not execute until it is explicitly started with resume. It can pause execution at any point by calling Fiber.yield, returning control and an optional value back to the caller:
# Producer fiber generating numbers cooperatively
generator = Fiber.new do |start_value|
current = start_value
loop do
Fiber.yield(current)
current += 2
end
end
puts generator.resume(10) #=> 10
puts generator.resume #=> 12
puts generator.resume #=> 14
puts generator.alive? #=> true
Values passed to resume become the return value of Fiber.yield inside the fiber, enabling bidirectional message passing between the caller and the fiber.
3. The Ruby 3+ Fiber Scheduler
Prior to Ruby 3.0, if code running inside a fiber performed a blocking operation (such as Kernel.sleep or reading a socket), the entire underlying operating system thread blocked.
In Ruby 3.0, CRuby introduced the Fiber Scheduler Interface (Fiber.set_scheduler). When a non-blocking scheduler is registered, standard synchronous Ruby methods:
Kernel.sleepIO#read,IO#write,IO#waitSocket#accept,Socket#connect
automatically detect when they must wait on I/O, seamlessly yield control of the current fiber to other ready fibers, and resume once the socket is ready. Your application code remains readable, linear, and synchronous without "callback hell" or Promise chaining.
4. The Modern Async Framework
The async gem is the standard, production-ready Fiber Scheduler implementation for Ruby 3+.
Install the gem:
gem install async
Running Concurrent Tasks
Wrap asynchronous code inside an Async block:
require 'async'
Async do |parent_task|
puts "Main event loop started"
# Spawn concurrent lightweight task 1
parent_task.async do
puts "Task 1: Fetching database record..."
sleep 0.5 # Automatically non-blocking under Async!
puts "Task 1: Completed!"
end
# Spawn concurrent lightweight task 2
parent_task.async do
puts "Task 2: Sending notification email..."
sleep 0.2
puts "Task 2: Completed!"
end
puts "Both tasks spawned. Awaiting completion..."
end
puts "All tasks finished."
Output:
Main event loop started
Task 1: Fetching database record...
Task 2: Sending notification email...
Both tasks spawned. Awaiting completion...
Task 2: Completed!
Task 1: Completed!
All tasks finished.
Managing Groups of Tasks with Async::Barrier
Use an Async::Barrier to coordinate, wait for, or limit concurrency across dozens or thousands of concurrent jobs:
require 'async'
require 'async/barrier'
require 'async/semaphore'
urls = (1..5).map { |id| "https://jsonplaceholder.typicode.com/todos/#{id}" }
Async do
barrier = Async::Barrier.new
# Limit maximum concurrent network connections to 2
semaphore = Async::Semaphore.new(2, parent: barrier)
urls.each do |url|
semaphore.async do
puts "Starting download: #{url}"
sleep 0.3 # Simulating network delay
puts "Finished download: #{url}"
end
end
# Wait for all tasks within barrier to complete
barrier.wait
puts "All downloads finished successfully."
end
5. Non-Blocking HTTP with async-http
The async-http gem provides an asynchronous HTTP client and server designed specifically for fibers:
gem install async-http
require 'async'
require 'async/http/endpoint'
require 'async/http/client'
Async do
endpoint = Async::HTTP::Endpoint.parse("https://httpbin.org")
client = Async::HTTP::Client.new(endpoint)
response = client.get("/get")
puts "Status: #{response.status}"
puts "Body length: #{response.read.length} bytes"
ensure
client&.close
end
Servers built on this stack (such as Falcon) can handle tens of thousands of concurrent WebSocket and HTTP/2 connections on a single server process with minimal memory overhead.
Best Practices
- Avoid Long-Running CPU Computations in Fibers: Fibers are cooperative. If a single fiber executes an intense CPU calculation (such as password hashing or cryptography) without yielding, all other fibers on that thread will starve. For CPU-bound operations, offload work to background workers or
Ractor. - Always Wrap in
Async do ... end: The Fiber Scheduler is scoped to theAsyncblock. Outside of an active scheduler block, standard calls likesleeprevert to blocking the entire thread. - Use Semaphores for Throttling: Never spawn 50,000 unbounded network requests simultaneously. Use
Async::Semaphoreto cap concurrency to what the remote host or network can accommodate.