Signals and graceful shutdown
suggest changeLong-running Ruby programs (servers, job workers, daemons, CLI tools that process many files) are stopped by the operating system sending them a signal. A program that handles signals well stops accepting new work, finishes or hands back the work in progress, flushes its buffers, closes connections, and exits with a sensible status. This is called a graceful shutdown.
The most important signals:
| Signal | Typically sent by | Default behavior in Ruby |
|---|---|---|
INT |
Ctrl+C in a terminal | raises Interrupt in the main thread |
TERM |
kill pid, docker stop, Kubernetes, systemd |
raises SignalException ("SIGTERM") in the main thread |
KILL |
kill -9 pid, orchestrators after a timeout |
process dies immediately; cannot be trapped |
HUP |
terminal closed; by convention "reload config / reopen logs" | raises SignalException |
QUIT |
Ctrl+\ | raises SignalException |
USR1, USR2 |
your own tooling | raises SignalException; free for app-defined meaning |
Signal.list returns the signals supported on the current platform as a hash of name to number.
Default behavior: signals are exceptions
Without any handler, INT and TERM become exceptions raised in the main thread. That means ensure blocks and at_exit hooks still run:
at_exit { puts "at_exit: #{$!.inspect}" }
begin
puts "working, pid #{Process.pid}"
sleep
ensure
puts "ensure runs"
end
Running kill -TERM <pid> prints:
ensure runs
at_exit: #<SignalException: SIGTERM>
After the exception propagates, Ruby re-sends the signal to itself with the default OS handler, so the parent sees the process as "killed by SIGTERM" (exit status 143 in a shell), which is the correct convention.
Interrupt is a subclass of SignalException, and both inherit from Exception, not StandardError. A bare rescue => e does not catch them, which is what you want. For a CLI tool, catching Interrupt gives a clean Ctrl+C:
begin
loop { print "."; sleep 0.1 }
rescue Interrupt
warn "\nInterrupted, bye"
exit 130 # 128 + SIGINT(2), the shell convention
end
Never write rescue Exception in a loop: it swallows Interrupt and SignalException and makes the program impossible to stop without kill -9.
Installing handlers with Signal.trap
Signal.trap (also available as Kernel#trap) replaces the default behavior with a block. The block receives the signal number and the method returns the previous handler:
previous = Signal.trap("TERM") do |signo|
puts "got #{Signal.signame(signo)}" # => "got TERM"
end
p previous # => "DEFAULT"
Signal names can be given as "TERM", "SIGTERM", :TERM or a number. Instead of a block you can pass a string command:
| Command | Meaning |
|---|---|
"DEFAULT" |
Ruby's default handler (raise Interrupt / SignalException) |
"SYSTEM_DEFAULT" |
the operating system's default action |
"IGNORE" / "" / nil |
ignore the signal |
"EXIT" |
exit the process as if by exit |
Some signals can't be trapped: KILL and STOP are handled by the kernel (Signal.trap("KILL") raises Errno::EINVAL), and Ruby reserves SEGV, BUS, ILL, FPE and VTALRM (ArgumentError: can't trap reserved signal).
What you may not do inside a trap handler
A trap handler runs in the main thread, interrupting it at an arbitrary point, possibly while it holds a lock. To prevent deadlocks Ruby forbids blocking synchronization inside a handler:
require 'logger'
mutex = Mutex.new
logger = Logger.new($stdout)
Signal.trap("INT") do
mutex.synchronize { } # ThreadError: can't be called from trap context
end
Things that fail or misbehave in trap context:
Mutex#lock/#synchronizeandMonitorraiseThreadError: can't be called from trap contextLoggeruses aMonitorinternally; it printslog writing failed. can't be called from trap contextand drops the messagerequireraises the sameThreadError- anything that goes through a library using a mutex: database clients, connection pools,
Net::HTTPwith pooling, etc. - long work in general: while the handler runs, the main thread's work is paused
What is safe: assigning a variable, pushing onto a Thread::Queue, writing to a pipe, and (with care) puts, exit or raise. The rule of thumb is: a trap handler only records that the signal arrived; the real work happens elsewhere.
Pattern 1: a stop flag
For a simple loop on the main thread, set a flag and check it between units of work:
stop = false
%w[INT TERM].each { |sig| Signal.trap(sig) { stop = true } }
until stop
process_next_batch # finish the current batch completely
end
puts "shutting down cleanly"
The current batch is never interrupted half-way. The downside: if the loop blocks for a long time (e.g. waiting on a socket), the flag isn't seen until it unblocks.
Pattern 2: a signal Queue
Thread::Queue#push is allowed in trap context, so a queue turns asynchronous signals into ordinary messages that a normal thread can handle, with full access to locks, logging, and databases:
require 'logger'
logger = Logger.new($stdout)
signals = Queue.new
%w[INT TERM HUP].each do |sig|
Signal.trap(sig) { signals << sig } # only enqueue, nothing else
end
loop do
case signals.pop # blocks until a signal arrives
when "HUP"
logger.info "reopening log files" # fine: we're not in trap context
logger.reopen
when "INT", "TERM"
logger.info "shutting down"
break
end
end
Note HUP is not available on Windows; see the end of the article.
Pattern 3: the self-pipe trick
If the program is built around IO.select (an event loop waiting on sockets), a queue doesn't fit. Instead, the handler writes a byte to a pipe that select is also watching. This is the classic "self-pipe" trick used by servers such as Puma and Unicorn:
require 'socket'
server = TCPServer.new(4000)
reader, writer = IO.pipe
%w[INT TERM].each do |sig|
Signal.trap(sig) { writer.write_nonblock(".", exception: false) }
end
loop do
ready, = IO.select([server, reader])
break if ready.include?(reader) # a signal arrived
client = server.accept
client.puts "hello"
client.close
end
server.close # stop accepting; in-flight work would be finished here
puts "server stopped"
write_nonblock(..., exception: false) guarantees the handler never blocks, even if the pipe buffer is full.
Draining a worker pool
A typical worker process has a producer feeding a job queue and several worker threads. A graceful shutdown means: stop taking new jobs, let workers finish what is already queued, then exit. Queue#close does most of the work: after closing, push raises ClosedQueueError, and pop returns nil once the queue is empty.
jobs = Queue.new
signals = Queue.new
%w[INT TERM].each { |sig| Signal.trap(sig) { signals << sig } }
workers = 3.times.map do |i|
Thread.new do
while (job = jobs.pop) # nil once the queue is closed and empty
sleep 0.2 # pretend to work
puts "worker #{i} finished job #{job}"
end
puts "worker #{i} exiting"
end
end
producer = Thread.new do
n = 0
# ClosedQueueError is a subclass of StopIteration, so `loop` ends quietly
loop { jobs << (n += 1); sleep 0.05 }
end
sig = signals.pop # main thread sleeps until INT or TERM
puts "got SIG#{sig}, draining #{jobs.size} queued jobs"
jobs.close
producer.join
workers.each(&:join)
puts "clean shutdown"
Orchestrators don't wait forever. docker stop sends TERM and then KILL after 10 seconds; Kubernetes waits terminationGracePeriodSeconds (30 by default). Bound your drain with a deadline that is shorter than that:
deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 20
workers.each do |t|
remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
next if t.join([remaining, 0].max) # finished in time
warn "worker #{t.inspect} did not finish, killing it"
t.kill # runs the thread's ensure blocks
end
Jobs killed this way should be idempotent or re-enqueued; that's exactly what Sidekiq does (see below).
Threads and signals
- Signals are always delivered to the main thread. Trap handlers run there, and
Interrupt/SignalExceptionare raised there, never in other threads. - When the main thread exits, other threads are killed (their
ensureblocks run). If you want workers to finish, the main thread mustjointhem. - Prefer stop flags or closed queues over
Thread#raise/Thread#killfor normal shutdown: they let the thread stop at a point you chose, not in the middle of a write.
at_exit and ensure
at_exit registers a block to run when the interpreter exits, whether by reaching the end of the script, exit, an uncaught exception or a default-handled INT/TERM. Hooks run in reverse order of registration and $! holds the exception (if any) that caused the exit:
at_exit { puts "closing database" }
at_exit { puts "flushing metrics" } # runs before "closing database"
at_exit do
if $!.is_a?(SignalException)
puts "exiting because of #{$!.signm}"
end
end
Neither at_exit nor ensure run on KILL, on exit!, or if the process crashes. Don't rely on them for anything that must survive a hard kill; that's what transactions and idempotent jobs are for.
Sending signals with Process.kill
Process.kill(signal, *pids) sends a signal to one or more processes:
Process.kill("TERM", pid) # ask politely
Process.kill("KILL", pid) # force (cannot be handled)
Process.kill(0, pid) # send nothing, just check that the process exists
# raises Errno::ESRCH if not, Errno::EPERM if not ours
Process.kill("TERM", -pgid) # negative pid: signal the whole process group
A common supervisor helper sends TERM, waits with a timeout, and escalates to KILL (Unix):
def stop_process(pid, timeout: 10)
Process.kill("TERM", pid)
waiter = Process.detach(pid) # thread that reaps the child
return waiter.value if waiter.join(timeout)
Process.kill("KILL", pid)
waiter.value # Process::Status
rescue Errno::ESRCH
nil # already gone
end
pid = spawn("ruby", "-e", 'Signal.trap("TERM") { puts "child: cleaning up"; exit }; sleep')
sleep 1
status = stop_process(pid, timeout: 5)
p status.success? # => true, the child handled TERM and exited 0
Trap handlers are not inherited by programs started with exec/spawn, but signals set to "IGNORE" are.
Puma, Sidekiq and containers
You usually don't trap signals yourself in a Rails app; the server does it. Know what each signal means to it:
- Puma:
TERMandINTstop gracefully (stop accepting, finish in-flight requests). In cluster mode,USR2restarts all workers andUSR1does a phased (rolling) restart.worker_shutdown_timeoutbounds how long a worker may take. - Sidekiq:
TSTPputs the process in "quiet" mode (stop fetching new jobs, keep running ones).TERMshuts down: Sidekiq waits up to its timeout (-t, 25 seconds by default) and pushes unfinished jobs back to Redis so they are retried. Set the timeout lower than your platform's kill grace period.TTINdumps all thread backtraces to the log, handy for debugging a stuck process. - Docker: use the exec form
CMD ["bundle", "exec", "puma"]. The shell formCMD bundle exec pumaruns under/bin/sh -c, which may not forwardTERMto Ruby, so the app getsKILLed after the timeout. If Ruby runs as PID 1, consider--init(tini) so signals and zombie children are handled properly.
Windows limitations
Windows has no real POSIX signals. Ruby on Windows supports only INT, ILL, ABRT, FPE, KILL, SEGV, TERM and EXIT (check Signal.list), so HUP, QUIT, USR1, USR2, TSTP and CHLD handlers can't be installed. Ctrl+C in a console delivers INT, and Process.kill("KILL", pid) terminates a process, but sending TERM to another process raises Errno::EINVAL. A process can still signal itself (Process.kill("TERM", Process.pid)), which is useful for tests. For portable code, trap only INT and TERM, and for controlling other processes use a different channel such as a socket, a pipe, or a "stop" file.