# Add Graceful Shutdown to a Fiber App

Yes. An agent makes your Fiber v3 server drain in-flight requests on SIGTERM through ListenConfig's GracefulContext, fixes the exit code, tests it, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-graceful-shutdown/fiber/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads the one line that starts the server, because that is where the problem is. In a Fiber service like gofiber/boilerplate, `go.mod` names `github.com/gofiber/fiber/v3` v3.6.1 and `github.com/gofiber/utils/v2` v2.6.3 on a `go 1.26.0` directive, and `app.go` parses two flags, `-port` defaulting to `:3000` and `-prod` which turns on prefork, mounts `recover` and `logger` middleware, registers `GET` and `POST /api/v1/users` from `handlers/handlers.go`, serves `./static/public`, and ends with `log.Fatal(app.Listen(*port, fiber.ListenConfig{EnablePrefork: *prod}))`. Nothing watches for a signal, so a `SIGTERM` from `docker stop` ends the process at once, and a `POST /api/v1/users` that is between `c.FormValue` and `database.Insert` in `database/database.go` is lost.

It then checks how the process is run, which decides who sends the signal. `Dockerfile` builds a static binary in `golang:1.27-alpine`, copies it into `alpine` with `dumb-init` as `ENTRYPOINT`, and `Makefile` starts it with `./app` or `./app -prod`; `dumb-init` forwards `SIGTERM` to the binary, so the signal arrives either way. The agent also reads Fiber's own `ListenConfig`: v3 has a `GracefulContext` field, a `ShutdownTimeout` that `listenConfigDefault` sets to ten seconds when left at zero, and a `PreforkShutdownGracePeriod` for the prefork master, which is why it changes no middleware and writes no shutdown loop of its own.

The change is small. `app.go` builds a context with `signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)` and passes it as `GracefulContext` in the same `ListenConfig` that carries `EnablePrefork`. When the context ends, Fiber closes the listener and calls `ShutdownWithTimeout`, which waits for active handlers up to the timeout and leaves still-active connections alone after it. The agent registers `app.Hooks().OnPreShutdown` and `OnPostShutdown` to log the start and the result of the drain. It also replaces `log.Fatal(app.Listen(...))`, because after a clean shutdown `Listen` returns `nil` and `log.Fatal(nil)` still prints `<nil>` and exits non-zero; the new code logs and exits non-zero only on a real error, so an orchestrator reads a clean stop as success.

A test proves the drain. `app_test.go` builds the app through a new `newApp()` function split out of `main`, adds a route that sleeps for a few hundred milliseconds, serves it with `app.Listener` on a `net.Listen("tcp", "127.0.0.1:0")` port under a cancellable `GracefulContext`, fires the slow request, cancels the context while it is in flight, and asserts that the request still returns 200 and `Listener` returns `nil` before the timeout. The agent runs `go vet ./...` and `go test ./... -v -race` as `.github/workflows/test.yml` does, and `golangci-lint run` with the `modernize` linter `.golangci.yml` enables, because `lint.yml` runs it on every pull request.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add graceful shutdown to this Fiber v3 application. Read go.mod, app.go, handlers/handlers.go, database/database.go, Dockerfile, Makefile, .golangci.yml and .github/workflows/test.yml first. In app.go, create a context with signal.NotifyContext for SIGINT and SIGTERM and pass it as GracefulContext in the existing fiber.ListenConfig next to EnablePrefork; register OnPreShutdown and OnPostShutdown hooks that log the drain and its result. Replace log.Fatal(app.Listen(...)) so that a nil return after a clean shutdown exits zero and only a real error exits non-zero. Move the app construction into a newApp() function so a test can use it. Write app_test.go that serves newApp() with app.Listener on a 127.0.0.1:0 listener under a cancellable GracefulContext, sends a request to a deliberately slow route, cancels the context mid-request, and asserts the request completes with 200 and Listener returns nil before the shutdown timeout. Run gofmt -l, go vet ./..., go test ./... -v -race and golangci-lint run, and open a pull request that explains the shutdown order and what happens under -prod prefork.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that changes `app.go` and adds `app_test.go`. The description states the order on a signal: the listener closes, active handlers get up to the shutdown timeout, the post-shutdown hook logs the result, `Listen` returns and the process exits zero. It names the exit-code change explicitly, since a reader who kept `log.Fatal` would see every clean stop reported as a crash.

