ruby
require "sidekiq/api"

class QueueDepthGuard
  class QueueSaturated < StandardError
    attr_reader :queue, :depth

Background Job Backpressure with Queue Depth Guard

rails reliability sidekiq
by codesnips 3 tabs
ruby
class Problem
  DEFAULT_TYPE = "https://api.example.com/problems/about:blank".freeze

  attr_reader :type, :title, :status, :detail, :instance, :extensions

  def initialize(status:, title:, detail: nil, type: nil, instance: nil, extensions: {})

API Error Handling with Problem Details (RFC7807-ish)

rails api error-handling
by codesnips 3 tabs
ruby
class LastSeenTracker
  THROTTLE = 5.minutes
  PENDING_KEY = "pending:last_seen".freeze

  class << self
    def touch(user_id, at: Time.current)

Database “Last Seen” without Hot Row Updates

rails performance redis
by codesnips 3 tabs
ruby
class CreateAuditLogs < ActiveRecord::Migration[7.1]
  def change
    create_table :audit_logs do |t|
      t.references :auditable, polymorphic: true, null: false
      t.string :actor
      t.string :action, null: false

Audit Trail with JSON Diff (Minimal, Useful)

rails activerecord auditing
by codesnips 4 tabs
ruby
class FeatureFlag < ApplicationRecord
  validates :key, presence: true, uniqueness: true
  validates :percentage, inclusion: { in: 0..100 }

  after_commit :expire_cache

Safer Feature Flagging: Cache + DB Fallback

rails caching reliability
by codesnips 3 tabs
ruby
module BoundedFanOut
  Result = Struct.new(:value, :error) do
    def ok?
      error.nil?
    end
  end

Parallelize Independent External Calls (in a bounded way)

concurrency threads http
by codesnips 3 tabs
ruby
class Document < ApplicationRecord
  belongs_to :account

  validates :source_url, presence: true

  before_save :normalize_checksum

Prevent Long Transactions with after_save_commit for Heavy Work

rails activerecord background-jobs
by codesnips 3 tabs
ruby
class AtLeastOneOfValidator < ActiveModel::Validator
  def validate(record)
    fields = Array(options[:fields])
    raise ArgumentError, "provide :fields" if fields.empty?

    return if fields.any? { |field| filled?(record.public_send(field)) }

Custom Validator for “At Least One of” Fields

rails activemodel validations
by codesnips 3 tabs
ruby
class PostsController < ApplicationController
  def index
    posts = Post.for_feed.page(params[:page]).per(25)

    render json: {
      data: posts.map { |post| PostSerializer.new(post).as_json },

N+1 Proof Serialization with preloaded associations

rails activerecord performance
by codesnips 3 tabs
ruby
class AddOptimisticLockingToDocuments < ActiveRecord::Migration[7.1]
  def change
    add_column :documents, :lock_version, :integer, null: false, default: 0
    add_index :documents, :updated_at
  end
end

Optimistic Locking for Collaborative Edits

rails activerecord concurrency
by codesnips 3 tabs
sql
CREATE TYPE outbox_status AS ENUM ('pending', 'retry', 'processing', 'done', 'dead');

CREATE TABLE outbox_events (
    id           BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    dedupe_key   TEXT        NOT NULL,
    topic        TEXT        NOT NULL,

Atomic “Read + Mark Processed” with UPDATE … RETURNING

postgres concurrency reliability
by codesnips 3 tabs
ruby
class ReportQuery
  SQL = <<~SQL.freeze
    SELECT date_trunc('day', events.created_at) AS day,
           count(*) AS total,
           count(*) FILTER (WHERE events.kind = 'purchase') AS purchases
    FROM events

Safe Raw SQL with exec_query + Binds

rails activerecord sql
by codesnips 2 tabs