# Add Idempotency Keys to a Fiber API

Yes. An agent mounts Fiber's idempotency middleware on your write routes, makes the frontend send a key per request, tests the retry case and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-idempotency-middleware/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 routes and what sits behind them. In an app laid out like gofiber/boilerplate, `app.go` parses a `-port` and a `-prod` flag, calls `database.Connect()`, builds `fiber.New` with `recover` and `logger` middleware, groups `GET /users` and `POST /users` under `/api/v1`, serves `./static/public` and ends with `app.Listen(*port, fiber.ListenConfig{EnablePrefork: *prod})`. `handlers/handlers.go` has `UserCreate` reading `c.FormValue("user")` into a `models.User` and appending it to the in-memory slice in `database/database.go`, which is a `[]*models.User` behind a `sync.Mutex`. `static/public/js/app.js` posts a `FormData` with the username and inserts the returned name at the top of the list. `go.mod` is on `go 1.26.0` with `github.com/gofiber/fiber/v3 v3.6.1`; `.github/workflows/test.yml` runs `go test ./... -v -race` on Go 1.26 and 1.27 on Linux and Windows runners, `lint.yml` runs golangci-lint `v2.14.0` with `--tests=false`, and `.golangci.yml` enables `modernize`. There are no `_test.go` files.

Fiber ships the middleware, and the agent reads its source at the pinned version rather than the docs for the next one. `middleware/idempotency` in `v3.6.1` has a `Config` with `Next` (default: skip safe methods through `fiber.IsMethodSafe`), `Lifetime` (`30 * time.Minute`), `KeyHeader` (`X-Idempotency-Key`), `KeyHeaderValidate` (the key must be 36 characters, the length of a UUID), `KeepResponseHeaders` (nil keeps every header), an in-process `Lock` and an in-memory `Storage`, and `DisableValueRedaction`. A request with no key passes through untouched; the first request with a key runs the handler and stores the response for `Lifetime`; later requests with that key get the stored response; a handler that returns an error stores nothing. The version has no per-user key scope, so the key alone identifies a response, and the pull request says so: a key must be unguessable, which a version 4 UUID is.

The agent mounts it on the group, `v1.Use(idempotency.New(cfg))`, after `recover` and `logger` and before the routes, so `GET /users` is skipped by the default `Next` and `POST /users` is covered. `cfg.Lifetime` comes from a new `-idempotency-ttl` flag beside `-port`, and `cfg.KeyHeaderValidate` wraps the length check in `fiber.NewError(fiber.StatusBadRequest, ...)`, because the default returns a plain error that the default error handler turns into a `500`. Prefork is the trap: with `-prod`, Fiber runs several processes and the in-memory storage and lock are per process, so a retry landing on another process would run the handler again. The agent documents this in the README and leaves a commented `Storage` line for a shared backend from the gofiber storage repository, since the boilerplate's database is a slice in memory and would have the same problem. The frontend changes in `app.js`: each `POST` sets `X-Idempotency-Key` to `crypto.randomUUID()` generated before the `fetch`, so a retry of that same submission reuses the key.

Tests use `app.Test`, which Fiber provides for exactly this, and go in `app_test.go` next to a `newApp()` the agent extracts from `main` so the test and the binary build the same router. Two `POST /api/v1/users` with the same key and the same form value leave one entry in `database.Get()` and return byte-identical bodies; two different keys leave two; a request with no header behaves as today; a 10-character key answers `400`; a `GET` with a key is not stored. The suite runs with `go test ./... -race` as the workflow does, on both operating systems the matrix names, and the agent runs `golangci-lint run --tests=false` with the repository's config before opening the pull request.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add idempotency keys to the write routes of this Fiber v3 app. Read go.mod, app.go, handlers/handlers.go, database/database.go, models/user.go, static/public/js/app.js, static/public/index.html, Makefile, Dockerfile, .golangci.yml and .github/workflows/test.yml and lint.yml first, and read the idempotency middleware source in the Fiber module cache at the pinned version. Extract a newApp function from main, mount idempotency.New on the /api/v1 group after recover and logger with Lifetime from a new -idempotency-ttl flag and a KeyHeaderValidate that answers 400 through fiber.NewError. Make app.js send a crypto.randomUUID() X-Idempotency-Key on each POST. Add app_test.go using app.Test for a repeated key, two different keys, no header, a short key and a GET with a key. Explain in the README that the in-memory storage and lock are per process and what prefork means for that. Run go test ./... -race and golangci-lint with the repository config, then open a pull request that quotes the output.",
  "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

