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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Health endpoints must be reachable without auth or CSRF so external probes can hit them.
- 2Actively exercising each dependency proves real connectivity better than assuming it works.
- 3Mapping failures to a 503 lets load balancers and orchestrators route around a sick instance.
Related explainers
ruby
class Order class InvalidTransition < StandardError; end TRANSITIONS = {
A state machine for order transitions in Ruby
state-machine
data-driven
error-handling
Intermediate
8 steps
javascript
const express = require('express'); const router = express.Router(); const { pool } = require('../db'); const redis = require('../redis');
Building a health check endpoint in Express
health-check
timeouts
promise-race
Intermediate
9 steps
ruby
class CreateOrderItems < ActiveRecord::Migration[7.1] def change create_table :order_items do |t| t.references :order, null: false, foreign_key: { on_delete: :cascade }
Enforcing order-item integrity in Rails
migrations
foreign-keys
validations
Intermediate
7 steps
rust
use std::cmp::Ordering; use std::str::FromStr; #[derive(Debug, Clone, PartialEq, Eq)]
Parsing and ordering semantic versions in Rust
parsing
trait-implementation
ordering
Intermediate
8 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 steps
ruby
class Registration < ApplicationRecord belongs_to :event validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }
Validating registrations in Rails
validations
i18n
error-handling
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-health-check-endpoint-in-rails-explained-ruby-481e/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.