n-1

ruby
# BAD: N+1 query problem
@users = User.all
@users.each do |user|
  puts user.posts.count  # Fires query for each user!
end

ActiveRecord query optimization and N+1 prevention

ruby rails activerecord
by Sarah Mitchell 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
Rails.application.configure do
  # Bullet configuration
  config.after_initialize do
    Bullet.enable = true
    Bullet.alert = true # Show JavaScript alert
    Bullet.bullet_logger = true # Log to bullet.log

Rails N+1 query detection with Bullet

rails performance n-1
by Maya Patel 3 tabs
typescript
import DataLoader from "dataloader";
import { Pool } from "pg";

export interface User { id: number; name: string; }
export interface Post { id: number; user_id: number; title: string; }

N+1 avoidance with DataLoader (GraphQL)

graphql performance dataloader
by codesnips 3 tabs
typescript
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export async function getFeedNaive(limit = 20) {
  const posts = await prisma.post.findMany({

Prisma: avoid N+1 with include/select

prisma performance typescript
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