caching

ruby
module Api
  module V1
    class UsersController < BaseController
      def show
        user = User.includes(:profile).find(params[:id])

ETags for conditional requests and caching

rails caching http-caching
by Alex Kumar 1 tab
ruby
json.array! @posts do |post|
  json.cache! ['v1', post], expires_in: 1.hour do
    json.id post.id
    json.title post.title
    json.excerpt post.excerpt
    json.published_at post.published_at

Fragment caching for expensive JSON serialization

rails caching performance
by Alex Kumar 1 tab
ruby
class Comment < ApplicationRecord
  belongs_to :post, touch: true
  belongs_to :author, class_name: "User"

  validates :body, presence: true, length: { maximum: 10_000 }

Granular Cache Invalidation with touch: true

rails caching activerecord
by codesnips 4 tabs
erb
<nav class="site-nav" data-controller="preload">
  <ul>
    <li>
      <%= link_to "Dashboard", dashboard_path,
            class: "nav-link",
            data: { turbo_preload: true } %>

Speed up perceived performance with Turbo preload links

rails hotwire turbo
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 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
sql
-- Prepared statements basics
-- PostgreSQL syntax
PREPARE get_user (INT) AS
SELECT id, username, email
FROM users
WHERE id = $1;

Query plan caching and prepared statements

postgresql performance query-plans
by Maria Garcia 2 tabs
ruby
class ProductsController < ApplicationController
  def index
    @products = Product
      .includes(:category)
      .order(created_at: :desc)
      .page(params[:page])

Fragment caching inside Turbo Frames (fast lists)

rails hotwire turbo
by codesnips 4 tabs
ruby
module CollectionCacheKey
  extend ActiveSupport::Concern

  def cache_key_for(scope)
    relation = scope.respond_to?(:all) ? scope.all : scope
    model = relation.klass

Deterministic Cache Keys for Collections

rails caching activerecord
by codesnips 3 tabs
typescript
import { createHash } from "crypto";
import { readFileSync } from "fs";

export function sha256(query: string): string {
  return createHash("sha256").update(query, "utf8").digest("hex");
}

GraphQL persisted queries (hash allowlist)

graphql security performance
by codesnips 3 tabs
javascript
export const CACHE_VERSION = 'v7';

export const APP_SHELL = '/index.html';

export const PRECACHE_URLS = [
  '/',

Service worker: cache static assets safely

web performance pwa
by codesnips 3 tabs
ruby
class Post < ApplicationRecord
  # View counter - increments without hitting the database
  kredis_counter :view_count, expires_in: 1.day

  # Recent viewers list - stores last 10 viewer IDs
  kredis_unique_list :recent_viewers, limit: 10

Rails Kredis for higher-level Redis operations

rails redis kredis
by Maya Patel 2 tabs