Command Palette

Search for a command to run...

Назад к скиллам
скилл № 55348

performance-tuning

Measure-first performance work for Laravel applications — diagnosing slow endpoints, queries and pages, then fixing them in order of actual impact. Covers…

БесплатноБез исполняемых скриптов
nasrulhazimот nasrulhazim★ 26 звёзд на GitHub

Установить performance-tuning в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Об этом скилле

Performance Tuning

Performance work without a baseline is decoration. Every change in this skill is bracketed by a measurement before and the same measurement after, and reported as both numbers.

The order matters. Roughly 80% of Laravel slowness is database access, 15% is work done synchronously that should be queued, and 5% is everything else. Work the list in that order rather than starting with the interesting problem.

Command Reference

Command Description
/perf baseline Capture the current numbers for a slow path before changing anything
/perf queries Find N+1s, missing indexes and unbounded result sets
/perf cache Design a caching tier and its invalidation
/perf queue Move synchronous work off the request
/perf frontend Livewire payload, asset and image budgets
/perf report Baseline → change → result, with remaining bottlenecks ranked

When to Use

  • A page, endpoint or job is slow enough that someone complained
  • A latency or throughput target has to be met before launch
  • Load has grown and something that used to be fine no longer is
  • A query, report or export times out
  • Memory exhaustion on a job or command

Do not use this skill to optimise something nobody measured. "This looks like it could be slow" is not a finding — it is a guess with a diff attached. If the path is not slow, say so and stop.


1. Baseline — before anything else

You cannot claim an improvement without a number to improve on.

// Query count and time for a single path
DB::enableQueryLog();
$start = microtime(true);

$result = $service->run();

dump([
    'queries' => count(DB::getQueryLog()),
    'ms'      => round((microtime(true) - $start) * 1000),
    'memory'  => round(memory_get_peak_usage(true) / 1048576, 1) . 'MB',
]);
# Endpoint-level, repeatable
curl -o /dev/null -s -w "%{time_total}s\n" https://app.test/dashboard

# What the app thinks it is
php artisan about

Record: query count, wall-clock ms, peak memory, response bytes. Capture them against realistic data volume — a seeder with 20 rows hides every N+1 in the codebase.

Instrument Use for
DB::listen() / getQueryLog() Query count and the actual SQL — start here, always
Laravel Debugbar Local per-request breakdown
Telescope Local/staging request history after the fact
Pulse Production-safe aggregates: slow queries, slow jobs, slow requests
EXPLAIN Whether a query uses an index
Browser devtools Front-end only — TTFB separates server from client

2. Queries — where the time actually is

N+1

The single most common Laravel performance bug. A page issuing 400 queries is not a database problem; it is a missing with().

// ❌ 1 + N queries
$orders = Order::all();
foreach ($orders as $order) {
    echo $order->customer->name;      // one query each
}

// ✅ 2 queries
$orders = Order::with('customer')->get();

// ✅ Nested, and only the columns needed
$orders = Order::with(['customer:id,name', 'items.product:id,title'])->get();

// ✅ Aggregates without loading the relation
$orders = Order::withCount('items')->withSum('items', 'total')->get();

Catch them automatically in local and CI:

// AppServiceProvider::boot()
Model::preventLazyLoading(! app()->isProduction());

That one line turns every N+1 into an exception in development. Add it before hunting manually.

Unbounded result sets

// ❌ Loads every row into memory
$users = User::all();

// ✅ Page it
$users = User::paginate(25);

// ✅ Stream it for a job or export
User::chunkById(1000, fn ($chunk) => $chunk->each(...));
User::lazyById()->each(...);           // generator, constant memory

chunkById over chunk — plain chunk skips rows when the underlying set changes mid-pass.

Indexes

An index earns its keep on columns used in WHERE, JOIN, ORDER BY and GROUP BY.

Schema::table('orders', function (Blueprint $table) {
    $table->index('status');                       // filtered on
    $table->index(['tenant_id', 'created_at']);    // composite: filter + sort
});

Read EXPLAIN before and after:

EXPLAIN SELECT * FROM orders WHERE tenant_id = 5 ORDER BY created_at DESC LIMIT 25;
type column Meaning
const / eq_ref / ref Index used. Good.
range Index used for a range. Usually fine.
index Full index scan — better than ALL, still reading everything
ALL Full table scan. This is the finding.

Composite index column order is left-to-right prefix. An index on (tenant_id, created_at) serves WHERE tenant_id = ? and WHERE tenant_id = ? ORDER BY created_at, but not WHERE created_at > ? alone.

Indexes are not free: every one slows writes and consumes space. Add the index the query plan asks for, not one per column.

Other query wins

Problem Fix
SELECT * on a wide table
Полный SKILL.md на GitHub

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

  • references/caching-strategy.md
  • references/query-optimisation.md

FAQ

Что делает скилл performance-tuning?

Measure-first performance work for Laravel applications — diagnosing slow endpoints, queries and pages, then fixing them in order of actual impact. Covers baselining before any change, N+1 detection and eager loading, database indexing strategy and EXPLAIN reading, pagination and chunking for large result sets, caching tiers and safe invalidation, moving work to queues, trimming Livewire payloads and polling, and front-end asset and image budgets. Every finding carries a number: query count, milliseconds, payload bytes or memory. Use this skill whenever the user reports something slow, wants to profile or optimise, asks about indexes, caching or N+1 queries, or needs a page or API endpoint to hit a latency target — including "this page is slow", "optimise this query", "why is this endpoint taking 4 seconds", "find the N+1", "should I add an index here", "add caching", "reduce the payload", "the dashboard takes forever", "profile this", "laman ni lambat", "kenapa query ni lambat", "tolong optimize", "nak tambah index", "guna cache macam mana", or "endpoint ni makan masa". Never optimise blind — pairs with debugging for root-causing and code-quality when the fix is a refactor.

Как установить скилл performance-tuning?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл performance-tuning запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить performance-tuning с