All jobs

Add Prometheus Metrics to a Vapor App

Yes. An agent wires swift-prometheus into a Vapor app, exposes GET /metrics with Vapor's own request counters and timers, tests it with VaporTesting and opens a PR.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

The agent reads how the app boots before it changes it. A Vapor app generated from vapor/template with vapor new has Package.swift on swift-tools 6.3 depending on vapor from 4.121.4, swift-nio from 2.101.0 and, when chosen, fluent 4.13.0 with a database driver and leaf 4.5.1, and a test target that depends on the VaporTesting product. Sources/App/entrypoint.swift detects the environment, calls LoggingSystem.bootstrap(from: &env), makes the Application and runs configure(app) from configure.swift, which registers the database, the CreateTodo migration and the routes. routes.swift defines GET / and GET /hello, and Controllers/TodoController.swift mounts GET, POST and DELETE under /todos. Tests/AppTests/AppTests.swift uses Swift Testing with a withApp helper that makes an Application(.testing), runs configure, autoMigrate, the test and autoRevert, and drives routes with app.testing().test(.GET, "hello"). There is no metrics dependency, so Vapor's built-in swift-metrics calls fall into the no-op factory.

The change is small because Vapor already emits the metrics. The agent adds swift-prometheus to Package.swift as a dependency and the Prometheus product to the app target, and in entrypoint.swift, right after the logging bootstrap, creates a PrometheusCollectorRegistry, wraps it in a PrometheusMetricsFactory and calls MetricsSystem.bootstrap with it once, keeping the registry where configure.swift can reach it through an Application.storage key. From that point Vapor's responder records http_requests_total, http_request_errors_total and http_request_duration_seconds for every route with method, path and status dimensions, with no change to routes.swift or the controller. The agent adds a GET /metrics route in routes.swift whose handler calls registry.emit(into:) on a byte buffer and returns it as text/plain; version=0.0.4, the exposition format Prometheus scrapes, and leaves the /hello and /todos routes as they are.

The test goes into AppTests.swift in the file's own style. Because MetricsSystem.bootstrap may run only once per process and the test suite calls configure for every test, the agent bootstraps the factory in the test with MetricsSystem.bootstrapInternal, which swift-metrics provides for exactly this, then issues GET /hello followed by GET /metrics and uses #expect to check a 200, the text/plain content type and a body containing http_requests_total with path="/hello" and status="200". It runs swift build and swift test, which for a Fluent project need the database the withApp helper migrates: with SQLite that is a file, and with PostgreSQL or MySQL the agent starts the server the repository's docker-compose.yml describes and sets DATABASE_HOST the way test-template.yml does in CI. The template's upcoming-feature flags (ExistentialAny, InternalImportsByDefault, MemberImportVisibility and the others in swiftSettings) apply to the new code, so the imports are explicit and existentials are spelled with any.

