How to Accept Connections From systemd Without Dropping Any on Restart
Restart an ordinary server and there is a gap: the old process has closed its listening socket and the new one has not opened it yet. Anyone connecting in that gap gets "connection refused". The fix is to let systemd own the listening socket and lend it to your process.
The socket stays open while your service restarts. New connections wait in the kernel's queue until the new process calls accept. You don't need a proxy, a second instance or any clever port sharing.
Two units: one holds the port, one runs the code
The socket unit is tiny. Save it as /etc/systemd/system/hello.socket:
[Socket]
ListenStream=127.0.0.1:8080
[Install]
WantedBy=sockets.target
The service has the same name, which is how systemd pairs them. This is /etc/systemd/system/hello.service:
[Unit]
Requires=hello.socket
After=hello.socket
[Service]
ExecStart=/usr/local/bin/hello
DynamicUser=yes
TimeoutStopSec=30
Leave Accept= at its default of no. That passes your service the listening socket itself. With Accept=yes, systemd accepts each connection and starts a service instance for it, which is a different design.
Your program picks up file descriptor 3
The protocol for receiving sockets is pleasingly small:
LISTEN_PIDnames the process the descriptors are meant for.LISTEN_FDSsays how many there are.- The descriptors start at number 3, after stdin, stdout and stderr.
That means Go needs only the standard library. Here is the whole server, with a deliberately slow handler so that restarts catch requests in flight.
package main
import (
"context"
"errors"
"fmt"
"log"
"net"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"time"
)
// systemdListener returns the one socket systemd passed to this process.
func systemdListener() (net.Listener, error) {
if os.Getenv("LISTEN_PID") != strconv.Itoa(os.Getpid()) {
return nil, errors.New("LISTEN_PID is not ours: not socket activated")
}
if n := os.Getenv("LISTEN_FDS"); n != "1" {
return nil, fmt.Errorf("want exactly 1 socket, LISTEN_FDS=%q", n)
}
f := os.NewFile(3, "systemd-socket") // passed descriptors start at 3
defer f.Close() // FileListener works on its own duplicate
return net.FileListener(f)
}
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
ln, err := systemdListener()
if err != nil {
return err
}
srv := &http.Server{
ReadHeaderTimeout: 5 * time.Second,
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(200 * time.Millisecond) // pretend to work
fmt.Fprintln(w, "hello from", os.Getpid())
}),
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
defer stop()
serveErr := make(chan error, 1)
go func() { serveErr <- srv.Serve(ln) }()
select {
case err := <-serveErr:
return err
case <-ctx.Done():
}
// Serve returns as soon as this starts, so wait here, not on Serve.
drain, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
return srv.Shutdown(drain)
}
Quick detour: net.FileListener duplicates the descriptor, so there are several handles on one kernel socket, including systemd's. Closing yours only drops your reference. That is why Shutdown can close the listener without closing the port. Rather neat.
Drain what you have already accepted
Socket activation protects connections still in the queue. Once you call accept, the connection is your problem. If the process exits mid-request, systemd cannot rescue it.
On restart, the sequence you want is:
- systemd sends
SIGTERMto the old process. Shutdownstops accepting and waits for active requests.- The old process exits.
- The new process starts, inherits the same socket and works through the queue.
Keep the drain timeout (20 seconds here) shorter than TimeoutStopSec (30), or systemd may kill you while you are still being polite. Hijacked connections, such as WebSockets, are not covered by Shutdown and need their own draining.
Install it, then try to break it
Build the binary, put it in place and enable the socket:
go build -o hello .
sudo install -m 755 hello /usr/local/bin/hello
sudo systemctl daemon-reload
sudo systemctl enable --now hello.socket
curl http://127.0.0.1:8080/
That first curl starts the service. To deploy a new version, replace the binary and run sudo systemctl restart hello.service. Restart the service, never the socket: stopping the socket closes the port and throws away its queue. Changes to the socket unit therefore need a real maintenance gap.
I tested this code with temporary user units on systemd 259 and Go 1.27.4, on port 18089. A load generator ran 50 concurrent clients for 20 seconds while the service was restarted 15 times:
- With a new connection per request: 4,900 succeeded, 0 failed.
- With keep-alive: 4,900 succeeded, 0 failed.
Treat the keep-alive result with some care. A server closing an idle connection can race with a client sending on it. Go's HTTP client retries some idempotent requests when that happens to a reused connection, but your client might not, and a POST without an idempotency key is not normally retried.
A broken binary will eventually close the port
Things go differently when a new version crashes on startup. I swapped the service's command for /bin/false and made one request. systemd retried until it hit the start limit, then the client got "connection reset by peer".
Both units ended up failed, the socket with Result=service-start-limit-hit. The next request was refused. A bad release can outlast the time the queue buys you.
After fixing the binary, recover with:
sudo systemctl reset-failed hello.service hello.socket
sudo systemctl start hello.socket
systemctl status hello.socket hello.service
The same limiter can bite a healthy service. The usual default is five starts in ten seconds, and manual restarts count. For my rapid-fire test I set StartLimitIntervalSec=0 under [Unit]. I would not copy that into production just to quieten a deploy script, since the limit is there to stop crash loops.
The queue is finite, and so is patience
Those waiting connections sit in the listen backlog. Backlog= defaults to a huge number, but the kernel silently caps it at net.core.somaxconn, typically 4096.
At 500 new connections a second, 4096 places last about eight seconds. A full queue means new connection attempts stall or fail, and clients with short timeouts can give up even when there is room. Check the real figures:
sysctl net.core.somaxconn
ss -ltn 'sport = :8080'
For a listening socket, Recv-Q is the number of connections waiting and Send-Q is the limit. Your worst-case wait is drain time plus startup time, so one 20-second request can hold up everyone queued behind the restart. Also leave FlushPending= at its default of no; turning it on discards pending connections when the service exits.