CodeGym /Cursos /Go SELF /Stopping background tasks on shutdown

Stopping background tasks on shutdown

Go SELF
Nível 63, Lição 4
Disponível

1. Application context and the background life cycle

Background tasks usually appear unnoticed: first you write a server that "receives a request → responds", and then you add conveniences. For example, you may want to clean up stale data once a minute, save a snapshot of an in-memory store to disk every 10 seconds, periodically print statistics to the log, or refresh the cache. And then you end up with code that "just keeps running separately".

The problem is that the server can stop "cleanly" (via Shutdown), while the background part stops "uncleanly": keeps running, hangs while waiting, fails to finish writing data, holds resources (files, connections), or simply prevents the process from exiting in time. In practice, it looks like an eternal "the server stopped, but the process is still alive — why?" Spoiler: because someone somewhere started an infinite loop and forgot to give it an exit.

What is a goroutine

A goroutine is a lightweight execution thread in Go. It is started very simply: go f(). The key word is "lightweight": goroutines are much cheaper than OS threads, and Go can schedule their execution using its runtime (scheduler), distributing many goroutines across a limited number of system threads.

But "lightweight" does not mean "free" and certainly does not mean "you can start it forever and forget it". A goroutine has a stack, it does work, it can hold references to objects (preventing the garbage collector from freeing memory), it can hold an open file or a lock. So the rule is very down-to-earth: every background goroutine must have a clear path to termination. Otherwise your server turns into a California hotel: you can check in, but check out — sometimes not.

Request context and application context

In HTTP handlers we use r.Context() and get used to thinking: "here is the context, here is cancellation". But a background task usually lives longer than a single request, so it needs an application-level context, not the "context of a specific client".

To keep things straight, it is useful to keep a small table in mind:

Context Where it comes from When it is canceled What it is suitable for
r.Context()
inside the handler (
r *http.Request
)
when the client disconnects, the request deadline expires, or the server starts shutdown work "strictly per request" (request → computation → response)
appCtx (a conventional name) we create it ourselves: context.WithCancel(context.Background()) when the application shuts down (on signal/on shutdown) background loops: cleanup, periodic jobs, cache, service processes

In the documentation and articles about context, the idea is emphasized: a context contains a cancellation signal (Done) and can be passed to many parallel jobs; when it is canceled, they should terminate quickly.

Why r.Context() is not suitable for background work

Sometimes there is a temptation: "Oh! I already have the request context. I'll start a background task inside the handler and give it r.Context() — and it will cancel itself." Usually that is a bad idea.

The problem is that r.Context() lives exactly as long as the request lives. If the client closed the connection, if the timeout expired, if the server started shutdown — this context is canceled. For "long-running background work" this almost always means premature termination.

Imagine a real-life situation: the client hit the endpoint "recompute statistics", and you decided to do the recomputation in the background. The client got tired of waiting 300 ms and left. The request context was canceled — your background work stopped too. Result: the statistics were not recomputed, but you already "promised yourself" that they were being recomputed. Classic.

So the rule is simple: use r.Context() for work that is needed to answer this client, and use appCtx for work that is needed so that the server can just live normally.

2. Patterns for starting and stopping background tasks

Basic pattern: context, loop, and stop points

A background task almost always looks like a loop. So we need just two things: (1) start it in a goroutine so it does not block the main thread, (2) regularly check the cancellation signal so the loop can finish.

Let's start with the minimal application context:

package main

import (
	"context"
)

func main() {
	bgCtx, cancelBG := context.WithCancel(context.Background())
	defer cancelBG()

	_ = bgCtx
}

By itself, bgCtx does nothing, but it is the "red stop button" for all background tasks we will start.

Now let's make a background task that is a "periodic cleaner" (for example, it cleans expired tasks in our task API). The task itself will be as simple as possible: once per second it "does something", but when canceled — it exits.

package main

import (
	"context"
	"time"
)

func startCleaner(ctx context.Context) {
	go func() {
		for ctx.Err() == nil {
			// old tasks could be cleaned up here
			time.Sleep(1 * time.Second)
		}
	}()
}

Pay attention to one detail: we do not write an "infinite" for { } with no conditions. We explicitly say: "while the context is not canceled". That is your managed shutdown contract.

If you want a slightly more explicit check (sometimes it reads better), you can write it via if err := ctx.Err(); err != nil { ... }. In long-running work it usually looks like this:

package main

import (
	"context"
	"time"
)

func doWork(ctx context.Context) error {
	for i := 0; i < 5; i++ {
		if err := ctx.Err(); err != nil {
			return err
		}
		time.Sleep(200 * time.Millisecond)
	}
	return nil
}

Here is a very "Go-like" idea: context cancellation is not a "panic" and not "magic", it is an ordinary error value that can be returned outward.

Binding background shutdown to shutdown

Now the most important part: how to connect "the server starts shutdown" and "background tasks stop working".

For this, http.Server has a convenient mechanism: srv.RegisterOnShutdown(fn). It lets you register a function that the server will call when shutdown begins. This is a great place to send a "stop signal" to the whole background.

Let's put the binding together in a small, clear fragment. We assume that srv is already being created and shutdown is done correctly, with a timeout.

package main

import (
	"context"
	"net/http"
)