Then it checks the endpoint from outside the process: swift run with serve --hostname 0.0.0.0 --port 8080 as the Dockerfile's CMD does, a few curl requests to /hello and /todos, and curl http://localhost:8080/metrics to show the counters incremented and the duration histogram buckets. It also builds the Docker image once with the repository's two-stage Dockerfile to confirm the new dependency resolves in the swift:6.3-noble build stage and nothing is needed in the ubuntu:noble runtime stage. The /metrics route is left unauthenticated, as scrapers expect, and the pull request says where to put a middleware or a network rule if the app is public.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "Add Prometheus metrics to this Vapor app and open a pull request. Read Package.swift, Sources/App/entrypoint.swift, Sources/App/configure.swift, Sources/App/routes.swift, Sources/App/Controllers/TodoController.swift, Tests/AppTests/AppTests.swift, Dockerfile and docker-compose.yml first. Add swift-prometheus to Package.swift and the Prometheus product to the App target. In entrypoint.swift, after LoggingSystem.bootstrap, create a PrometheusCollectorRegistry, bootstrap MetricsSystem once with a PrometheusMetricsFactory over it, and store the registry on app.storage behind a StorageKey so configure.swift can reach it. Add GET /metrics in routes.swift that emits the registry into a buffer and answers text/plain; version=0.0.4. Do not change the existing routes or the controller. Add a test to AppTests.swift that bootstraps the factory with MetricsSystem.bootstrapInternal, calls GET /hello then GET /metrics and expects a 200 with http_requests_total for path /hello and status 200 in the body. Run swift build and swift test, run the server and show curl output for /hello and /metrics, and build the Docker image. Put the test output and the curl exchanges in the pull request description.",
  "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 Package.swift, Package.resolved, Sources/App/entrypoint.swift, Sources/App/routes.swift (the /metrics route) and Tests/AppTests/AppTests.swift, with a small StorageKey type in configure.swift or a file beside it. The description shows the swift test summary from the sandbox, the curl exchange with the first lines of the exposition text, including http_requests_total and the http_request_duration_seconds buckets, and the final line of the Docker build. The session keeps the whole build log, and GET /o/{org}/p/{project}/sessions/{id}/changes returns the diff per file.

A reviewer checks that MetricsSystem.bootstrap is called once and before the application is made, that the route returns the version=0.0.4 content type a scraper needs, and whether /metrics should be reachable from the internet in their deployment. On a repository that runs swift test in CI, the pull request's check runs the new test with the rest of the suite.

Run it on every new Vapor service

Every service a team generates from the template starts without metrics, so start one run per new repository: a handler on your server that receives GitHub's repository webhook, or a script that reads GET /o/{org}/github for the installation's repositories, calls POST /o/{org}/sessions with this body and the repository URL in resources, with a request_id per repository so a retry returns the run already started.

Give the key a webhook_url and Rush POSTs run.completed, run.failed or run.cancelled when each turn ends, signed per Standard Webhooks, with data.session_url to read for the pull request. A key runs at most max_concurrent sessions at once, 4 by default, and a batch across many Vapor services needs no pacing: requests past that number are answered 202 with status: "queued" and their runs start as the key's slots free.

The use case this job follows, with its automation and trigger: Hand off a long task.

Why run it on Rush?

The work here is mostly in getting the order right: a metrics factory that must be bootstrapped exactly once, a test suite that configures the app many times, and a Swift toolchain, a database and a Docker build that all have to agree. The agent does that in its own sandbox with Swift 6.3 and the database from the repository's Compose file, and the swift test run, the curl output and the image build are on the session rather than in a sentence.

What arrives is a pull request with a passing test and a scrape-ready endpoint, the same body working on every Vapor service a team owns, each in its own sandbox. The sandbox parks with the resolved packages and the .build directory in place when the turn ends, so adding a custom counter to TodoController or a histogram with different buckets is a follow-up on the same session, without another cold Swift build.

Frequently asked questions

Do I have to instrument each route by hand?

No. Vapor's default responder already records a request counter, an error counter and a duration timer through swift-metrics for every route, with method, path and status as dimensions. Bootstrapping the Prometheus factory is what makes those numbers appear; the only new route is /metrics itself.

Why bootstrap in entrypoint.swift rather than in configure.swift?

Because MetricsSystem.bootstrap may be called once per process and configure runs once per test in AppTests.swift. Bootstrapping in entrypoint.swift keeps production simple, and the test uses MetricsSystem.bootstrapInternal, which swift-metrics exposes so tests can replace the factory.

Will /metrics be public?

It answers any request, like the other routes, because a scraper has to reach it. The pull request points at where a Middleware on that route group or a network rule in your deployment would restrict it, and leaves that choice to you since it depends on where Prometheus runs.

Does it work without Fluent or Leaf?

Yes. Nothing in the change touches the database or templates; the only difference is that swift test for a project without Fluent needs no database, which the template's withApp(configure:) helper already handles.

More Vapor jobs

The same job on other stacks

Keep reading