Skip to content

feat: Add health endpoint basic structures and routes - #9588

Merged
Kump3r merged 11 commits into
concourse:masterfrom
Kump3r:health-endpoint-base
Jul 10, 2026
Merged

Kump3r merged 11 commits into
concourse:masterfrom
Kump3r:health-endpoint-base

Conversation

@Kump3r

@Kump3r Kump3r commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

Changes proposed by this PR

Initial work based on concourse/rfcs#141

  • atc/health.go - Health DTOs and constants
  • atc/health_test.go - Comprehensive unit tests
  • atc/routes.go - Modified with health route constants and mapping

Notes to reviewer

This is the very beginning of the /api/v1/health endpoint feature. The focus of this PR is to establish basic structure and data types. Actual logic will follow in separate PR's following the "Implementation plan" I created in the rfc PR. The focus on the review here that I desire is the design and validity of the data structures and JSON schema. Since I will follow-up with the actual health server in the next PR, I used stubs for now in places, where the handler was expected.

@Kump3r
Kump3r requested a review from a team May 27, 2026 09:50
@Kump3r

Kump3r commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor Author

PR Checklist: health-endpoint-base

Implementation

Health Server Package (atc/api/healthserver/)

  • server.go — Server struct with dbConn, workerFactory, minWorkerCount
  • health.go — GetHealth handler with DB + worker logic
  • DB health: SELECT pg_is_in_recovery() with 2s timeout — detects unreachable and read-only (standby)
  • Worker health: total==0 || running==0 → failing; running < minWorkerCount → degraded; running >= minWorkerCount → ok
  • HTTP 503 on failing, HTTP 200 on ok/degraded

DTOs (atc/health.go)

  • Health, DatabaseHealth, WorkerHealth structs with correct JSON tags
  • Overall status constants: ok, degraded, failing
  • Subsystem status constants: healthy, unhealthy

HTTP Wiring (atc/api/handler.go)

  • http.NotFound stub replaced with healthserver.GetHealth
  • dbConn and minWorkerCount added to NewHandler signature

Auth / Middleware

  • atc/wrappa/api_auth_wrappa.go — GetHealth confirmed in unauthenticated bucket (alongside GetInfo)
  • atc/wrappa/reject_archived_wrappa.go — GetHealth confirmed in non-pipeline passthrough case
  • atc/auditor/auditor.go — GetHealth confirmed under EnableSystemAuditLog (alongside GetInfo)

Configuration (atc/atccmd/command.go)

  • --health-min-worker-count CLI flag added (default 1, group Health Endpoint)
  • dbConn threaded through constructAPIHandler → NewHandler → healthserver.NewServer

Tests

  • atc/api/health_test.go — integration tests via the real HTTP test server
    • DB healthy + workers meet threshold → 200, status ok
    • Workers exactly at threshold → 200, status ok
    • No running workers (stalled registered) → 503, status failing
    • No workers at all → 503, status failing
    • DB unreachable → 503, status failing, error message present
    • DB read-only (standby replica) → 503, status failing, error contains "read-only"
    • Worker factory returns error → 503, status failing
    • Timestamp is recent
  • atc/health_test.go — DTO unit tests updated to match new struct shapes
  • atc/api/api_suite_test.go — fakeDbConn wired in
  • All 1046 existing API tests still pass

Still To Do

  • Add other componenets, besides workers and DB, like scheduler, runtime, GC etc.
  • Integration test scenario: custom minWorkerCount value (e.g. minWorkerCount=3, 2 running → degraded)
  • degraded path exercised in a test (requires test suite to support non-default minWorkerCount)
  • Manual testing instructions / curl examples in PR description
  • Packaging: documentation, bosh release, helm chart updates
  • go-concourse client library: go-concourse/concourse/health.go + client.go interface + tests

Open questions

Should we include the scheduler in the health check?

Right now the endpoint checks two things: can we talk to the database, and are there workers available. But there's a third signal we could add: is Concourse actually scheduling builds?