The run's record keeps the `go test -race` output with the new drain test beside the existing handler tests, and the `golangci-lint` run, so a reviewer sees the slow request complete through a shutdown rather than trusting the description.

Before merging, a reviewer decides whether ten seconds suits the platform's grace period, sets `ShutdownTimeout` explicitly if not, and reads the paragraph on prefork: with `-prod`, the master forwards the stop to its children and waits `PreforkShutdownGracePeriod` before killing them, so a drain longer than that period needs the field raised too. The agent leaves both values at Fiber's defaults and says so.

## Run it on every new service from the boilerplate

A team that stamps services out of one boilerplate runs this once per repository from its own server: one `POST /o/{org}/sessions` per repository, each with that repository in `resources` and a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run already started instead of opening a second pull request. Each run clones into its own sandbox, and the pull requests arrive independently.

To keep it in place, an automation on the Project with a `github` trigger on `pull_request.opened` and `pull_request.synchronize` and the prompt "check that app.go still passes a GracefulContext to Listen and does not call log.Fatal on its result; comment on the pull request if a change removes either" reads each new pull request. The trigger puts the pull request after the prompt; only work by an owner, member or collaborator fires it, never a fork's.

## Why run it on Rush?

Shutdown code is only tested by sending the signal while a request is in flight, which nobody does by hand twice. The agent does it in its own sandbox with a real listener on a free port and the race detector on, and the test stays in the repository so the next edit to `app.go` is checked the same way.

Every command the agent ran stays with the run, from `go vet` to the lint output, so the pull request can cite a passing drain test and an unchanged handler suite. Running this across a fleet of Fiber services at once costs no more attention than one, because each run has its own machine and its own record.

## Frequently asked questions

### Does Fiber not stop cleanly on its own?

No. `app.Listen` serves until the listener fails and installs no signal handler, so the Go runtime's default action on `SIGTERM` ends the process immediately. Fiber v3 gives you the pieces, `GracefulContext` and `ShutdownTimeout` on `ListenConfig` and the `Shutdown` family of methods on `App`; wiring a signal to them is the application's job.

### Why is log.Fatal(app.Listen(...)) a problem?

After a graceful stop `Listen` returns `nil`, and `log.Fatal(nil)` prints `<nil>` and exits with status 1 regardless. An orchestrator then records every clean stop as a failure. The change checks the error first and exits zero on a nil return.

### What about prefork under -prod?

With `EnablePrefork` the master process watches its children. On the context ending it signals them and waits `PreforkShutdownGracePeriod` before sending `SIGKILL`. The `GracefulContext` goes in the same `ListenConfig`, so the same code serves both modes; the reviewer only needs to make sure that grace period is at least the shutdown timeout.

### Will this slow down docker stop?

Only while a request is in flight. With no active handlers `ShutdownWithTimeout` returns at once. With one, it waits until that handler returns or the timeout passes, whichever comes first, and the container exits then. The Dockerfile's `dumb-init` entrypoint already forwards the signal, so nothing changes there.

## More Fiber jobs

- [Add Health Checks to a Fiber API](https://getrush.ai/run/add-health-checks/fiber/)
- [Add Idempotency Keys to a Fiber API](https://getrush.ai/run/add-idempotency-middleware/fiber/)
- [Add Input Validation to a Fiber API](https://getrush.ai/run/add-input-validation/fiber/)

## The same job on other stacks

- [Add Graceful Shutdown to a Gin API](https://getrush.ai/run/add-graceful-shutdown/gin/)
- [Add Graceful Shutdown to a Go Service from a Linear Issue](https://getrush.ai/run/add-graceful-shutdown/go/)
- [Add Graceful Shutdown to a grammY Bot](https://getrush.ai/run/add-graceful-shutdown/grammy/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