The pull request changes `app.go` (the `newApp` function, the flag and the group middleware), `static/public/js/app.js` (the header on each `POST`) and `README.md`, and adds `app_test.go`. Its description quotes the `go test -race` output and the golangci-lint result, and shows two `curl` calls from the sandbox with the same key where the second returns the first's body and the user list has grown by one.

A reviewer checks the `Lifetime` default against how long their clients retry, whether the response headers the middleware stores include anything per request they would rather not replay (the default keeps all of them), and the prefork note: a deployment that runs `-prod` behind one load balancer needs the shared storage before the guarantee holds across processes.

Reads are untouched by the default `Next`, the static site and the 404 handler are unchanged, and a client that sends no key gets exactly the behaviour it had.

## Run it on every new write route

The middleware covers a group, so the risk is a write route added outside it. An automation on the Project with a `github` trigger on `pull_request.opened` and `pull_request.synchronize` runs read-only with a prompt that lists every `Post`, `Put`, `Patch` and `Delete` registration in the pull request and comments when one is mounted on the app or on a group without the middleware, naming the file and line. The event the trigger adds after the prompt names the pull request; nothing is filled into the prompt.

A handler on your own server reading that comment sends this body to `POST /o/{org}/sessions` with the route appended to the prompt and the branch in `resources` as `https://github.com/your-org/your-app/tree/<branch>`, and a `request_id` that is a UUID v5 of the head SHA so a redelivered event returns the run already started. The run pushes to the branch, and the key's `webhook_url` gets `run.completed`.

## Why run it on Rush?

Idempotency is proven by repeating a request and reading the second answer, which is the one thing a code review cannot do. The agent builds and runs the server in its own sandbox, sends the same request twice with the same key and once more with a new one, and keeps the responses and the resulting user list in the run's record beside the tests.

Every Fiber service with a form or JSON write has the same gap, and each would read the middleware source and discover the prefork caveat on its own. One run per repository mounts it on that service's groups, writes that service's tests, and opens one pull request each with the same header name and the same README note.

## Frequently asked questions

### Does a request without the header still work?

Yes. The middleware only acts when `X-Idempotency-Key` is present, so existing clients and the `curl` examples in the README behave as before. The frontend sends a key on every `POST` so a browser retry is covered.

### Why does the key have to be 36 characters?

The default validator checks for the length of a UUID and nothing else, and the pinned version scopes nothing to a user, so the key alone retrieves a stored response. A random version 4 UUID is unguessable; the agent keeps the check and makes a wrong length a `400` instead of the default `500`.

### What about prefork?

With `-prod`, Fiber forks several processes and the in-memory storage and lock belong to each one, so a retry served by another process runs the handler again. The README explains it and points at the `Storage` option for a shared backend; the boilerplate's slice database has the same per-process limit, so the two are solved together.

### Are error responses stored?

No. A handler that returns an error stores nothing, so a client that retries after a `500` gets a fresh attempt with the same key. Successful responses are stored for `Lifetime`, including their headers unless `KeepResponseHeaders` narrows them.

### Does it slow down reads?

No. The default `Next` skips safe methods, so `GET /users` never touches the storage or the lock. Only requests with a non-safe method and a key pay for the lookup.

## More Fiber jobs

- [Add Input Validation to a Fiber API](https://getrush.ai/run/add-input-validation/fiber/)
- [Add JWT Authentication to a Fiber API](https://getrush.ai/run/add-jwt-authentication/fiber/)
- [Run a Fiber Docker Image as a Non-Root User](https://getrush.ai/run/add-non-root-user/fiber/)

## More jobs like this: Hand off a long task

- [Add ignoreDifferences to Argo CD Applications](https://getrush.ai/run/add-ignore-differences/argo-cd/)
- [Add Image Update Automation to a Flux Repository](https://getrush.ai/run/add-image-automation/flux/)
- [Sign Docker Images with Cosign in CI](https://getrush.ai/run/add-image-signing/docker/)

## 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/)
