Writing a Fiber scheduler

suggest change

Ruby 3.0 added the fiber scheduler interface. You register a scheduler object for a thread with Fiber.set_scheduler. From then on, when a non-blocking fiber does something that would block (sleep, reading a socket, Queue#pop, Mutex#lock, Thread#join), Ruby doesn't block the thread. It calls a method (a hook) on your scheduler, and the scheduler can switch to another fiber until the operation can go on.

That's how the async gem makes ordinary, synchronous-looking Ruby code concurrent. Fibers and Async shows how to use it. This article goes one level down and builds a small scheduler from scratch, so you can see what Async does under the hood. It's aimed at advanced readers. For real programs, use Async.

This article covers:

The examples were run with Ruby 4.0.

The interface

There is no Fiber::Scheduler class to subclass. The Ruby docs describe Fiber::Scheduler as an interface, and any object that has the right methods works:

Hook Called by Required
fiber(**opts, &block) Fiber.schedule { } yes
kernel_sleep(duration = nil) sleep yes
io_wait(io, events, timeout) IO that isn't ready: read, gets, write, accept, wait_readable, ... yes
block(blocker, timeout = nil) Mutex#lock, Queue#pop, ConditionVariable#wait, Thread#join, ... yes
unblock(blocker, fiber) the opposite of block, possibly from another thread yes
close thread exit, Fiber.set_scheduler(nil) yes
fiber_interrupt(fiber, exception) IO#close while another fiber waits on that IO (Ruby 4.0) Ruby 4.0 warns if missing
io_read, io_write, io_pread, io_pwrite IO reads and writes, using IO::Buffer no, falls back to io_wait
io_select IO.select no
process_wait(pid, flags) Process.wait no
address_resolve(hostname) DNS lookups (Addrinfo, TCPSocket.new) no
timeout_after(duration, klass, message, &block) Timeout.timeout no
blocking_operation_wait(work) blocking C calls that release the GVL (Ruby 3.4) no

The scheduler only applies to non-blocking fibers. The main fiber of a thread is blocking, so code in it behaves as before, even with a scheduler set. Fibers created by Fiber.schedule, or by Fiber.new(blocking: false), are non-blocking.

All the hooks follow the same pattern:

  1. Write down what the current fiber is waiting for: a time, an IO, a "please wake me up" flag.
  2. Call Fiber.yield to go back to the event loop.
  3. When the event loop sees that the fiber can continue, it calls fiber.resume.

The value passed to resume becomes the return value of Fiber.yield, and so of the hook.

A minimal scheduler

Here is a complete scheduler in about 120 lines. It uses IO.select to wait for IO and timers, a self-pipe to wake up IO.select from other threads, and plain hashes to remember who waits for what. Save it as scheduler.rb. The rest of the examples load it with require_relative "scheduler".

Warning[:experimental] = false # IO::Buffer is used internally, silence its warning

class SimpleScheduler
  def initialize
    @readable = {}  # io => fiber waiting to read
    @writable = {}  # io => fiber waiting to write
    @waiting  = {}  # fiber => wake-up time (monotonic seconds)
    @blocked  = {}  # fiber => true, for fibers parked in #block
    @ready    = []  # fibers woken by #unblock, maybe from another thread
    @raises   = []  # [fiber, exception] pairs from #fiber_interrupt
    @mutex    = Thread::Mutex.new
    @urgent_r, @urgent_w = IO.pipe # wakes up IO.select from #unblock
  end

  # --- hooks called by Ruby ---------------------------------------

  # Fiber.schedule { ... } ends up here
  def fiber(&block)
    fiber = Fiber.new(blocking: false, &block)
    fiber.resume
    fiber
  end

  # sleep(duration)
  def kernel_sleep(duration = nil)
    if duration
      @waiting[Fiber.current] = now + duration
    else
      @blocked[Fiber.current] = true # sleep forever, until woken
    end
    Fiber.yield
    true
  end

  # IO#read, IO#write, IO#wait_readable, ... when the IO is not ready
  def io_wait(io, events, timeout)
    fiber = Fiber.current
    @readable[io] = fiber if events.anybits?(IO::READABLE)
    @writable[io] = fiber if events.anybits?(IO::WRITABLE)
    @waiting[fiber] = now + timeout if timeout
    Fiber.yield # returns the ready events, or false on timeout
  ensure
    @readable.delete(io)
    @writable.delete(io)
    @waiting.delete(fiber)
  end

  # Mutex#lock, Queue#pop, ConditionVariable#wait, Thread#join, ...
  def block(blocker, timeout = nil)
    fiber = Fiber.current
    if timeout
      @waiting[fiber] = now + timeout
    else
      @blocked[fiber] = true
    end
    Fiber.yield
  ensure
    @waiting.delete(fiber)
    @blocked.delete(fiber)
  end

  # The opposite of #block. May be called from another thread.
  def unblock(blocker, fiber)
    @mutex.synchronize { @ready << fiber }
    @urgent_w.write_nonblock(".", exception: false)
  end

  # Ruby 4.0: IO#close on an IO another fiber is waiting on.
  def fiber_interrupt(fiber, exception)
    @mutex.synchronize { @raises << [fiber, exception] }
    @urgent_w.write_nonblock(".", exception: false)
  end

  # Called when the thread exits or Fiber.set_scheduler(nil) is called.
  def close
    run
  ensure
    @urgent_r.close
    @urgent_w.close
  end

  # --- the event loop ---------------------------------------------

  def run
    while @readable.any? || @writable.any? || @waiting.any? || @blocked.any? || @ready.any? || @raises.any?
      readable, writable = IO.select(
        [*@readable.keys, @urgent_r], @writable.keys, [], select_timeout
      )

      readable&.each do |io|
        if io == @urgent_r
          io.read_nonblock(1024, exception: false)
        elsif (fiber = @readable.delete(io))
          fiber.resume(IO::READABLE)
        end
      end
      writable&.each do |io|
        fiber = @writable.delete(io)
        fiber&.resume(IO::WRITABLE)
      end

      t = now
      @waiting.select { |_, at| at <= t }.each_key do |fiber|
        @waiting.delete(fiber)
        fiber.resume(false) if fiber.alive? # false means "timed out"
      end

      ready = @mutex.synchronize { @ready.slice!(0..) }
      ready.each do |fiber|
        @blocked.delete(fiber)
        fiber.resume if fiber.alive?
      end

      raises = @mutex.synchronize { @raises.slice!(0..) }
      raises.each { |fiber, error| fiber.raise(error) if fiber.alive? }
    end
  end

  private

  def now = Process.clock_gettime(Process::CLOCK_MONOTONIC)

  def select_timeout
    return 0 if @ready.any? || @raises.any?
    return nil if @waiting.empty?
    [@waiting.values.min - now, 0].max
  end
end

Some details worth pointing out:

This scheduler is for learning. It doesn't handle a fiber whose timeout fires at the same moment it's unblocked, it supports only one waiting fiber per IO, and IO.select gets slow with thousands of descriptors. Production schedulers use epoll, kqueue or io_uring.

Running fibers concurrently

Fiber.schedule asks the current scheduler to create a fiber. Here two fibers sleep at the same time:

require_relative "scheduler"

Fiber.set_scheduler(SimpleScheduler.new)

start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
elapsed = -> { (Process.clock_gettime(Process::CLOCK_MONOTONIC) - start).round(1) }

Fiber.schedule do
  puts "A: sleeping 0.3s"
  sleep 0.3
  puts "A: done at #{elapsed.()}"
end

Fiber.schedule do
  puts "B: sleeping 0.1s"
  sleep 0.1
  puts "B: done at #{elapsed.()}"
end

puts "main: both fibers scheduled at #{elapsed.()}"
A: sleeping 0.3s
B: sleeping 0.1s
main: both fibers scheduled at 0.0
B: done at 0.1
A: done at 0.3

Each sleep calls kernel_sleep, which yields back to the main fiber. The main fiber reaches the end of the script, Ruby calls close on the scheduler, and the event loop wakes up B after 0.1 seconds and A after 0.3. In total it takes 0.3 seconds, not 0.4.

If you want the loop to finish at a known point instead of at program exit, set the scheduler for a block and reset it afterwards. Fiber.set_scheduler(nil) calls close, which runs all remaining fibers to completion:

require_relative "scheduler"

def with_scheduler(scheduler)
  Fiber.set_scheduler(scheduler)
  yield
ensure
  Fiber.set_scheduler(nil) # calls scheduler.close, which runs the loop
end

with_scheduler(SimpleScheduler.new) do
  Fiber.schedule { sleep 0.2; puts "slow done" }
  Fiber.schedule { sleep 0.1; puts "fast done" }
  puts "block finished"
end

puts "after with_scheduler, scheduler: #{Fiber.scheduler.inspect}"
block finished
fast done
slow done
after with_scheduler, scheduler: nil

That's what Async do ... end does too: it installs a scheduler, runs the block in a task and waits for every child task before it returns.

Which operation calls which hook

To see the hooks in action, prepend a module that prints every call before passing it on to the real scheduler:

require "socket"
require "io/nonblock"
require_relative "scheduler"

module TraceHooks
  %i[fiber kernel_sleep io_wait block unblock close].each do |hook|
    define_method(hook) do |*args, **kw, &blk|
      shown = args.map do |a|
        case a
        when Numeric, nil then a.inspect
        else a.class.name
        end
      end
      puts "  [#{hook}(#{shown.join(", ")})]"
      super(*args, **kw, &blk)
    end
  end
end
SimpleScheduler.prepend(TraceHooks)

Fiber.set_scheduler(SimpleScheduler.new)

Fiber.schedule do
  puts "sleep:"
  sleep 0.05

  puts "Queue#pop:"
  q = Thread::Queue.new
  Thread.new { sleep 0.05; q << 1 }
  q.pop

  puts "Mutex#lock held by another fiber:"
  m = Thread::Mutex.new
  Fiber.schedule { m.synchronize { sleep 0.05 } }
  m.lock
  m.unlock

  puts "read from a socket with no data yet:"
  a, b = UNIXSocket.pair
  a.nonblock = true
  Thread.new { sleep 0.05; b.write "hi" }
  p a.readpartial(10)
end
  [fiber()]
sleep:
  [kernel_sleep(0.05)]
  [close()]
Queue#pop:
  [block(Thread::Queue, nil)]
  [unblock(Thread::Queue, Fiber)]
Mutex#lock held by another fiber:
  [fiber()]
  [kernel_sleep(0.05)]
  [block(Thread::Mutex, nil)]
  [unblock(Thread::Mutex, Fiber)]
read from a socket with no data yet:
  [io_wait(UNIXSocket, 1, nil)]
"hi"

A few things to notice:

The a.nonblock = true line (from io/nonblock) matters on Windows, where sockets are blocking by default. A read on a blocking socket blocks the whole thread and the scheduler never gets a chance to run. On Linux and macOS Ruby makes sockets non-blocking automatically, so the line is harmless there.

A concurrent TCP echo server

With io_wait in place, ordinary socket code becomes concurrent. Here a server handles each connection in its own fiber, and three clients connect at the same time. The server sleeps 0.2 seconds per request, but all three requests finish in about 0.2 seconds in total:

require "socket"
require "io/nonblock"
require_relative "scheduler"

Fiber.set_scheduler(SimpleScheduler.new)

server = TCPServer.new("127.0.0.1", 0) # port 0: pick any free port
port = server.addr[1]

# server: one fiber per connection
Fiber.schedule do
  3.times do
    client = server.accept
    client.nonblock = true
    Fiber.schedule do
      line = client.gets
      sleep 0.2 # pretend to do some slow work
      client.puts "echo: #{line}"
      client.close
    end
  end
  server.close
end

start = Process.clock_gettime(Process::CLOCK_MONOTONIC)

# three clients, all running at the same time
3.times do |i|
  Fiber.schedule do
    sock = TCPSocket.new("127.0.0.1", port)
    sock.nonblock = true
    sock.puts "hello #{i}"
    puts sock.gets
    sock.close
  end
end

Fiber.scheduler.run
elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start
puts "took #{elapsed.round(2)}s"
echo: hello 0
echo: hello 1
echo: hello 2
took 0.21s

There are no callbacks and no async/await keywords. accept, gets and puts look like blocking calls, but each one that has to wait calls io_wait, and the scheduler runs another fiber in the meantime. The example calls Fiber.scheduler.run directly so it can measure the time. When the main fiber finishes, close runs the loop again, but by then there's nothing left to do.

Closing an IO another fiber is waiting on

If one fiber closes an IO while another fiber waits on it, the waiting fiber has to get an IOError. In Ruby 4.0 this goes through the fiber_interrupt hook. Ruby prints warning: Scheduler should implement #fiber_interrupt if your scheduler doesn't have it. Our implementation queues the exception and raises it in the fiber from the event loop:

require "socket"
require "io/nonblock"
require_relative "scheduler"

Fiber.set_scheduler(SimpleScheduler.new)

a, b = UNIXSocket.pair
a.nonblock = true

Fiber.schedule do
  a.read(10)
rescue IOError => e
  puts "reader: #{e.class}: #{e.message}"
end

Fiber.schedule do
  sleep 0.1
  puts "closer: closing the socket"
  a.close
end
closer: closing the socket
reader: IOError: stream closed in another thread

Timeouts in hooks

block and io_wait receive a timeout when the caller asked for one, for example Queue#pop(timeout:) or IO#wait_readable(1). The scheduler only has to wake the fiber up when the time is over. Ruby then checks whether the queue still is empty and returns nil:

require_relative "scheduler"
Fiber.set_scheduler(SimpleScheduler.new)
q = Thread::Queue.new
Fiber.schedule do
  t = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  p q.pop(timeout: 0.1)
  p (Process.clock_gettime(Process::CLOCK_MONOTONIC) - t).round(1)
  p q.pop(timeout: 1)
end
Fiber.schedule { sleep 0.3; q << :late }
nil
0.1
:late

The first pop timed out after 0.1 seconds. The second one was woken by unblock when the other fiber pushed :late, long before its 1 second ran out.

To support Timeout.timeout the same way, a scheduler implements timeout_after. Async does, and that's why Timeout.timeout inside an Async task only interrupts the code at wait points. Cancellation and timeouts explains why that's much safer than the thread-based default.

Blocking and non-blocking fibers

Every fiber is either blocking or non-blocking. Only non-blocking fibers go through the scheduler:

require_relative "scheduler"

p Fiber.current.blocking?          # the main fiber is blocking
p Fiber.new { }.blocking?          # Fiber.new defaults to blocking: false
p Fiber.new(blocking: true) { }.blocking?

Fiber.set_scheduler(SimpleScheduler.new)

t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
ms = -> { ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - t0) * 1000).round(-1) }

