Signals and graceful shutdown
suggest changeA long-running Dart program (an HTTP server, a queue worker, a CLI tool that writes files) should not just die when it's asked to stop. It should finish or abandon in-flight work in a controlled way, flush logs, close database connections and exit with a meaningful exit code. That's graceful shutdown.
The operating system asks a process to stop by sending it a signal:
SIGINT(2): the user pressed Ctrl+C in the terminalSIGTERM(15): the polite "please stop" sent bykill <pid>,docker stop, Kubernetes, systemd and most process managersSIGHUP(1): the terminal was closed. Daemons often use it to mean "reload your configuration"SIGKILL(9): immediate termination. It can't be caught, so no cleanup happens
In Dart, signals are handled with ProcessSignal from dart:io. This article covers:
- watching signals with
ProcessSignal.watch() - which signals are supported on which platform
- a reusable "wait for shutdown signal" helper
- graceful shutdown of an
HttpServer, including waiting for in-flight requests - a shutdown hook registry with timeouts
- reloading configuration on
SIGHUPand other custom signals - sending signals to child processes, and testing shutdown code
- stopping worker isolates
- running in Docker and Kubernetes
The examples were run on Linux (Dart 3.13 in WSL) unless noted otherwise. Windows output is shown where it differs.
Watching a signal
ProcessSignal.watch() returns a Stream<ProcessSignal> that emits an event every time the process receives the signal:
import 'dart:async';
import 'dart:io';
void main() {
print('Working (pid $pid). Press Ctrl+C to stop.');
var ticks = 0;
final timer = Timer.periodic(const Duration(milliseconds: 300), (_) {
ticks++;
});
ProcessSignal.sigint.watch().listen((signal) {
timer.cancel();
print('Got $signal (number ${signal.signalNumber}) after $ticks ticks');
exit(130); // 128 + 2, the conventional code for "killed by SIGINT"
});
}
Pressing Ctrl+C after about 1.5 seconds:
Working (pid 678). Press Ctrl+C to stop.
^CGot SIGINT (number 2) after 4 ticks
$ echo $?
130
Things to know about watch():
- Listening replaces the default behavior. Without a listener,
SIGINTandSIGTERMkill the process. Once you listen, the process keeps running and it's up to your code to exit. - Cancelling all subscriptions restores the default behavior. The next signal kills the process again. We'll use this below to make a second Ctrl+C force an exit.
- An active subscription keeps the process alive, just like an open socket or a running timer. If your program is otherwise done, cancel the subscription or the VM never exits.
- A signal can be watched several times, also from several isolates. All listeners are called, in no specific order.
signal.signalNumbergives the numeric value andtoString()the name (SIGINT).
Shells and process managers report "killed by signal N" as exit code 128 + N: 130 for SIGINT, 143 for SIGTERM. Using the same codes after a graceful shutdown tells a supervisor why the program stopped.
Platform support
Only some signals can be watched. The rest are either used internally by the VM (SIGQUIT, SIGPROF) or can't be caught at all (SIGKILL, SIGSTOP). This program tries to watch several signals:
import 'dart:async';
import 'dart:io';
void main() {
final signals = [
ProcessSignal.sigint,
ProcessSignal.sighup,
ProcessSignal.sigterm,
ProcessSignal.sigusr1,
ProcessSignal.sigwinch,
ProcessSignal.sigquit,
ProcessSignal.sigkill,
];
for (final signal in signals) {
try {
final sub = signal.watch().listen(
(_) {},
onError: (Object e) => print('$signal: async error: $e'),
);
Timer(const Duration(milliseconds: 200), sub.cancel);
print('$signal: watching');
} on SignalException catch (e) {
print('$signal: ${e.message}');
}
}
}
On Linux (macOS behaves the same):
SIGINT: watching
SIGHUP: watching
SIGTERM: watching
SIGUSR1: watching
SIGWINCH: watching
SIGQUIT: Listening for signal SIGQUIT is not supported
SIGKILL: Listening for signal SIGKILL is not supported
On Windows:
SIGINT: watching
SIGHUP: watching
SIGTERM: watching
SIGUSR1: Listening for signal SIGUSR1 is not supported
SIGWINCH: Listening for signal SIGWINCH is not supported
SIGQUIT: Listening for signal SIGQUIT is not supported
SIGKILL: Listening for signal SIGKILL is not supported
SIGTERM: async error: SignalException: Failed to listen for SIGTERM, osError: OS Error: The request is not supported, errno = 50
Summary:
| Signal | Linux / macOS | Windows |
|---|---|---|
sigint |
yes | yes (Ctrl+C) |
sighup |
yes | yes (console window closed) |
sigterm |
yes | no |
sigusr1, sigusr2, sigwinch |
yes | no |
| anything else | no | no |
Note the two different failure modes. An unsupported signal makes watch() throw a SignalException right away. SIGTERM on Windows gets past that check but fails in the OS, and the error arrives asynchronously on the stream. If you don't have an onError handler, that's an unhandled exception that crashes the program. The safe approach is to not watch SIGTERM on Windows at all:
final signals = [
ProcessSignal.sigint,
if (!Platform.isWindows) ProcessSignal.sigterm,
];
Windows has no real signals. Ctrl+C and closing the console window are console events that Dart maps to sigint and sighup. There is no ProcessSignal for Ctrl+Break, and "killing" a process on Windows always terminates it without giving it a chance to clean up (see "Sending signals" below).
Waiting for a shutdown signal
Most programs want one thing: "tell me when I should stop". This helper completes a Future with the first SIGINT or SIGTERM:
Future<ProcessSignal> waitForShutdownSignal() {
final signals = [
ProcessSignal.sigint,
if (!Platform.isWindows) ProcessSignal.sigterm,
];
final completer = Completer<ProcessSignal>();
final subs = <StreamSubscription<ProcessSignal>>[];
for (final signal in signals) {
subs.add(signal.watch().listen((s) {
for (final sub in subs) {
sub.cancel();
}
completer.complete(s);
}));
}
return completer.future;
}
It cancels all subscriptions as soon as the first signal arrives. That has two benefits:
- the subscriptions no longer keep the process alive
- the default handlers are back, so if shutdown hangs, a second Ctrl+C (or
SIGTERM) kills the process immediately
The second point is the behavior users expect: the first Ctrl+C asks nicely, the second one means it.
For a single signal, ProcessSignal.sigint.watch().first does the same thing, because first cancels its subscription after the first event.
Graceful shutdown of an HTTP server
A graceful HTTP server shutdown has these steps:
- Stop accepting new connections.
- Let requests that are already being handled finish.
- Give up after a deadline and close the remaining connections forcibly.
- Release other resources (database pools, files) and exit.
HttpServer.close() does step 1, but be careful: the Future it returns completes as soon as the server stops listening. It does not wait for in-flight requests to finish. To know when they are done, track them yourself:
import 'dart:async';
import 'dart:io';
Future<ProcessSignal> waitForShutdownSignal() {
final signals = [
ProcessSignal.sigint,
if (!Platform.isWindows) ProcessSignal.sigterm,
];
final completer = Completer<ProcessSignal>();
final subs = <StreamSubscription<ProcessSignal>>[];
for (final signal in signals) {
subs.add(signal.watch().listen((s) {
for (final sub in subs) {
sub.cancel();
}
completer.complete(s);
}));
}
return completer.future;
}
/// Counts requests that are being handled and lets you wait
/// until there are none left.
class InFlight {
int _count = 0;
Completer<void>? _idle;
int get count => _count;
Future<void> track(Future<void> Function() handler) async {
_count++;
try {
await handler();
} finally {
_count--;
if (_count == 0) {
_idle?.complete();
_idle = null;
}
}
}
Future<void> get idle {
if (_count == 0) return Future.value();
return (_idle ??= Completer<void>()).future;
}
}
Future<void> handle(HttpRequest request) async {
final secs = int.tryParse(request.uri.queryParameters['secs'] ?? '') ?? 0;
print('-> ${request.uri}');
await Future.delayed(Duration(seconds: secs));
request.response.write('done ${request.uri}\n');
await request.response.close();
print('<- ${request.uri}');
}
Future<void> main() async {
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 8080);
final inFlight = InFlight();
print('Listening on http://localhost:${server.port} (pid $pid)');
server.listen((request) {
inFlight.track(() => handle(request));
});
final signal = await waitForShutdownSignal();
print('$signal: stopping, ${inFlight.count} request(s) in flight');
await server.close(); // stop accepting new connections
try {
await inFlight.idle.timeout(const Duration(seconds: 5));
print('All requests finished');
} on TimeoutException {
print('Gave up waiting for ${inFlight.count} request(s)');
await server.close(force: true);
}
// Release other resources: database pools, files, timers...
print('Cleanup done');
// Exit explicitly: a handler that is still running (or any
// forgotten timer) would otherwise keep the process alive.
exit(128 + signal.signalNumber);
}
To try it, start a request that takes 2 seconds, then send SIGTERM while it's running:
$ dart server.dart &
$ curl "localhost:8080/report?secs=2" &
$ kill -TERM %1
The request completes before the server exits:
Listening on http://localhost:8080 (pid 671)
-> /report?secs=2
SIGTERM: stopping, 1 request(s) in flight
done /report?secs=2
<- /report?secs=2
All requests finished
Cleanup done
The exit code is 143. A request that takes 20 seconds hits the 5 second deadline instead. The connection is closed forcibly and the client gets no response:
Listening on http://localhost:8080 (pid 692)
-> /report?secs=20
SIGTERM: stopping, 1 request(s) in flight
Gave up waiting for 1 request(s)
Cleanup done
The final exit() matters here. close(force: true) closes the socket, but the handler's Future.delayed is still pending. Without exit(), the process would stay alive for 15 more seconds until that handler finishes.
And if shutdown takes too long for the user, a second signal kills the process right away, because waitForShutdownSignal restored the default handlers:
Listening on http://localhost:8080 (pid 648)
-> /report?secs=20
SIGTERM: stopping, 1 request(s) in flight
^C
$ echo $?
130
exit()stops the VM immediately. It doesn't runfinallyblocks or wait for pending futures, so only call it after everything that matters (flushing files, closing database connections) has been awaited. If you are sure nothing else is pending, you can instead set the top-levelexitCodevariable and letmainreturn. The process then exits with that code once the event loop is empty.
If you use package:shelf, shelf_io.serve() returns the same HttpServer, so the same pattern applies.
A shutdown hook registry
In a bigger application, many components own resources: a log file, a database pool, a cache client, background timers. Rather than putting all cleanup in main, let each component register a shutdown hook. A small registry can then:
- run the hooks in reverse order of registration, like nested
try/finallyblocks (the database registered first is closed last, after everything that uses it) - put a timeout on each hook, so one stuck hook doesn't block the rest
- catch errors, so one failing hook doesn't skip the others
- force an exit on a second signal
import 'dart:async';
import 'dart:io';
typedef ShutdownHook = FutureOr<void> Function();
class Shutdown {
final _hooks = <(String, ShutdownHook)>[];
final _subs = <StreamSubscription<ProcessSignal>>[];
bool _started = false;
/// Registers cleanup code. Hooks run in reverse order of
/// registration, like nested try/finally blocks.
void add(String name, ShutdownHook hook) => _hooks.add((name, hook));
void watchSignals() {
final signals = [
ProcessSignal.sigint,
if (!Platform.isWindows) ProcessSignal.sigterm,
];
for (final signal in signals) {
_subs.add(signal.watch().listen((s) {
run(exitCode: 128 + s.signalNumber, reason: s.toString());
}));
}
}
Future<Never> run({required int exitCode, required String reason}) async {
if (_started) {
print('Already shutting down, forcing exit');
exit(exitCode);
}
_started = true;
print('Shutting down: $reason');
for (final (name, hook) in _hooks.reversed) {
try {
await Future.sync(hook).timeout(const Duration(seconds: 2));
print(' $name: ok');
} on TimeoutException {
print(' $name: timed out');
} catch (e) {
print(' $name: failed: $e');
}
}
exit(exitCode);
}
}
Future<void> main() async {
final shutdown = Shutdown()..watchSignals();
final log = File('app.log').openWrite();
shutdown.add('log file', () async {
log.writeln('stopped at ${DateTime.now()}');
await log.close();
});
shutdown.add('database', () async {
await Future.delayed(const Duration(milliseconds: 100));
});
shutdown.add('cache', () => throw StateError('cache already closed'));
shutdown.add('metrics', () => Completer<void>().future); // never completes
final timer = Timer.periodic(const Duration(seconds: 1), (_) {
log.writeln('tick');
});
shutdown.add('timer', timer.cancel);
print('Running (pid $pid)');
}
Future.sync(hook) turns both synchronous and asynchronous hooks into a Future, and also catches a synchronous throw as a failed Future. Sending SIGTERM after 1.5 seconds:
Running (pid 742)
Shutting down: SIGTERM
timer: ok
metrics: timed out
cache: failed: Bad state: cache already closed
database: ok
log file: ok
The exit code is 143 and the log file was flushed:
$ tail -2 app.log
tick
stopped at 2026-10-17 21:13:49.878098
Unlike waitForShutdownSignal, this registry keeps listening during shutdown and handles the second signal itself. When SIGINT arrives while the stuck metrics hook is still running:
Running (pid 723)
Shutting down: SIGTERM
timer: ok
Already shutting down, forcing exit
Because run() is a public method, you can also trigger shutdown from code (a /quit admin endpoint, a fatal error) or from a test, without sending a real signal.
Reloading configuration and other custom signals
Signals aren't only for stopping. A Unix convention is that SIGHUP tells a daemon to reload its configuration, and SIGUSR1/SIGUSR2 trigger application-defined actions like dumping statistics or rotating logs. None of these are available on Windows, except SIGHUP, which there means the console window was closed.
import 'dart:io';
Map<String, String> loadConfig(String path) {
final config = <String, String>{};
for (final line in File(path).readAsLinesSync()) {
final i = line.indexOf('=');
if (i > 0) config[line.substring(0, i).trim()] = line.substring(i + 1).trim();
}
return config;
}
void main() {
const path = 'app.conf';
File(path).writeAsStringSync('level=info\n');
var config = loadConfig(path);
var requests = 0;
print('Started with $config');
ProcessSignal.sighup.watch().listen((_) {
try {
config = loadConfig(path);
print('SIGHUP: reloaded $config');
} on IOException catch (e) {
print('SIGHUP: reload failed, keeping old config: $e');
}
});
ProcessSignal.sigusr1.watch().listen((_) {
print('SIGUSR1: handled $requests requests, config $config');
});
ProcessSignal.sigterm.watch().listen((_) {
print('SIGTERM: bye');
exit(0);
});
// Simulated work, and an edit to the config file.
Stream.periodic(const Duration(milliseconds: 100)).listen((_) => requests++);
Future.delayed(const Duration(seconds: 1), () {
File(path).writeAsStringSync('level=debug\n');
});
}
Sending signals from another terminal with kill -USR1 <pid>, kill -HUP <pid>, kill -USR1 <pid> and kill -TERM <pid>:
Started with {level: info}
SIGUSR1: handled 6 requests, config {level: info}
SIGHUP: reloaded {level: debug}
SIGUSR1: handled 22 requests, config {level: debug}
SIGTERM: bye
If the reload fails (missing file, bad syntax), keep running with the old configuration and log the problem. Crashing a production server because of a typo in a config file is worse than ignoring the reload.
Sending signals to child processes
Process.kill() sends a signal to a process started with Process.start(). The default signal is SIGTERM. To signal an arbitrary process by id, use Process.killPid(pid, signal). Both return true if the signal was delivered. See Running OS commands for more on starting processes.
This is also the way to test shutdown logic: start the program as a child process, wait until it's ready, send a signal and check the output and exit code. Here's a worker that cleans up on SIGINT/SIGTERM (worker.dart):
import 'dart:io';
void main() {
final signals = [
ProcessSignal.sigint,
if (!Platform.isWindows) ProcessSignal.sigterm,
];
for (final signal in signals) {
signal.watch().listen((s) async {
print('worker: got $s, flushing data');
await Future.delayed(const Duration(milliseconds: 200));
print('worker: clean exit');
exit(0);
});
}
print('ready');
}
And the parent that stops it (parent.dart):
import 'dart:convert';
import 'dart:io';
Future<void> main() async {
final script = Platform.script.resolve('worker.dart').toFilePath();
final worker = await Process.start(Platform.resolvedExecutable, [script]);
final lines = worker.stdout
.transform(utf8.decoder)
.transform(const LineSplitter())
.asBroadcastStream();
lines.listen((line) => print('[child] $line'));
await lines.firstWhere((line) => line == 'ready');
print('sending SIGTERM to ${worker.pid}');
final sent = worker.kill(); // ProcessSignal.sigterm is the default
print('delivered: $sent');
final code = await worker.exitCode;
print('worker exit code: $code');
}
Waiting for the ready line is important: a signal sent before the child has called watch() gets the default behavior and kills it.
On Linux:
[child] ready
sending SIGTERM to 795
delivered: true
[child] worker: got SIGTERM, flushing data
[child] worker: clean exit
worker exit code: 0
On Windows the same program prints:
[child] ready
sending SIGTERM to 16044
delivered: true
worker exit code: -1
On Windows kill() ignores the signal argument and terminates the process outright, so the child's cleanup code never runs. There is no portable way to ask a Windows process to shut down gracefully. A common workaround is a custom channel: write a quit command to the child's stdin, or call an HTTP endpoint, and have the child shut down when it receives it.
When a child is killed by a signal it doesn't handle, exitCode on Linux and macOS is the negative signal number. With worker.kill(ProcessSignal.sigkill) the output ends with:
worker exit code: -9
Stopping worker isolates
Signals are delivered to the process, not to a specific isolate. Usually the main isolate watches them and tells worker isolates to stop by sending a message, so each worker can finish its current job first. See Isolates for an introduction to isolates and ports.
import 'dart:io';
import 'dart:isolate';
// Runs in a worker isolate: processes jobs until told to stop.
Future<void> worker((SendPort, SendPort) ports) async {
final (ready, done) = ports;
final commands = ReceivePort();
ready.send(commands.sendPort);
var stopping = false;
commands.listen((msg) {
if (msg == 'stop') stopping = true;
});
var jobs = 0;
while (!stopping) {
await Future.delayed(const Duration(milliseconds: 300)); // one job
jobs++;
}
commands.close();
Isolate.exit(done, 'worker finished $jobs jobs');
}
Future<void> main() async {
final ready = ReceivePort();
final done = ReceivePort();
await Isolate.spawn(worker, (ready.sendPort, done.sendPort));
final toWorker = await ready.first as SendPort;
print('Worker started (pid $pid)');
await ProcessSignal.sigint.watch().first;
print('SIGINT: asking worker to stop');
toWorker.send('stop');
print(await done.first);
}
Pressing Ctrl+C after about 1.6 seconds:
Worker started (pid 645)
^CSIGINT: asking worker to stop
worker finished 3 jobs
This program doesn't call exit(). Once the worker isolate has exited and all ports and subscriptions are closed (first cancels its subscription after one event), the event loop is empty and the process exits normally with code 0. That's the cleanest kind of shutdown: nothing is cut off.
Docker, Kubernetes and systemd
Process managers stop a program in two steps: they send SIGTERM, wait for a grace period, then send SIGKILL. The grace period is 10 seconds for docker stop, 30 seconds by default in Kubernetes (terminationGracePeriodSeconds) and 90 seconds by default in systemd (TimeoutStopSec). Your shutdown deadline must be shorter than the grace period, or your cleanup gets cut off by SIGKILL.
To make sure the signal actually reaches your Dart program in a container:
- Compile to a native executable with
dart compile exe(see Compiling to executables) and run it directly as the container's main process. - Use the exec form of
ENTRYPOINT/CMD, which runs your program as PID 1:
FROM dart:stable AS build
WORKDIR /app
COPY . .
RUN dart pub get && dart compile exe bin/server.dart -o bin/server
FROM scratch
COPY --from=build /runtime/ /
COPY --from=build /app/bin/server /app/bin/server
ENTRYPOINT ["/app/bin/server"]
- Avoid the shell form (
ENTRYPOINT /app/bin/server). It runs/bin/sh -c ...as PID 1, and the shell does not forwardSIGTERMto its child. Your program never sees the signal and gets killed bySIGKILLat the end of the grace period.
Also note that a process running as PID 1 in a container gets no default signal handling from the kernel: a SIGTERM that the program doesn't handle is simply ignored. With a SIGTERM handler, as shown in this article, that's not a problem.
Summary
- Use
ProcessSignal.sigint.watch()(Ctrl+C) andProcessSignal.sigterm.watch()(kill, Docker, Kubernetes) to learn that the program should stop. - Don't watch
SIGTERMon Windows. Onlysigintandsighupwork there, and other signals throw aSignalException. - Listening disables the default "terminate" behavior. Cancel the subscriptions once shutdown starts so a second signal kills the process.
HttpServer.close()stops accepting connections but doesn't wait for in-flight requests. Track them and wait with a timeout, thenclose(force: true).- Run cleanup in reverse order, with a timeout and error handling per step.
exit()skipsfinallyblocks and pending futures. Call it only after cleanup has been awaited, or setexitCodeand let the program end on its own.- Exit with
128 + signal.signalNumber(130, 143) to report how the program was stopped. - Test shutdown by starting the program with
Process.start, waiting for it to be ready and callingkill(). That only works on Linux and macOS, because on Windowskill()always terminates the process outright.