Signals and graceful shutdown

suggest change

Long-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:

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

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:

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.

Feedback about page:

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



Table Of Contents