Skip to Content
Course content

229: Health Check Endpoints in Rails

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I once worked on a project where we had a "healthy" dashboard showing green lights across the board, while our users were seeing 500 errors on every single page. The culprit? A health check endpoint that was lying to us.

# app/controllers/health_controller.rb
class HealthController < ApplicationController
  def show
    render json: { status: 'ok' }, status: :ok
  end
end

The Danger of the Lying Health Check

At first glance, this looks fine. If the server is running and the Rails router can hit this action, it returns a 200 OK. But here is the problem: this endpoint only tells the load balancer that the Ruby process is alive. It doesn't tell us if the application is actually functional.

In that project, our database connection had hung. The Rails process was technically "up," so the load balancer kept sending traffic to a broken instance. The health check was essentially saying, "I'm awake!" while the app was screaming, "I can't find the database!"

Verifying the Infrastructure

A real health check needs to verify the critical dependencies your app needs to survive. For most Rails apps, that means the database. If your app can't talk to Postgres or MySQL, it's not healthy; it's a zombie.

Here is how we fix that. We want to actually attempt a lightweight query or check the connection status before we tell the load balancer everything is fine:

# app/controllers/health_controller.rb
class HealthController < ApplicationController
  # Skip authentication/logging for health checks to avoid bloating logs
  skip_before_action :authenticate_user! 

  def show
    # Attempt to execute a simple query to verify the DB connection
    ActiveRecord::Base.connection.execute('SELECT 1')
    
    render json: { status: 'online', timestamp: Time.current }, status: :ok
  rescue StandardError => e
    # Log the actual error so we know WHY it's failing
    Rails.logger.error "Health check failed: #{e.message}"
    
    # Return a 503 Service Unavailable so the load balancer pulls this instance
    render json: { status: 'unhealthy', error: e.message }, status: :service_unavailable
  end
end

By calling ActiveRecord::Base.connection.execute('SELECT 1'), we force Rails to actually communicate with the database. If the connection is dead, it throws an exception, we catch it, and we return a 503 Service Unavailable. This tells the infrastructure (like Kubernetes or AWS) to stop sending traffic to this specific pod or instance and restart it.

Leveraging Rails 7.1+ Defaults

If you're on a modern version of Rails (7.1 or newer), you might have noticed a /up endpoint already exists in your routes.rb. This was added specifically because this pattern is so universal.

# config/routes.rb
Rails.application.routes.draw do
  get "up" => "rails/health#show", as: :rails_health_check
end

The built-in Rails::HealthController does exactly what I showed you above—it checks the database connection by default. I usually stick with the built-in one unless I have complex dependencies. If your app relies heavily on Redis or an external API to function, you'll still want to write your own custom health check that pings those services too. Just remember: be careful not to make your health check too heavy. If your health check takes 2 seconds to run, you're just adding overhead to your infrastructure's monitoring loop.




📋 Practical Task

Implementing a Multi-Service Health Check for a Redis-Backed App

Imagine your Rails application relies on both a PostgreSQL database and a Redis cache. If either one goes down, the app is considered "unhealthy."

Your Task: Modify the HealthController to verify both dependencies. The endpoint should return a 200 OK only if both the database is reachable and Redis is responding. If either fails, it should return a 503 Service Unavailable.

Requirements:

  • Use ActiveRecord::Base.connection.execute('SELECT 1') for the database check.
  • Use Redis.current.ping (or your app's specific Redis connection object) to verify Redis.
  • Ensure the response body is JSON and explicitly states which service failed in the event of an error.
  • Ensure the HTTP status code is correctly set to :service_unavailable on failure.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.