Fiber.schedule do
  sleep 0.1
  puts "non-blocking fiber woke at #{ms.()}ms"
end

Fiber.schedule do
  Fiber.blocking do
    p Fiber.blocking?
    sleep 0.2                       # blocks the whole thread, no scheduler
  end
  puts "blocking section done at #{ms.()}ms"
end

puts "main reached the end at #{ms.()}ms"
true
false
true
1
blocking section done at 200ms
main reached the end at 200ms
non-blocking fiber woke at 200ms

Fiber.blocking { } (Ruby 3.2) temporarily makes the current fiber blocking. Inside the block sleep really blocks the thread, so the first fiber, which wanted to wake up after 100ms, couldn't run until 200ms. Fiber.blocking? returns false for a non-blocking fiber and a positive integer for a blocking one.

Schedulers use Fiber.blocking for their own IO, so that an operation inside a hook doesn't call the scheduler again. You'll see it in the io_read example below.

Note that Fiber.new creates non-blocking fibers by default. If you use fibers by hand with resume and Fiber.yield (as generators, for example) while a scheduler is active, a sleep inside such a fiber goes to the scheduler, which will later resume the fiber from its event loop. Create those fibers with blocking: true if they shouldn't take part.

Fiber storage: Fiber[:key]

With many requests running on one thread, Thread.current[:request_id] doesn't work for request-scoped data. Despite its name, Thread.current[] is fiber-local: each fiber has its own copy, and a new fiber starts with none of the values. Ruby 3.2 added fiber storage, accessed with Fiber[] and Fiber[]=. A new fiber (or thread) gets a copy of its parent's storage:

