Agent Wranglers

ENG-9Required

Give the server a health check

Give the server two check addresses. Liveness says the process runs, and readiness says it can serve requests now.

How to do it

Add a liveness address such as /livez that answers 200 without touching any dependency. Restarts follow liveness, so a database blip never causes a restart loop. Add a readiness address such as /healthz that runs a cheap query against each critical dependency, such as the database. A service the app can work without, such as an email or analytics provider, never fails readiness. Give each check a short timeout, such as one second. Answer 200 when all critical dependencies work and 503 when one fails. Keep both fast, uncached and free of private data. The one-step deploy and load balancers poll readiness. Orchestrators restart on liveness only.

Examples

JavaScript example

app.get('/livez', (req, res) => res.set('Cache-Control', 'no-store').type('text').send('ok'));

app.get('/healthz', (req, res) => {
  res.set('Cache-Control', 'no-store');
  try {
    db.prepare('SELECT 1').get();
    res.type('text').send('ok');
  } catch {
    res.status(503).type('text').send('database unavailable');
  }
});

Python example

# Flask
@app.get("/livez")
def livez():
    return "ok", 200, {"Cache-Control": "no-store"}

@app.get("/healthz")
def healthz():
    headers = {"Cache-Control": "no-store"}
    try:
        db.execute("SELECT 1")
        return "ok", 200, headers
    except DatabaseError:
        return "database unavailable", 503, headers

Go example

http.HandleFunc("/livez", func(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Cache-Control", "no-store")
	w.Write([]byte("ok"))
})

http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Cache-Control", "no-store")
	ctx, cancel := context.WithTimeout(r.Context(), time.Second)
	defer cancel()
	if err := db.PingContext(ctx); err != nil {
		http.Error(w, "database unavailable", http.StatusServiceUnavailable)
		return
	}
	w.Write([]byte("ok"))
})

How to check

Stop the database on a test server. Readiness answers 503 within two seconds, liveness still answers 200, and the process is not restarted. Block an optional provider, and readiness still answers 200.

Sources

For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/engineering/build-test-and-deploy/health-check-and-rollback">Agent Wranglers engineering playbook</a>. In code you write, add a comment next to it with the same link.