If the scheduler component has stopped running (e.g. it's stuck or stalled), the ATC looks healthy from the outside — database is up, workers are connected — but builds are silently not being picked up. An operator watching the health endpoint would have no idea.

We already track when the scheduler last ran in the database, so we could flag it as degraded if it hasn't run within a reasonable time window (e.g. more than 2× its configured interval). It would still return HTTP 200 so load balancers don't drop traffic, but the JSON would surface the problem.

The one concern worth discussing: every call to the health endpoint would do an extra database read to check scheduler state. Under aggressive probing (e.g. k8s checking every few seconds across many ATC instances) that adds load. We could mitigate it by caching the result for a few seconds.

Proposition

Component Health Reporting

After reviewing atc/component.go, there are 23 registered components across three groups:

  • Runtime (scheduler, tracker, scanner) — control whether builds start and run
  • Garbage Collection (reaper, collector_*, pipeline_pauser) — clean up containers, volumes, resource caches etc.
  • System (signing_key_lifecycler, being_watched_build_marker) — infrastructure maintenance

Decision

All components will be reported in the health response so operators have full visibility. However, only runtime component stalls affect the overall status.

Group Stale behaviour HTTP impact
Runtime (scheduler, tracker, scanner) Promotes overall status to degraded 200 with "status": "degraded"
GC + System Visible in JSON body No change to status or HTTP code

A component is considered stale if it hasn't run within staleMultiplier × interval (default multiplier: 2.0, configurable via --health-component-stale-multiplier). Paused components are excluded — pausing is an intentional operator action.

Rationale

A stale scheduler means builds silently stop being picked up — that is a meaningful degradation operators and load balancers should know about. A stale GC collector is a problem that accumulates over time but does not immediately break builds, so it should not cause noisy status changes for tooling that keys off the top-level status or HTTP code.

Example response (runtime component stale)

{
  "status": "degraded",
  "database": { "status": "healthy" },
  "workers": { "status": "healthy", "total": 3, "running": 3 },
  "components": [
    { "name": "scheduler", "healthy": false, "paused": false, "last_ran": "2026-06-08T10:00:00Z", "stale": true },
    { "name": "tracker",   "healthy": true,  "paused": false, "last_ran": "2026-06-08T10:05:00Z", "stale": false },
    { "name": "collector_volumes", "healthy": false, "paused": false, "last_ran": "2026-06-07T08:00:00Z", "stale": true }
  ]
}

Regarding this:

The one concern worth discussing: every call to the health endpoint would do an extra database read to check scheduler state. Under aggressive probing (e.g. k8s checking every few seconds across many ATC instances) that adds load. We could mitigate it by caching the result for a few seconds.

To my current design idea, I think we can use one single cheap query for all:

ComponentFactory.All() is a single SELECT id, name, interval, last_ran, paused FROM components - no joins, no subqueries, no aggregation. The components table has at most ~23 rows. It returns everything needed to compute staleness (last_ran, interval, paused) in one round trip.

So the full health check becomes exactly 3 queries total:

Query Purpose
SELECT pg_is_in_recovery() DB writability check
SELECT ... FROM workers Worker count + states
SELECT ... FROM components All 23 component states

All three are already used elsewhere on hot paths - no joins, no aggregation. The staleness calculation (time.Since(lastRan) > multiplier × interval) happens in Go after the fetch, not in SQL.
The only scenario worth watching is high-frequency probing (e.g. k8s liveness every 2s × 10 ATC replicas ≈ 15 queries/second against the same 3 tables). Still cheap in absolute terms, but we can add a short in-memory cache later if metrics show it adding up.

@taylorsilva

Copy link
Copy Markdown
Member

Just throwing my thoughts down as I'm skimming.

  • Reading your "Pr Checklist" comment
    • "is Concourse actually scheduling builds?" - There are existing metrics that operators can watch that would tell them this.
      • That said, I'm not against having the granular component health checks. I think they could be useful info for operators.
    • When is the "last ran" time updated for components? Do we update it even if the component failed?
      • Looks like it doesn't update "last ran" if the component failed, so your setup should work:
        if err := coordinator.Runnable.Run(ctx); err != nil {
        logger.Error("component-failed", err)
        return
        }
        if err := coordinator.Component.UpdateLastRan(); err != nil {
        logger.Error("failed-to-update-last-ran", err)
        return
        }
    • In the example response, components[*] each object has a healthy and stale field. The stale field feels redundant. Is there ever a time where healthy is true and stale is true?
    • All these tables are very small. I doubt we'd see performance issues stemming from any of these queries. Only one I'm not familiar with is pg_is_in_recovery(). Running a quick EXPLAIN ANALYZE I get 0.029ms on the database backing ci.concourse-ci.org.
      • Caching the results of these queries adds complexity and all the problems of figuring out when to invalidate the cache. I'd skip adding any caching for now and wait for real world feedback from users.

Haven't look at the code yet.

@Kump3r

Kump3r commented Jun 10, 2026

Copy link
Copy Markdown
Contributor Author
  • In the example response, components[*] each object has a healthy and stale field. The stale field feels redundant. Is there ever a time where healthy is true and stale is true?

Good catch. The original thinking was to keep status as a uniform field across all subsystems (database, workers, components) so clients only need one field to check health, while stale was meant to carry the reason - distinguishing "unhealthy because stale" from potential future failure modes like a component reporting its own error.

In practice that future hasn't arrived. Right now there is exactly one way a component becomes unhealthy: it goes stale. So stale: true and status: "unhealthy" are always identical, and stale adds noise without information. last_ran is already in the response so any client that wants to reason about staleness can do so themselves.

Dropping stale, keeping status with healthy/unhealthy. If we add a second failure mode later we can introduce a reason field at that point.

Also thanks for confirming the other implementation details and decisions so far!

@Kump3r

Kump3r commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor Author

Manual Testing

Connect to the database:

docker compose exec db psql -U dev concourse 

Trigger overall degraded (runtime component stale)

UPDATE components SET last_ran = NOW() - INTERVAL '5 minutes' WHERE name = 'scheduler';

The scheduler is a runtime dependency — a stale scheduler promotes the top-level status to "degraded".

Trigger component-level unhealthy without affecting overall status (GC component stale)

UPDATE components SET last_ran = NOW() - INTERVAL '5 minutes' WHERE name = 'collector_volumes';

The collector stalling is surfaced in the components array ("status": "unhealthy") but the top-level status stays "ok" — GC stalls don't break builds immediately.

Trigger overall failing (no running workers)

docker compose stop worker

Reset

UPDATE components SET last_ran = NOW() WHERE name IN ('scheduler', 'collector_volumes');
docker compose start worker

Check the endpoint

curl -s http://localhost:8080/api/v1/health | jq .

Expected shape:

{
  "status": "ok | degraded | failing",
  "timestamp": "...",
  "database": { "status": "healthy | unhealthy", "error": "..." },
  "workers":  { "status": "healthy | degraded | unhealthy", "total": 1, "running": 1 },
  "components": [
    { "name": "scheduler", "status": "healthy | unhealthy", "paused": false, "last_ran": "..." },
    ...
  ]
}

@Kump3r
Kump3r force-pushed the health-endpoint-base branch from f1ce8e1 to 35ec721 Compare June 13, 2026 09:38
@Kump3r

Kump3r commented Jun 13, 2026

Copy link
Copy Markdown
Contributor Author

Okay the overall idea got its shape, what is left to be done from my POV is:

  • - Packaging: documentation, bosh release, helm chart updates
  • - go-concourse client library: go-concourse/concourse/health.go + client.go interface + tests

Both of which I prefer to do after the review, as it doesn't make sense to invest time if stuff needs to be reworked based on that.

@taylorsilva taylorsilva moved this from Todo to In Progress in Pull Requests Jun 18, 2026
@taylorsilva

Copy link
Copy Markdown
Member

I will review this! Keep getting pulled off on side quests as you can probably tell 😅 I'll stop putting it off and review over the next few days.

@taylorsilva taylorsilva left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed most of this. Looking good so far! Let me know your thoughts on the things I called out (WDYT).

Comment thread atc/atccmd/command.go Resolved
Comment thread atc/health.go Resolved
Comment thread atc/health.go Resolved
Comment thread atc/api/healthserver/health.go Resolved
Comment thread atc/api/healthserver/health.go Resolved
Comment thread atc/api/healthserver/health.go Resolved
Comment thread atc/api/api_suite_test.go Resolved
@taylorsilva taylorsilva moved this from In Progress to Waiting on Contributor in Pull Requests Jun 30, 2026
@taylorsilva

Copy link
Copy Markdown
Member

Read your replies and replied where necessary. Feel free to ping me when you've pushed changes to this again. No rush! :)

@Kump3r
Kump3r requested a review from taylorsilva July 2, 2026 10:38
@Kump3r

Kump3r commented Jul 2, 2026

Copy link
Copy Markdown
Contributor Author

Added a note to each section with my 2 cents, I more or less tried addressing everything, leaving the test suit refactor as a hanging. Think it is a bit out of scope here and am not sure how to make it any better sadly. Sorry for that, if you have any concrete suggestions I will dive deeper into that, based on my current understanding and knowledge, I would have to refactor a lot of tests just to make this work and not sure whether that brings any value, besides code clarity :/

@Kump3r Kump3r added the rfc label Jul 9, 2026
@taylorsilva taylorsilva moved this from Waiting on Contributor to In Progress in Pull Requests Jul 9, 2026

@taylorsilva taylorsilva left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've reviewed the latest changes and they LGTM.

I pushed a commit resolving our issue with how the test setup worked. I used the options pattern to make it easier for us to introduce similar test changes in the future. Now all the setup code is consolidated into one set of functions instead of having duplicate funcs.

If someone wants to configure something in the api.NewHandler(), they just add fields to the apiServerConfig struct and new apiConfigOpt func for the new fields.

I added a few fields as examples. Didn't include apiConfigOpt funcs for them since we don't need to change them from the default. Also helped make those values more descriptive when reading the code.

@Kump3r
Kump3r merged commit 3c3fc8d into concourse:master Jul 10, 2026
11 checks passed
@github-project-automation github-project-automation Bot moved this from In Progress to Done in Pull Requests Jul 10, 2026
@Kump3r

Kump3r commented Jul 10, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @taylorsilva for the support in RFC and in reviewing. I will address the follow-up packaging (helm/bosh/fly/client lib) in separate PR's.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Archived in project

Development

Successfully merging this pull request may close these issues.

2 participants