Signal-driven shutdown
You can connect SIGTERM to context cancellation and wait for long-lived goroutines to stop, which both binaries need before closing their clients.
Learning outcomes
- Explain how SIGTERM and SIGINT become context cancellation through
signal.NotifyContext. - Describe how
http.Server.Shutdownstops accepting connections and drains in-flight requests under a deadline. - Coordinate the relay and consumer loops so they stop before their Kafka clients and database connections close.
- Explain consumer-group cleanup and why an uncommitted Kafka event can be delivered again.
- Validate
JWT_SECRETbefore the API starts listening and keep the complete shutdown within 10 seconds.
Your API serves checkout requests while its relay publishes committed outbox rows to the order-events topic. The notifier in cmd/worker consumes order-events and order-events.retry. When a deployment sends SIGTERM, both processes must stop within 10 seconds without leaving an API listener open or closing a Kafka client that a goroutine is still using.
Graceful shutdown is the process of stopping new work, allowing work already in progress to finish or be handed back safely, and releasing resources before the process exits. Each part needs an owner and a way to stop. The order matters because your handlers, relay and consumers share resources.
Signals and context cancellation
The operating system tells a process when it should stop through a signal. The signals you need to distinguish are:
- SIGINT: an interrupt, commonly sent when you press Ctrl-C in a terminal.
- SIGTERM: a termination request sent by a process supervisor or deployment system.
- SIGKILL: an immediate termination that the process cannot catch or handle.
Your API and worker need to handle SIGTERM. Supporting SIGINT as well makes local development easier.
Go's signal handling package can turn a signal into context cancellation. signal.NotifyContext returns a context that is cancelled when one of the specified signals arrives.
ctx, stop := signal.NotifyContext(
context.Background(),
os.Interrupt,
syscall.SIGTERM,
)
defer stop()The returned ctx is the root context for the process lifecycle. When the process receives SIGINT or SIGTERM, ctx.Done() is closed. Any component using this context, or a context derived from it, can observe the cancellation.
A context does not terminate a goroutine by itself. It communicates that the goroutine should stop. The goroutine must check the context and return from its own work loop.
For example, a background loop can wait for either its next unit of work or cancellation:
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
publishPending()
}
}The loop checks for cancellation between work cycles. If publishPending can block, that operation also needs a way to observe cancellation or a bounded execution time.
Ownership of background goroutines
Every goroutine needs an owner, a cancellation path and a way for its owner to wait for it. This is the goroutine lifecycle applied to process shutdown.
The API starts an outbox relay that uses both MySQL and Kafka. Its owner must know when the relay has returned before closing the resources it uses.
A sync.WaitGroup tracks whether a goroutine has finished:
workCtx, cancelWork := context.WithCancel(ctx)
defer cancelWork()
var relay sync.WaitGroup
relay.Add(1)
go func() {
defer relay.Done()
outbox.NewRelay(db, producer).Run(workCtx)
}()Call Add before starting the goroutine. The deferred Done runs when the relay returns. The process owner can then call relay.Wait() to wait for that return.
Cancellation and waiting solve different problems:
- Calling a cancellation function tells the goroutine to stop.
- The goroutine's context checks give it an opportunity to stop.
Waittells the owner when the goroutine has actually returned.
Calling cancelWork() does not mean the relay has finished. Closing its Kafka producer immediately afterward can still interrupt a publish that is in progress.
The same rule applies to the worker's consumer loops. Starting them with go does not give the process a way to know when they have finished. Track both loops and wait for both before closing shared resources.
Draining the HTTP server
The API has a different kind of work to stop. It accepts HTTP requests through the listener configured by HTTP_ADDR. When shutdown starts, it must stop accepting new connections and allow active requests to finish.
http.Server.Shutdown(ctx) handles this drain. It closes the server's listeners and idle connections, then waits for active connections to become idle. It returns when the drain finishes or its context expires.
shutdownCtx, cancel := context.WithTimeout(
context.Background(),
10*time.Second,
)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
slog.Error("http shutdown", "err", err)
}Use a fresh context for this operation. The signal context is already cancelled when shutdown begins. Passing it directly to Shutdown gives the drain an already-expired context, so it cannot wait for requests to finish.
After a successful shutdown, ListenAndServe returns http.ErrServerClosed. This is the expected result of calling Shutdown, not a server failure. Treating it as a fatal error can make a normal SIGTERM produce a non-zero exit status.
There is another distinction to keep in mind: the HTTP server and the relay have separate lifecycles. Shutdown manages HTTP connections. It does not stop the relay or wait for its goroutine.
The API therefore needs to coordinate both operations. The signal tells the relay to stop, while the server begins draining HTTP requests. The process waits for the HTTP shutdown and for the relay to return before closing the producer.
The API resource order
The relay reads pending outbox rows from MySQL and publishes them to Kafka. The producer must remain open while that relay is running.
A safe shutdown keeps the dependencies available until their users have stopped:
- Receive SIGTERM and cancel the work context.
- Stop accepting HTTP connections and drain in-flight requests.
- Wait for the relay goroutine to return.
- Close the Kafka producer.
- Close the database connection when its remaining users have stopped.
The HTTP server and relay may begin stopping at the same time. What matters is that the process does not close their shared resources until both have finished.


