ruby
require "timeout"

module HealthCheck
  class Probe
    Result = Struct.new(:name, :status, :latency_ms, :critical, :error, keyword_init: true) do
      def healthy?

Health Check Endpoint with Dependency Probes

rails reliability health-check
by codesnips 3 tabs
sql
CREATE TABLE daily_events (
    id          BIGSERIAL PRIMARY KEY,
    category    TEXT        NOT NULL,
    item_id     BIGINT      NOT NULL,
    score       NUMERIC(10,2) NOT NULL DEFAULT 0,
    occurred_at TIMESTAMPTZ NOT NULL DEFAULT now()

Database-Driven “Daily Top” with window functions

postgres sql analytics
by codesnips 3 tabs
ruby
class CreateTags < ActiveRecord::Migration[7.0]
  def change
    create_table :tags do |t|
      t.string :name, null: false
      t.integer :taggings_count, null: false, default: 0
      t.timestamps

Normalize Tags at Write Time

rails activerecord callbacks
by codesnips 3 tabs
ruby
class Article < ApplicationRecord
  scope :ranked, -> { order(score: :desc, id: :desc) }

  scope :after_cursor, ->(cursor) do
    return all if cursor.nil?

Deterministic Sorting with Secondary Key

rails activerecord pagination
by codesnips 4 tabs
ruby
class AddSoftDeleteToDocuments < ActiveRecord::Migration[7.0]
  disable_ddl_transaction!

  def change
    add_column :documents, :marked_for_deletion_at, :datetime, null: true

Safer Time-Based Deletes with “mark then sweep”

rails reliability activerecord
by codesnips 4 tabs
sql
-- Product.active.touch_all(:cache_synced_at) for catalog 42
UPDATE "products"
SET "updated_at" = '2024-05-01 12:00:00.123456',
    "cache_synced_at" = '2024-05-01 12:00:00.123456'
WHERE "products"."catalog_id" = 42
  AND "products"."status" = 'active';

Use `touch_all` for Efficient “Bump Updated At”

rails activerecord performance
by codesnips 4 tabs
ruby
class ExplainAnalyzer
  def initialize(relation, watched_tables:)
    @relation = relation
    @watched_tables = Array(watched_tables).map(&:to_s)
  end

Fast Fail for Missing Indexes (EXPLAIN sanity check)

rails postgres performance
by codesnips 3 tabs
ruby
class CreateTopSellersMv < ActiveRecord::Migration[7.0]
  def up
    execute <<~SQL
      CREATE MATERIALIZED VIEW top_sellers AS
        SELECT p.id            AS product_id,
               p.name          AS product_name,

Cache-Friendly “Top N” with Materialized View Refresh

rails postgres performance
by codesnips 4 tabs
ruby
class ApplicationError < StandardError
  attr_reader :context

  class << self
    def context_keys(*keys)
      @context_keys = keys unless keys.empty?

Structured Exceptions with Context

rails observability exceptions
by codesnips 3 tabs
ruby
class ShardedCounter
  SHARDS = 16
  SNAPSHOT_TTL = 10 # seconds

  def initialize(name, redis: REDIS)
    @name = name

Lock-Free Read Pattern for Hot Counters (Approximate)

rails redis performance
by codesnips 3 tabs
ruby
class Order < ApplicationRecord
  has_many :line_items, dependent: :destroy, inverse_of: :order

  accepts_nested_attributes_for :line_items,
    reject_if: :all_blank,
    allow_destroy: true

Transactionally Create Parent + Children with accepts_nested_attributes_for

rails activerecord nested-attributes
by codesnips 3 tabs
ruby
class OverdueInvoicesQuery
  def initialize(relation: Invoice.all, as_of: Time.current)
    @relation = relation
    @as_of = as_of
  end

ActiveRecord::Relation as a Boundary (No Arrays)

rails activerecord query-objects
by codesnips 3 tabs