Fiber[:request_id] = "req-42"
Thread.current[:old_style] = "fiber-local"

Fiber.new do
  p Fiber[:request_id]            # inherited
  p Thread.current[:old_style]    # not inherited
  Fiber[:request_id] = "changed in child"
  Fiber[:extra] = 1
end.resume

p Fiber[:request_id]              # parent's value is unchanged
p Fiber[:extra]

Thread.new { p Fiber[:request_id] }.join

Fiber.new(storage: { request_id: "explicit" }) { p Fiber.current.storage }.resume
Fiber.new(storage: nil) { p Fiber[:request_id] }.resume
p Fiber.current.storage
"req-42"
nil
"req-42"
nil
"req-42"
{request_id: "explicit"}
nil
{request_id: "req-42"}

The child gets a copy, so changes it makes don't leak back into the parent. Pass storage: to Fiber.new to start with a specific hash, or storage: nil to start empty.

Because Fiber.schedule creates fibers with Fiber.new, the storage flows into every fiber a request starts. That makes it a good place for a request id that a logger can pick up:

require_relative "scheduler"

def log(msg) = puts("[#{Fiber[:request_id] || "-"}] #{msg}")

def handle(id, delay)
  Fiber[:request_id] = id
  log "start"
  Fiber.schedule do               # child fiber inherits a copy of the storage
    sleep 0.05
    log "background job"
  end
  sleep delay
  log "done"