func main() {
	bgCtx, cancelBG := context.WithCancel(context.Background())
	defer cancelBG()

	mux := http.NewServeMux()
	srv := &http.Server{Addr: ":8080", Handler: mux}

	startCleaner(bgCtx)

	srv.RegisterOnShutdown(func() {
		cancelBG()
	})

	_ = srv
}

The logic here is very transparent: while the server is running, the background is running. As soon as the server is told "Shutdown", it calls our on-shutdown hooks, and we cancel bgCtx. After that, all background goroutines that respect ctx.Err() should finish quickly.

How to wait for completion: the done channel

Sometimes you want not only to "send the stop signal", but also to wait until the background really finishes (for example, so it has time to write the final log line or close the file). We will not build complex waiting schemes, but we will show the smallest and most readable option: the start function returns a done channel that is closed when the goroutine finishes.

package main

import (
	"context"
	"time"
)

func startCleaner(ctx context.Context) <-chan struct{} {
	done := make(chan struct{})
	go func() {
		defer close(done)

		for ctx.Err() == nil {
			time.Sleep(1 * time.Second)
		}
	}()
	return done
}

Now in main you can wait for the background to finish at the right moment. For example, after a successful Shutdown:

package main

import (
	"context"
	"log"
	"net/http"
	"time"
)

func main() {
	bgCtx, cancelBG := context.WithCancel(context.Background())
	mux := http.NewServeMux()
	srv := &http.Server{Addr: ":8080", Handler: mux}

	cleanerDone := startCleaner(bgCtx)
	srv.RegisterOnShutdown(func() { cancelBG() })

	go func() {
		time.Sleep(2 * time.Second) // suppose the "stop signal" arrived
		shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
		defer cancel()
		_ = srv.Shutdown(shutdownCtx)
	}()

	_ = srv.ListenAndServe()
	<-cleanerDone
	log.Printf("cleaner stopped") // cleaner stopped
}

Yes, here we simulate the "signal" with Sleep so the example stays short. In your real code, instead of this you will wait on the signal context: <-sigCtx.Done(). The point is different: the background goroutine has a formal end, and you can wait for it.

3. What this looks like in a task application

If we keep our educational task server in mind (/api/v1/tasks etc.), then the background task can be very realistic: "every N seconds delete tasks that have been marked as done more than a day ago" (or, hypothetically, "with an expired TTL"). Even if we do not have a real TTL right now, the background can still be used as an example of discipline: learn to start it and stop it correctly.

The scenario looks like this:

flowchart TD
    A[main: start HTTP server] --> B["create bgCtx = WithCancel(Background)"]
    B --> C["go: start cleaner(bgCtx)"]
    A --> D[wait for OS signal]
    D --> E["call srv.Shutdown(shutdownCtx)"]
    E --> F["RegisterOnShutdown: cancelBG()"]
    F --> G["cleaner sees ctx.Err() != nil and exits"]
    G --> H[main waits for cleanerDone and exits the process]

This is exactly what we are aiming for: a managed life cycle not only for the server, but also for everything "around the service".

4. Common mistakes

Mistake #1: "Started a goroutine and forgot about it" (an eternal loop with no exit).
At first such code seems fine, because "the server works". But on shutdown the process may hang, and at best it will exit without a chance to finish work cleanly (for example, without writing the file). The fix is usually boring, but correct: you add ctx and a ctx.Err() check in the loop, and in main you create context.WithCancel and call cancel() on shutdown.

Mistake #2: using r.Context() as the context of a background task.
In the first tests this may "work", because you start the background and quickly make requests. But in reality the client may leave, the load balancer may close the connection, the server may start shutdown — and you get cancellation "too early". The cure is to separate responsibilities: for the application's background life use a separate bgCtx, and keep r.Context() for work "within the request".

Mistake #3: you made context cancellation, but the background work still does not finish.
This happens when there are no stop points inside the loop, and the work is one large chunk that runs for a long time and does not check ctx.Err(). As a result, cancellation formally happened, but the goroutine only finds out about it "someday later". In practice, it helps to split the work into chunks and check ctx.Err() between steps, as we did in the example with the loop and time.Sleep.

Mistake #4: you forgot to bind shutdown and cancel the background "however it works".
When cancellation is scattered across several places, it is easy to get situations like "Shutdown is already underway, but the background is still running" or "the background was canceled before the server started closing". srv.RegisterOnShutdown is good because it turns background cancellation into part of the server shutdown protocol: one entry point, one event, fewer surprises.

Mistake #5: cancel() was never called (so the context exists, but it is useless).
Sometimes bgCtx is created, passed into a goroutine, ctx.Err() is checked — everything looks nice... but nobody ever calls cancellation. The background will not stop because it simply never received a signal. So the habit "created WithCancel — immediately put defer cancel() and/or bind cancel to shutdown" usually saves you from very silly hangs.

1
Tarefa
Go SELF, nível 63, lição 4
Bloqueado
Ticker controlado
Ticker controlado
1
Tarefa
Go SELF, nível 63, lição 4
Bloqueado
Encerramento do pulso em segundo plano
Encerramento do pulso em segundo plano
1
Tarefa
Go SELF, nível 63, lição 4
Bloqueado
Dois contextos
Dois contextos
1
Tarefa
Go SELF, nível 63, lição 4
Bloqueado
Dois serviços
Dois serviços
1
Pesquisa/teste
Encerramento gracioso, nível 63, lição 4
Indisponível
Encerramento gracioso
Encerramento gracioso
Comentários
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION