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
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 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.