end

Fiber.set_scheduler(SimpleScheduler.new)
Fiber.schedule { handle("req-1", 0.1) }
Fiber.schedule { handle("req-2", 0.02) }
log "main"
[req-1] start
[req-2] start
[-] main
[req-2] done
[req-1] background job
[req-2] background job
[req-1] done

The two requests are interleaved on one thread, yet each line is logged with the right id, including the lines from the background fibers. Async tasks are fibers too, so Fiber[] works the same way there.

io_read and io_write with IO::Buffer

io_wait is enough to make IO work: Ruby tries a non-blocking read or write, and if the IO isn't ready, it calls io_wait and tries again. A scheduler can take over the reads and writes themselves by implementing io_read(io, buffer, length, offset) and io_write(io, buffer, length, offset). Ruby passes an IO::Buffer (experimental) for the data, length is the minimum number of bytes the caller needs (0 means "whatever is available"), and the hook returns the number of bytes transferred, or a negated errno on failure. This is what lets a scheduler hand IO to io_uring on Linux.

Here is an io_read that does the read itself and waits with io_wait when there's no data yet:

require "socket"
require "io/nonblock"
require_relative "scheduler"

class BufferScheduler < SimpleScheduler
  # Called for IO#read, #readpartial, #gets, ... instead of io_wait.
  # Must return the number of bytes read, or -errno on failure.
  def io_read(io, buffer, length, offset)
    total = 0
    loop do
      # IO::Buffer#read does one read(2) into the buffer at offset
      result = Fiber.blocking { buffer.read(io, 0, offset) }
      if result == -Errno::EAGAIN::Errno || result == -Errno::EWOULDBLOCK::Errno
        puts "  io_read: would block, waiting"
        io_wait(io, IO::READABLE, nil)
      elsif result <= 0
        return total.zero? ? result : total # 0 = EOF, negative = error
      else
        puts "  io_read: got #{result} bytes"
        total += result
        offset += result
        return total if total >= length
      end
    end
  end
