Implement Health and Readiness Checks

Production platforms need endpoints to determine whether the application is running and whether it can serve requests.

A liveness endpoint checks whether the application process is responsive.

A readiness endpoint checks whether required dependencies are available.

For our application, MongoDB is a critical dependency.

We can inspect the Mongoose connection state to determine whether the database is connected.

Health and Readiness Endpoints
import mongoose from 'mongoose';

app.get('/health/live', (req, res) => {
  res.status(200).json({
    status: 'alive'
  });
});

app.get('/health/ready', (req, res) => {
  const databaseReady = mongoose.connection.readyState === 1;

  if (!databaseReady) {
    return res.status(503).json({
      status: 'not-ready',
      database: 'disconnected'
    });
  }

  res.status(200).json({
    status: 'ready',
    database: 'connected'
  });
});

Provides a liveness endpoint and a readiness endpoint that checks the MongoDB connection state.

Key Takeaways
  • Liveness checks indicate whether the application process is running.

  • Readiness checks indicate whether the application can serve traffic.

  • Check critical dependencies before reporting readiness.