Cancellation and timeouts
suggest changeAny operation that waits on something outside your program (a network call, a database query, a child process, another thread) can take much longer than expected or never finish at all. A robust program puts a limit on every wait and has a way to tell work in progress to stop.
Ruby has no single "cancellation token" type like Go's context or .NET's CancellationToken. Instead you combine a few tools:
Timeout.timeout, the general-purpose but blunt instrument- timeouts built into blocking operations:
Queue#pop(timeout:),Thread#join(limit),IO#timeout=,Net::HTTPtimeouts,Regexp.timeout - deadlines computed with the monotonic clock and passed down the call chain
- cooperative cancellation with a flag or a token that workers check
Thread#raisewithThread.handle_interruptfor forced cancellationtask.with_timeoutandtask.stopin theasyncgem
The examples were run with Ruby 4.0 and async 2.46. Everything except the async section uses only the standard library.
Timeout.timeout
Timeout.timeout(seconds) { ... } runs the block and raises Timeout::Error if it hasn't finished in time. It returns the block's value when it does finish. Passing nil or 0 means no limit:
require "timeout"
def slow_lookup
sleep 2
:found
end
begin
result = Timeout.timeout(0.5) { slow_lookup }
p result
rescue Timeout::Error => e
puts "gave up: #{e.message} (#{e.class})"
end
p Timeout.timeout(1) { :fast }
p Timeout.timeout(nil) { :no_limit }
gave up: execution expired (Timeout::Error)
:fast
:no_limit
You can pass your own exception class and message as the second and third arguments:
require "timeout"
class LookupTimeout < StandardError; end
begin
Timeout.timeout(0.2, LookupTimeout, "user lookup took too long") { sleep 1 }
rescue LookupTimeout => e
puts "#{e.class}: #{e.message}"
end
LookupTimeout: user lookup took too long
How it works and why that matters
Timeout.timeout doesn't make the block cooperate. A background timer thread waits and, when time is up, calls Thread#raise on your thread. The exception appears at whatever line your code happens to be executing. That has consequences.
Without a custom class, the exception raised inside the block is Timeout::ExitException, which inherits from Exception. A plain rescue => e inside the block doesn't catch it, and it's turned into Timeout::Error once it leaves the block:
begin
Timeout.timeout(0.2) do
begin
sleep 1
rescue => e
puts "inner rescue saw: #{e.class}"
end
puts "still running?"
end
rescue Timeout::Error
puts "outer caught Timeout::Error"
end
outer caught Timeout::Error
With a custom class that inherits from StandardError, the exception is raised directly. Any rescue => e in the code being timed out can swallow it, and the timeout silently has no effect:
require "timeout"
class LookupTimeout < StandardError; end
begin
Timeout.timeout(0.2, LookupTimeout) do
begin
sleep 1
rescue => e
puts "inner rescue swallowed: #{e.class}"
end
puts "block kept running"
end
puts "no error reached the caller"
rescue LookupTimeout
puts "caller saw LookupTimeout"
end
inner rescue swallowed: LookupTimeout
block kept running
no error reached the caller
Rescue the custom class outside the block, and let unrelated code inside the block rescue only the specific exceptions it expects.
The bigger problem is that the interruption can land in the middle of a multi-step update and leave data inconsistent:
require "timeout"
$balance = { alice: 100, bob: 0 }
def transfer(amount)
$balance[:alice] -= amount
sleep 0.3 # pretend this is a slow network call
$balance[:bob] += amount
end
begin
Timeout.timeout(0.1) { transfer(40) }
rescue Timeout::Error
puts "timed out"
end
p $balance
timed out
{alice: 60, bob: 0}
Forty units disappeared. The same thing can happen inside a library: a connection pool can lose track of a checked-out connection, or a protocol client can be left halfway through a message. This is why many libraries say not to wrap their calls in Timeout.timeout and offer their own timeout options instead.
You can mark a section as uninterruptible with Thread.handle_interrupt. Asynchronous exceptions of the listed classes are deferred until the block exits:
def transfer(amount)
Thread.handle_interrupt(Timeout::ExitException => :never) do
$balance[:alice] -= amount
sleep 0.3
$balance[:bob] += amount
end
end
begin
Timeout.timeout(0.1) { transfer(40) }
rescue Timeout::Error
puts "timed out (after the transfer finished)"
end
p $balance
timed out (after the transfer finished)
{alice: 60, bob: 40}
The operation now takes as long as it takes, and the timeout is reported afterwards. Use Timeout.timeout for code you control, keep the timed section small, and prefer the built-in timeouts described next.
Built-in timeouts on blocking operations
Most blocking calls in the standard library accept a limit. They return or raise at a well-defined point, so nothing gets interrupted halfway.
Threads, queues and condition variables
q = Thread::Queue.new
p q.pop(timeout: 0.1) # => nil, nothing arrived
Thread.new { sleep 0.05; q << :job }
p q.pop(timeout: 1) # => :job
sq = Thread::SizedQueue.new(1)
sq << 1
p sq.push(2, timeout: 0.1) # => nil, queue stayed full
t = Thread.new { sleep 1; :done }
p t.join(0.1) # => nil, thread still running
p t.alive?
p t.join(2)&.value # => :done
nil
:job
nil
nil
true
:done
Queue#pop(timeout:) and SizedQueue#push(timeout:) were added in Ruby 3.2. Since nil is also a value you could push onto a queue, don't use nil as a work item if you rely on nil meaning "timed out".
Thread::ConditionVariable#wait(mutex, timeout) and Thread::Mutex#sleep(timeout) also take a limit. A condition variable can wake up spuriously, so loop until the condition holds or the time is up. The cancellation token below shows the pattern.
Sockets and IO
Since Ruby 3.2 every IO object has a timeout attribute. When it's set, blocking reads and writes raise IO::TimeoutError instead of waiting forever. TCPSocket.new and Socket.tcp take a connect_timeout::
require "socket"
server = TCPServer.new("127.0.0.1", 0) # a server that never answers
port = server.addr[1]
sock = TCPSocket.new("127.0.0.1", port, connect_timeout: 1)
sock.timeout = 0.2
begin
sock.gets
rescue IO::TimeoutError => e
puts "#{e.class}: #{e.message}"
end
# the low-level way: wait for readability with a limit
p sock.wait_readable(0.1) # => nil on timeout
p IO.select([sock], nil, nil, 0.1) # => nil on timeout
sock.close
server.close
IO::TimeoutError: Blocking operation timed out!
nil
nil
IO#timeout applies to each individual operation, not to the whole exchange: a server that sends one byte every 0.1 seconds never trips a 0.2 second timeout. To bound the total time, combine it with a deadline (see below). More socket examples are in TCP sockets.
Net::HTTP
Net::HTTP has separate timeouts for connecting, reading and writing. The defaults are 60 seconds each, which is too long for most services:
require "net/http"
require "socket"
server = TCPServer.new("127.0.0.1", 0)
port = server.addr[1]
Thread.new { loop { server.accept } } # accept but never reply
http = Net::HTTP.new("127.0.0.1", port)
http.open_timeout = 1 # TCP connect (and TLS handshake)
http.read_timeout = 0.3 # each read waiting for data
http.write_timeout = 1 # each write
begin
http.get("/")
rescue Net::ReadTimeout => e
puts "#{e.class}: #{e.message}"
end
p Net::ReadTimeout.ancestors.include?(Timeout::Error)
p Net::OpenTimeout.ancestors.include?(Timeout::Error)
Net::ReadTimeout: Net::ReadTimeout with #<TCPSocket:(closed)>
true
true
Both Net::OpenTimeout and Net::ReadTimeout are subclasses of Timeout::Error, so rescue Timeout::Error catches either. With Net::HTTP.start(host, port, open_timeout: 1, read_timeout: 2) you can set them in one call. Note that Net::HTTP retries idempotent requests (like GET) once after a read timeout by default, so the worst case is about twice read_timeout. Set http.max_retries = 0 to turn that off. Popular HTTP gems (Faraday, HTTPX, http.rb) have equivalent options. See HTTP client.
Database drivers work the same way: the pg gem uses connect_timeout and the server-side statement_timeout, mysql2 has connect_timeout/read_timeout/write_timeout, and ActiveRecord passes these through from database.yml.
Regular expressions
A badly written regular expression can take exponential time on some inputs. Ruby 3.2 added a global Regexp.timeout and a per-pattern timeout: option:
Regexp.timeout = 0.5
evil = "a" * 50 + "!"
pattern = /\A(a|aa)+\1\z/ # the backreference disables Ruby's memoization
started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
begin
pattern.match?(evil)
rescue Regexp::TimeoutError => e
elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
puts "#{e.class}: #{e.message} after #{elapsed.round(1)}s"
end
strict = Regexp.new('\A(a|aa)+\1\z', timeout: 0.1)
p strict.timeout
p Regexp.linear_time?(/\A(a|a)*\z/)
p Regexp.linear_time?(pattern)
Regexp::TimeoutError: regexp match timeout after 0.5s
0.1
true
false
Since Ruby 3.2 most patterns are matched in linear time thanks to memoization; Regexp.linear_time? tells you whether a pattern qualifies. Patterns with backreferences or lookarounds don't, and those are the ones to worry about when matching user input. Setting Regexp.timeout once at startup in a web application is cheap insurance.
Deadlines instead of timeouts
A timeout of 2 seconds on each of five steps can add up to 10 seconds. Usually what you want is a single budget for the whole operation: a deadline. Compute it once and pass the remaining time to each blocking call.
Always measure with Process.clock_gettime(Process::CLOCK_MONOTONIC), not Time.now. The wall clock can jump backwards or forwards when NTP adjusts it; the monotonic clock only moves forward.
class Deadline
class Exceeded < StandardError; end
def self.in(seconds) = new(now + seconds)
def self.now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
def initialize(at) = @at = at
def remaining = [@at - Deadline.now, 0.0].max
def expired? = remaining.zero?
def check!(what = "operation")
raise Exceeded, "#{what}: deadline exceeded" if expired?
end
end
def fetch_part(name, deadline, queue)
deadline.check!(name)
item = queue.pop(timeout: deadline.remaining)
raise Deadline::Exceeded, "#{name}: deadline exceeded" if item.nil?
item
end
q = Thread::Queue.new
Thread.new do
[:header, :body].each { |x| sleep 0.15; q << x }
end
deadline = Deadline.in(0.25) # one budget for the whole request
begin
%w[header body footer].each do |name|
part = fetch_part(name, deadline, q)
printf("%-6s %-7p %.2fs left\n", name, part, deadline.remaining)
end
rescue Deadline::Exceeded => e
puts e.message
end
header :header 0.10s left
body: deadline exceeded
The same object works with any API that takes a timeout: sock.timeout = deadline.remaining before each read, http.read_timeout = deadline.remaining, thread.join(deadline.remaining). In a web app, create the deadline when the request arrives and pass it to service objects, or store it in a fiber-local variable (Fiber[:deadline] = ..., Ruby 3.2+), which child threads and fibers inherit.
Cooperative cancellation
Timeouts limit how long you wait. Cancellation tells other code to stop: a user pressed Cancel, the process got SIGTERM, or one of several parallel requests already produced an answer.
The safest form is cooperative: the worker checks a flag at points where stopping is safe. A plain boolean (as in Terminating a Thread) works, but a worker sleeping between polls won't notice it until it wakes up. A small token built on a condition variable can wake sleepers immediately:
class CancellationToken
class Cancelled < StandardError; end
def initialize
@mutex = Thread::Mutex.new
@cond = Thread::ConditionVariable.new
@reason = nil
end
def cancel(reason = "cancelled")
@mutex.synchronize do
@reason ||= reason
@cond.broadcast # wake everyone sleeping in #wait
end
end
def cancelled? = @mutex.synchronize { !@reason.nil? }
def reason = @mutex.synchronize { @reason }
def check!
r = reason
raise Cancelled, r if r
end
# Sleep up to `seconds`, returning early (true) if cancelled.
def wait(seconds)
deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + seconds
@mutex.synchronize do
until @reason
left = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
break if left <= 0
@cond.wait(@mutex, left)
end
!@reason.nil?
end
end
end
token = CancellationToken.new
workers = 3.times.map do |i|
Thread.new do
done = 0
until token.cancelled?
done += 1 # one unit of work
token.wait(0.1) # poll interval, wakes up early on cancel
end
"worker #{i}: #{done} units, stopped (#{token.reason})"
end
end
sleep 0.35
started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
token.cancel("shutdown requested")
workers.each { |t| puts t.value }
printf("all stopped in %.3fs\n", Process.clock_gettime(Process::CLOCK_MONOTONIC) - started)
begin
token.check!
rescue CancellationToken::Cancelled => e
puts "check! raised: #{e.message}"
end
worker 0: 4 units, stopped (shutdown requested)
worker 1: 4 units, stopped (shutdown requested)
worker 2: 4 units, stopped (shutdown requested)
all stopped in 0.000s
check! raised: shutdown requested
Pass the token down to every function that might run long and call token.check! between steps. Code deep in the call stack raises Cancelled, ensure blocks run on the way up, and the top level rescues it. Because the check happens at points you chose, there's no risk of interrupting an update halfway. A deadline and a token combine naturally: a token can carry an optional deadline and report cancelled? once it passes.
For stopping workers on SIGINT/SIGTERM (a trap handler sets the token, or pushes onto a queue), see Signals and graceful shutdown.
Forced cancellation with Thread#raise
When the code you want to stop doesn't check a token, for example a third-party library call, Thread#raise injects an exception into another thread. Thread#kill is the same idea but can't be rescued (only ensure runs). Both have the problems described for Timeout.timeout, which is built on Thread#raise; see also How to kill a thread.
Thread.handle_interrupt lets the target thread decide where the exception may arrive. A common pattern is to block it by default, allow it only in a section that's safe to abandon, and protect the cleanup:
class Cancelled < StandardError; end
worker = Thread.new do
Thread.handle_interrupt(Cancelled => :never) do
file = "opened"
begin
Thread.handle_interrupt(Cancelled => :immediate) do
loop { sleep 0.05 } # interruptible section
end
rescue Cancelled => e
puts "worker: #{e.message}"
:cancelled
ensure
sleep 0.1 # cleanup can't be interrupted again
puts "worker: cleanup done (#{file} closed)"
end
end
end
sleep 0.1
worker.raise(Cancelled, "stop now")
p worker.value
worker: stop now
worker: cleanup done (opened closed)
:cancelled
The third mode, :on_blocking, delivers the exception only while the thread is blocked in IO, sleep or similar, never in the middle of Ruby code. Inside a :never section you can call Thread.pending_interrupt? to check whether a cancellation is waiting, which turns forced cancellation into a cooperative one.
Neither Thread#raise nor Timeout.timeout can interrupt a C extension that is blocked without releasing the GVL or a call that ignores interrupts. If you must be able to stop arbitrary code, run it in a separate process.
Timeouts for child processes
A child process can be killed cleanly at any time, which makes it the most reliable way to bound untrusted or misbehaving work. Wait on the process with a limit and kill it if the limit passes:
require "open3"
require "timeout"
def run_with_timeout(*cmd, timeout:)
Open3.popen2e(*cmd) do |stdin, out, wait_thr|
stdin.close
reader = Thread.new { out.read } # drain output so the child can't block
if wait_thr.join(timeout)
[wait_thr.value.exitstatus, reader.value]
else
Process.kill(:KILL, wait_thr.pid) # on Unix send :TERM first, then :KILL
wait_thr.join
reader.join
raise Timeout::Error, "#{cmd.first} did not finish in #{timeout}s"
end
end
end
p run_with_timeout("ruby", "-e", "puts :hi", timeout: 5)
begin
run_with_timeout("ruby", "-e", "sleep 10", timeout: 0.5)
rescue Timeout::Error => e
puts e.message
end
# Process.spawn + Process.detach is the same idea without pipes
pid = Process.spawn("ruby", "-e", "sleep 10")
waiter = Process.detach(pid)
unless waiter.join(0.3)
Process.kill(:KILL, pid)
waiter.join
puts "killed the child"
end
[0, "hi\n"]
ruby did not finish in 0.5s
killed the child
The reader thread matters: if the child writes more than the pipe buffer holds and nobody reads it, the child blocks forever and every run "times out". On Unix, give the child a chance to clean up with Process.kill(:TERM, pid), wait a few seconds, then send :KILL. If the child starts its own children, spawn it with pgroup: true and kill the whole group with Process.kill(:TERM, -pid). More on running commands is in Operating system or shell commands.
Timeouts and cancellation with async
The async gem runs tasks on fibers with a fiber scheduler (see Fibers and Async). Cancellation is much safer there, because a fiber can only be interrupted at a point where it's waiting (IO, sleep, a queue), never between two Ruby statements:
require "async"
Async do |task|
# with_timeout raises Async::TimeoutError inside the block
begin
task.with_timeout(0.2) { sleep 1 }
rescue Async::TimeoutError => e
puts "timed out: #{e.class}"
end
# stop cancels a child task: it raises Async::Stop at its current wait point
child = task.async do
loop { sleep 0.05 }
ensure
puts "child: ensure runs"
end
sleep 0.1
child.stop
p child.status
p child.stopped?
# race two tasks, cancel the loser
fast = task.async { sleep 0.1; :fast }
slow = task.async { sleep 5; :slow }
winner = fast.wait
slow.stop
p [winner, slow.status]
end
timed out: Async::TimeoutError
child: ensure runs
:cancelled
true
[:fast, :cancelled]
Stopping a task also stops all of its children, so cancelling the task that handles a request cancels every sub-request it started. Async::Barrier#stop stops a whole group at once. When a fiber scheduler is active, Timeout.timeout is implemented by the scheduler too, so it's interrupted only at wait points and becomes as safe as with_timeout.
Best practices
- Put a limit on every network call, query and child process. Library defaults are often "forever" or 60 seconds.
- Prefer timeouts built into the operation (
open_timeout,read_timeout,IO#timeout,pop(timeout:),join(limit)) over wrapping code inTimeout.timeout. - If you do use
Timeout.timeout, keep the block small, use it only around code you understand, and protect critical sections withThread.handle_interrupt. - Use one deadline per operation and pass the remaining time down, instead of separate timeouts for each step.
- Measure time with
Process::CLOCK_MONOTONIC. - Cancel cooperatively: pass a token, check it between steps, and let
ensuredo the cleanup. - Never
rescue Exceptionaround code that might be cancelled; it swallowsTimeout::ExitException,InterruptandAsync::Stop. - After a timeout, assume the connection or object in use is in an unknown state: close it and open a new one rather than reusing it.
- Run code that can't be interrupted safely in a separate process and kill the process when time is up.