The relay is backed by the transactional outbox. That pattern stores the order change and its publication intent in the same MySQL transaction. If shutdown interrupts the relay before an outbox row is published, the row remains available for a later relay run. Closing the producer while the relay is still using it creates an avoidable publish failure.
The database has the same dependency rule. HTTP handlers and the relay can both use it. Close the database only after the server has drained and the relay has returned.
A shutdown that waits indefinitely is not graceful. Every operation that can block needs a bound, and the process needs one overall deadline.
Consumer-group cleanup
The notifier has two consumer loops. One consumes order-events under the notifier consumer group. The other consumes order-events.retry under the notifier-retry consumer group.
A consumer group coordinates which records its members process from a topic's partitions. When a consumer stops, it needs to leave the group so another member can take over its partitions without waiting for the old member's session to expire.
The worker's Run method needs to observe the cancelled context and perform its consumer cleanup before returning. With franz-go's BlockRebalanceOnPoll option, a poll can leave rebalancing blocked while fetched records are being processed. The worker must call AllowRebalance() when that processing is finished, then leave the group with a bounded context before closing its consumer.
Stopping the process does not mean every fetched record has been completed. Kafka uses committed offsets to track which records a consumer group has finished. Receiving a record is not the same as committing its offset.
Consider a record that the notifier receives but does not commit before shutdown. The group can deliver that record again after the worker restarts. This is expected at-least-once delivery. The notifier must make repeated processing safe by using the event identity to recognise work it has already applied.
The process owner must wait for both consumer loops to return:
Cancel the worker context
Wait for the primary consumer loop
Wait for the retry consumer loop
Close the shared Kafka producer
Close the databaseWaiting for both loops matters because each can still be using shared resources. Closing the producer or database while either loop is active can interrupt its cleanup or processing.
Bounded shutdown
The complete process shutdown must finish within 10 seconds of SIGTERM. That is the limit checked for both binaries, not a separate allowance for every shutdown stage.
A shutdown can exceed its deadline even when every individual operation seems reasonable. For example, an HTTP drain that consumes the entire budget leaves no time for relay cleanup or consumer-group departure. Choose internal deadlines with the full process deadline in mind.
The worker has an additional responsibility during consumer cleanup. If it exits while processing a record, it must not commit an offset for work it did not finish. Leaving the record uncommitted allows Kafka to deliver it again. The notifier's event handling must tolerate that replay.
Startup configuration
Graceful shutdown only helps a process that started with valid configuration. The API signs access tokens using JWT_SECRET, which must contain at least 32 bytes.
Validate the secret before starting the HTTP listener. Go strings are byte sequences, so len(secret) measures bytes rather than Unicode characters.
secret := os.Getenv("JWT_SECRET")
if len(secret) < 32 {
return errors.New("JWT_SECRET must contain at least 32 bytes")
}Both an empty value and short fail this check. The API should return a startup error and exit with a non-zero status instead of continuing to listen.
Read the API listener address from HTTP_ADDR as well. The shutdown test starts another API instance on an available address, requests GET /healthz, and checks that the listener is released after SIGTERM.
Be careful with os.Exit. It terminates the process immediately and does not run deferred functions. Use it only when you have already decided that no deferred cleanup remains. During normal shutdown, let the lifecycle owner wait for its components and return normally so cleanup can finish.
Shutdown ownership in both binaries
The API and worker have different resources, but the same ownership rule applies. The API coordinates its HTTP server and relay. The worker coordinates its two consumer loops. Neither process should close a shared client while a goroutine still uses it.
The API and notifier shutdown exercise checks these observable outcomes:
- The API listens on the address supplied through
HTTP_ADDR. GET /healthzreturns HTTP 200.- The API exits with status 0 within 10 seconds of SIGTERM and releases its listening address.
- The worker exits with status 0 within 10 seconds of SIGTERM.
- The API exits with a non-zero status when
JWT_SECRETis empty or contains fewer than 32 bytes.
These checks establish that both process lifecycles are managed correctly. The Kafka offset rule remains important for protecting event processing when a shutdown interrupts a consumer.
Check your understanding
The API receives SIGTERM while an HTTP request is still running. Which context should the API use for srv.Shutdown?
References
Everything above is explained on this page; these are where it comes from (Go 1.25 net/http and os/signal, franz-go v1.22).