Skip to content

Core\Server::isDraining

Core\Server::isDraining(): bool

Core\Server::isDraining() returns true when the server that runs your program has started to shut down. It returns false while the server works normally.

A server shuts down in steps. First it stops accepting new connections. Then it gives the requests it already has some time to finish. This is called draining. During this time, isDraining() returns true, so a request can see that the server is about to stop.

A command-line program is not run by a server. There, isDraining() always returns false.

Good to know: the server's health_path setting gives a load balancer the same answer. Use isDraining() when you write your own health check or when a long request should stop early.

The examples below show the answer in a command-line program, a health check for a load balancer, and a job that stops between two items when the server shuts down.

Return value

Returns bool. true after the server stopped accepting new connections. false while it still accepts them. A program that no server runs, such as a command-line program, always gets false.

Examples

Check the server

<?nvs
// Shows how to check whether the server has started to shut down.
// No server runs this program, so `Core\Server::isDraining` returns `false`.
// This prints "The server accepts new requests."
if (Core\Server::isDraining()) {
echo "The server is shutting down.\n";
} else {
echo "The server accepts new requests.\n";
}
Output
The server accepts new requests.

A health check for a load balancer

<?nvs
// Shows a health check that tells a load balancer to stop sending requests during a shutdown.
// A load balancer calls this address every few seconds.
// Status 503 tells it to send new requests to another server.
if (Core\Server::isDraining()) {
Core\Response::setStatus(503);
Core\Response::sendText("shutting down\n");
} else {
// The server is not shutting down, so the status is 200 and the body is "ok".
Core\Response::sendText("ok\n");
}
Output
ok

Stop a long job between items

<?nvs
// Shows a long job that stops between two items when the server shuts down.
array<string> $invoices = ['INV-1001', 'INV-1002', 'INV-1003', 'INV-1004'];
uint $sent = 0;
foreach ($invoices as string $invoice) {
// The check runs before each item, so an item is never stopped halfway.
if (Core\Server::isDraining()) {
echo "The server is shutting down. The next run sends the rest.\n";
break;
}
echo 'Sent ', $invoice, "\n";
$sent = $sent + 1;
}
// No server runs this program, so the loop sends all four invoices.
echo $sent, " invoices sent\n";
Output
Sent INV-1001
Sent INV-1002
Sent INV-1003
Sent INV-1004
4 invoices sent