Graceful Shutdown
Stop accepting new requests and drain active connections.
Graceful Shutdown
Ply can stop the server without cutting active requests. The simplest option
is RunWithGracefulShutdown.
app := ply.New()
app.Get("/", func(c *core.Context) {
c.Text(200, "ok")
})
if err := app.RunWithGracefulShutdown(":8080"); err != nil {
log.Fatal(err)
}This starts the server, waits for SIGINT or SIGTERM, then calls Shutdown
with a 10 second timeout. The call returns after shutdown completes or the
timeout expires.
Manual shutdown
Use RunServer and Shutdown when you need a different timeout or lifecycle:
app := ply.New()
app.Get("/", func(c *core.Context) {
c.Text(200, "ok")
})
go func() {
if err := app.RunServer(":8080"); err != nil {
log.Printf("server stopped: %v", err)
}
}()
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt, syscall.SIGTERM)
<-quit
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := app.Shutdown(ctx); err != nil {
log.Printf("shutdown: %v", err)
}What happens
- The listener stops accepting new connections.
- Active requests are allowed to finish.
- The call returns when they finish or the context expires.
Shutdownreturnsserver is not runningif the server was never started.
After the context deadline, remaining connections are closed. Choose a timeout that is longer than your slowest expected request but shorter than the orchestrator's termination grace period.
Containers
Kubernetes and most container runtimes send SIGTERM first, then SIGKILL
after a grace period. Set the grace period longer than the shutdown timeout.
A typical pair is a 30 second shutdown timeout and a 45 second termination
grace period.
terminationGracePeriodSeconds: 45Health checks
Stop reporting ready during shutdown. A readiness endpoint that returns 503
as soon as SIGTERM arrives gives load balancers time to remove the instance
before its listener closes.
Ply does not expose readiness hooks. Set an atomic flag in your signal handler and check it in the health route.
Notes
RunWithGracefulShutdownis not available for TLS. See the TLS page for a manual TLS shutdown example.- Do not call
Shutdowntwice. Handle the first error and exit. - Background goroutines are not tracked. Stop them yourself after the server drains.

Ply