end

Fiber.set_scheduler(BufferScheduler.new)

a, b = UNIXSocket.pair
a.nonblock = true

Fiber.schedule do
  data = a.readpartial(100)
  p data
end

Fiber.schedule do
  sleep 0.05
  b.write "hello"
end
  io_read: would block, waiting
  io_read: got 5 bytes
"hello"

buffer.read is wrapped in Fiber.blocking, so that it doesn't call back into the scheduler. EAGAIN and EWOULDBLOCK are the same number on Linux, but not on Windows, so the code checks both.

Other optional hooks follow the same idea. process_wait lets Process.wait wait without blocking the thread. address_resolve lets DNS lookups run without blocking. blocking_operation_wait (Ruby 3.4) receives long-running C calls that release the GVL and are marked as safe to move to another thread, and can run them on a worker thread pool.

How Async builds on this

Async's scheduler, Async::Scheduler, implements the same interface: all the required hooks plus io_read, io_write, io_select, process_wait, address_resolve, timeout_after, blocking_operation_wait and fiber_interrupt. Instead of IO.select, it uses the io-event gem, which picks the best mechanism for the platform (io_uring or epoll on Linux, kqueue on macOS and BSD, select as a fallback). On top of the hooks, Async adds tasks with parent/child relationships, cancellation (Task#stop), Async::Barrier, Async::Semaphore and timeouts.

Since it's the same interface, plain Ruby code runs unchanged under Async. Here sleep, Thread::Queue, Fiber.schedule and Fiber[] work without any Async-specific API:

require "async"

Fiber[:request_id] = "req-7"

Async do |task|
  p Fiber.scheduler.class.ancestors.take(2)

  queue = Thread::Queue.new

  task.async do
    sleep 0.1                     # Kernel#sleep -> kernel_sleep hook
    queue << "hello from an Async task (#{Fiber[:request_id]})"
  end

  Fiber.schedule do               # Fiber.schedule -> Async::Scheduler#fiber
    puts queue.pop                # Queue#pop -> block/unblock hooks
  end
end

p Fiber.scheduler
[Async::Reactor, Async::Scheduler]
hello from an Async task (req-7)
nil

The output was produced with async 2.46 (run with ruby -W:no-experimental to hide the IO::Buffer warning). Async do installed an Async::Reactor (a subclass of Async::Scheduler) as the scheduler, ran everything, and removed it again at the end, just like with_scheduler above.

This is the main benefit of the scheduler interface: libraries don't need to be written for a particular event loop. A database driver or HTTP client that uses normal Ruby IO becomes non-blocking under any scheduler, Async or your own. The exception is C extensions that do their own blocking IO without going through Ruby's IO layer. They still block the thread, unless the scheduler offloads them with blocking_operation_wait.

Fibers make IO-bound work concurrent, but everything still runs on one thread. For CPU-bound work in parallel, see Ractors.

Best practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents