Skip to content

Liveness and Readiness Answer Different Questions

The Course
•
18 min study

The decision

A live process may still be unable to serve traffic because its database is unavailable or its schema is incompatible. Keep a cheap liveness check separate from a readiness decision.

Read, predict, run

The model returns 200 only when required dependencies are ready. The capstone’s health route calls a small repository probe, not an expensive report query. Readiness must not reveal credentials or private records:

JavaScript
export function run({ databaseReady, schemaReady }) {
  return databaseReady && schemaReady ? 200 : 503;
}

Before pressing Run, predict what run returns for {"databaseReady": true, "schemaReady": false} and {"databaseReady": true, "schemaReady": true}, from the code above. Write your answers down first: after Run, the case table shows the expected values beside the actual ones.

Liveness and Readiness Answer Different Questions Next.js · 10 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Review Queue · Practice lab</strong> </header> {children} </body> </html> ); } import ApiProbe from "./ApiProbe.jsx"; import Cases from "./Cases.jsx"; export default function Page() { return ( <main> <h1>Liveness and Readiness Answer Different Questions</h1> <p> Two probe routes: app/api/live/route.js and app/api/ready/route.js, which calls run from lib/contract.js. </p> <ApiProbe /> <Cases /> </main> ); } "use client"; import { useState } from "react"; export default function ApiProbe() { const [results, setResults] = useState({}); async function ask(path) { const response = await fetch(path); const text = `${response.status} ${await response.text()}`; setResults((r) => ({ ...r, [path]: text })); } async function outage(down) { await fetch("/api/outage", { method: "POST", body: JSON.stringify({ down }) }); setResults({}); } return ( <section> <p> <button onClick={() => ask("/api/live")}>Ask /api/live</button>{" "} <button onClick={() => ask("/api/ready")}>Ask /api/ready</button> </p> <p> <button onClick={() => outage(true)}>Take the database down</button>{" "} <button onClick={() => outage(false)}>Bring it back</button> </p> <ul aria-label="Probe answers"> {Object.entries(results).map(([path, text]) => ( <li key={path}> {path}: {text} </li> ))} </ul> </section> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } // Liveness: is this process able to answer at all? It checks no dependency, // so a database outage doesn't make the orchestrator restart every instance. export async function GET() { return Response.json({ live: true }, { headers: { "Cache-Control": "no-store" } }); } import { setDatabaseUp } from "@/lib/dependencies.js"; export async function POST(request) { const { down } = await request.json(); setDatabaseUp(!down); return new Response(null, { status: 204 }); } import { run } from "@/lib/contract.js"; import { EXPECTED_SCHEMA, probeDatabase, schemaVersion } from "@/lib/dependencies.js"; // Readiness: may the load balancer send this instance traffic right now? export async function GET() { const databaseReady = await probeDatabase(); const schemaReady = databaseReady && (await schemaVersion()) === EXPECTED_SCHEMA; const result = run({ databaseReady, schemaReady }); // The starter's run returns a status; the exercise returns { status, body }. const status = typeof result === "number" ? result : result.status; const body = typeof result === "number" ? null : result.body; return Response.json(body, { status, headers: { "Cache-Control": "no-store" } }); } export function run({ databaseReady, schemaReady }) { return databaseReady && schemaReady ? 200 : 503; } export const examples = [ [{ databaseReady: true, schemaReady: false }, 503], [{ databaseReady: true, schemaReady: true }, 200], ]; // What this instance can see. The database can be switched off from the page // to simulate an outage. const EXPECTED_SCHEMA = 2; let databaseUp = true; export function setDatabaseUp(up) { databaseUp = up; } export async function probeDatabase() { // A real probe runs "SELECT 1" with a short timeout. return databaseUp; } export async function schemaVersion() { if (!databaseUp) throw new Error("connection refused"); return 2; } export { EXPECTED_SCHEMA };
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Check your prediction
  • Input {"databaseReady": true, "schemaReady": false} → 503.
  • Input {"databaseReady": true, "schemaReady": true} → 200.

The case table computes these results on the server side of the simulation. It compares values; it does not prove a production deployment or database works.

The failure to avoid

Returning 200 because the HTTP handler itself ran makes the probe meaningless. Conversely, making liveness depend on every optional service can cause unnecessary restart loops.

Compare a readiness handler that answers 200 because it ran with one that asks the database. During a database outage the first keeps sending traffic to an instance that fails every request; the second answers 503, and the load balancer routes around it. If liveness also checked the database, the same outage would restart every instance, which can't help.

Two probes, one outage

The lab has both probes as route handlers. app/api/live/route.js checks nothing and answers 200 while the process can answer at all. app/api/ready/route.js asks the dependencies and passes what it learns to run:

JavaScript
const databaseReady = await probeDatabase();
const schemaReady = databaseReady && (await schemaVersion()) === EXPECTED_SCHEMA;
const result = run({ databaseReady, schemaReady });

Ask both, press Take the database down, and ask both again. Predict the four answers first.

Liveness and readiness during an outage Next.js · 10 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Review Queue · Practice lab</strong> </header> {children} </body> </html> ); } import ApiProbe from "./ApiProbe.jsx"; import Cases from "./Cases.jsx"; export default function Page() { return ( <main> <h1>Liveness and Readiness Answer Different Questions</h1> <p> Two probe routes: app/api/live/route.js and app/api/ready/route.js, which calls run from lib/contract.js. </p> <ApiProbe /> <Cases /> </main> ); } "use client"; import { useState } from "react"; export default function ApiProbe() { const [results, setResults] = useState({}); async function ask(path) { const response = await fetch(path); const text = `${response.status} ${await response.text()}`; setResults((r) => ({ ...r, [path]: text })); } async function outage(down) { await fetch("/api/outage", { method: "POST", body: JSON.stringify({ down }) }); setResults({}); } return ( <section> <p> <button onClick={() => ask("/api/live")}>Ask /api/live</button>{" "} <button onClick={() => ask("/api/ready")}>Ask /api/ready</button> </p> <p> <button onClick={() => outage(true)}>Take the database down</button>{" "} <button onClick={() => outage(false)}>Bring it back</button> </p> <ul aria-label="Probe answers"> {Object.entries(results).map(([path, text]) => ( <li key={path}> {path}: {text} </li> ))} </ul> </section> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } // Liveness: is this process able to answer at all? It checks no dependency, // so a database outage doesn't make the orchestrator restart every instance. export async function GET() { return Response.json({ live: true }, { headers: { "Cache-Control": "no-store" } }); } import { setDatabaseUp } from "@/lib/dependencies.js"; export async function POST(request) { const { down } = await request.json(); setDatabaseUp(!down); return new Response(null, { status: 204 }); } import { run } from "@/lib/contract.js"; import { EXPECTED_SCHEMA, probeDatabase, schemaVersion } from "@/lib/dependencies.js"; // Readiness: may the load balancer send this instance traffic right now? export async function GET() { const databaseReady = await probeDatabase(); const schemaReady = databaseReady && (await schemaVersion()) === EXPECTED_SCHEMA; const result = run({ databaseReady, schemaReady }); // The starter's run returns a status; the exercise returns { status, body }. const status = typeof result === "number" ? result : result.status; const body = typeof result === "number" ? null : result.body; return Response.json(body, { status, headers: { "Cache-Control": "no-store" } }); } export function run({ databaseReady, schemaReady }) { return databaseReady && schemaReady ? 200 : 503; } export const examples = [ [{ databaseReady: true, schemaReady: false }, 503], [{ databaseReady: true, schemaReady: true }, 200], ]; // What this instance can see. The database can be switched off from the page // to simulate an outage. const EXPECTED_SCHEMA = 2; let databaseUp = true; export function setDatabaseUp(up) { databaseUp = up; } export async function probeDatabase() { // A real probe runs "SELECT 1" with a short timeout. return databaseUp; } export async function schemaVersion() { if (!databaseUp) throw new Error("connection refused"); return 2; } export { EXPECTED_SCHEMA };
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Check your prediction
Text
/api/live: 200 {"live":true}
/api/ready: 200 null

and after the outage:

Text
/api/live: 200 {"live":true}
/api/ready: 503 null

The load balancer stops sending traffic to this instance, and the orchestrator leaves it running, ready for the database to come back. The null is because run returns only a status, so the handler has nothing to send as the body; a person debugging can't tell "not ready" from a broken handler. The exercise fixes that.

Exercise

Extend the contract

Return a body with ready: true or false alongside status. Do not return internal dependency error messages.

Edit lib/contract.js, then rerun the original cases. If the requested rule changes an earlier result, update that expected value deliberately. Keep the other cases. Add the acceptance cases to examples so the preview checks them too.

  • Input {"databaseReady": false, "schemaReady": true} must return {"status": 503, "body": {"ready": false}}.
Your working space Next.js · 10 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Review Queue · Practice lab</strong> </header> {children} </body> </html> ); } import ApiProbe from "./ApiProbe.jsx"; import Cases from "./Cases.jsx"; export default function Page() { return ( <main> <h1>Liveness and Readiness Answer Different Questions</h1> <p> Two probe routes: app/api/live/route.js and app/api/ready/route.js, which calls run from lib/contract.js. </p> <ApiProbe /> <Cases /> </main> ); } "use client"; import { useState } from "react"; export default function ApiProbe() { const [results, setResults] = useState({}); async function ask(path) { const response = await fetch(path); const text = `${response.status} ${await response.text()}`; setResults((r) => ({ ...r, [path]: text })); } async function outage(down) { await fetch("/api/outage", { method: "POST", body: JSON.stringify({ down }) }); setResults({}); } return ( <section> <p> <button onClick={() => ask("/api/live")}>Ask /api/live</button>{" "} <button onClick={() => ask("/api/ready")}>Ask /api/ready</button> </p> <p> <button onClick={() => outage(true)}>Take the database down</button>{" "} <button onClick={() => outage(false)}>Bring it back</button> </p> <ul aria-label="Probe answers"> {Object.entries(results).map(([path, text]) => ( <li key={path}> {path}: {text} </li> ))} </ul> </section> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } // Liveness: is this process able to answer at all? It checks no dependency, // so a database outage doesn't make the orchestrator restart every instance. export async function GET() { return Response.json({ live: true }, { headers: { "Cache-Control": "no-store" } }); } import { setDatabaseUp } from "@/lib/dependencies.js"; export async function POST(request) { const { down } = await request.json(); setDatabaseUp(!down); return new Response(null, { status: 204 }); } import { run } from "@/lib/contract.js"; import { EXPECTED_SCHEMA, probeDatabase, schemaVersion } from "@/lib/dependencies.js"; // Readiness: may the load balancer send this instance traffic right now? export async function GET() { const databaseReady = await probeDatabase(); const schemaReady = databaseReady && (await schemaVersion()) === EXPECTED_SCHEMA; const result = run({ databaseReady, schemaReady }); // The starter's run returns a status; the exercise returns { status, body }. const status = typeof result === "number" ? result : result.status; const body = typeof result === "number" ? null : result.body; return Response.json(body, { status, headers: { "Cache-Control": "no-store" } }); } export function run({ databaseReady, schemaReady }) { return databaseReady && schemaReady ? 200 : 503; } export const examples = [ [{ databaseReady: true, schemaReady: false }, 503], [{ databaseReady: true, schemaReady: true }, 200], ]; // What this instance can see. The database can be switched off from the page // to simulate an outage. const EXPECTED_SCHEMA = 2; let databaseUp = true; export function setDatabaseUp(up) { databaseUp = up; } export async function probeDatabase() { // A real probe runs "SELECT 1" with a short timeout. return databaseUp; } export async function schemaVersion() { if (!databaseUp) throw new Error("connection refused"); return 2; } export { EXPECTED_SCHEMA };
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Hint 1: the idea

The body must say the same thing as the status, so both come from one decision. It should say no more than a load balancer needs.

Hint 2: a first step

Derive the public boolean from the same decision as the status.

Show one solution

Replace the exported run function and any constants shown here; keep the examples export underneath it. Compare the result with your own approach.

JavaScript
export function run({ databaseReady, schemaReady }) {
  const ready = Boolean(databaseReady && schemaReady);
  return { status: ready ? 200 : 503, body: { ready } };
}

ready is computed once and used for both the status and the body, so they can't disagree; Boolean(...) makes it a strict boolean even if a flag is missing. Leaving out which dependency failed keeps the internal layout private; the server log is the place for that detail.

Explain it without the code

Write what liveness and readiness should each answer while the database is down, and what each answer causes.

Going further

Read the Next.js guide for the framework boundary around this rule. The preview runs code-playpad's Next.js simulation. Real caching, hydration, authentication and persistence require the real-server checks described on Day 7.

Was this article helpful?

Your response is saved on this device.