ruby 36 lines · 7 steps

Building a health check endpoint in Rails

A controller that probes the database and cache, then returns an HTTP status that load balancers can act on.

Explained by highlit
1class HealthController < ApplicationController
2 skip_before_action :authenticate_user!, raise: false
3 skip_forgery_protection
4 
5 def show
6 checks = {
7 database: database_healthy?,
8 cache: cache_healthy?
9 }
10 
11 if checks.values.all?
12 render json: { status: "ok", checks: checks }, status: :ok
13 else
14 render json: { status: "error", checks: checks }, status: :service_unavailable
15 end
16 end
17 
18 private
19 
20 def database_healthy?
21 ActiveRecord::Base.connection.execute("SELECT 1")
22 true
23 rescue StandardError => e
24 Rails.logger.error("Health check DB failure: #{e.message}")
25 false
26 end
27 
28 def cache_healthy?
29 token = SecureRandom.hex(8)
30 Rails.cache.write("health_check", token, expires_in: 10.seconds)
31 Rails.cache.read("health_check") == token
32 rescue StandardError => e
33 Rails.logger.error("Health check cache failure: #{e.message}")
34 false
35 end
36end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Health endpoints must be reachable without auth or CSRF so external probes can hit them.
  2. 2Actively exercising each dependency proves real connectivity better than assuming it works.
  3. 3Mapping failures to a 503 lets load balancers and orchestrators route around a sick instance.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a health check endpoint in Rails — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code