/claude-toolkit:performance-tuningfrom claude-toolkit
Measure-first performance tuning for Laravel apps: diagnoses slow endpoints, queries, and pages, then fixes them by impact. Covers N+1 detection, indexing, caching, queues, Livewire payloads, and front-end budgets.
Ships in claude-toolkit. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
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 | 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 |
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.
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 |
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.
// ❌ 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.
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.
| Problem | Fix |
|---|---|
SELECT * on a wide table | select(['id', 'name', 'total']) |
| Counting by loading | ->count(), never count($model->items) after loading |
whereHas on a large relation | whereIn on a sub-select, or denormalise a counter |
| Repeated identical query in a loop | Hoist it out, or cache for the request |
orderBy on an unindexed expression | Store the computed value in a column and index it |
Cache the expensive and stable. Caching a cheap query buys nothing and adds an invalidation bug.
// Request-scoped: same value used several times in one request
$settings = once(fn () => Setting::all()->keyBy('key'));
// Short TTL for a hot read
$stats = Cache::remember("tenant:{$id}:stats", now()->addMinutes(5),
fn () => $this->computeStats($id));
// Forever + explicit invalidation on write
$config = Cache::rememberForever("tenant:{$id}:config",
fn () => Config::forTenant($id));
| Tier | Use for | Invalidate by |
|---|---|---|
once() / static | Same value read repeatedly in one request | End of request |
Cache::remember + short TTL | Dashboards, counts, aggregates | Time |
rememberForever | Config, reference data, rarely-changing lookups | Model event on write |
config:cache / route:cache / view:cache | Always, in production | Deploy |
Invalidation is the hard part and the dangerous part:
// Model event — invalidate where the write happens, not at every read site
protected static function booted(): void
{
static::saved(fn (self $m) => Cache::forget("tenant:{$m->tenant_id}:config"));
static::deleted(fn (self $m) => Cache::forget("tenant:{$m->tenant_id}:config"));
}
Never cache across an authorization or tenant boundary. A cache key without the tenant or
user in it will eventually serve one customer another's data. That is not a performance bug,
it is a security incident — see security-hardening.
If the user does not need the result to render the response, it does not belong in the request.
// ❌ 3 seconds of the user's time spent on things they never see
Mail::to($user)->send(new WelcomeMail($user));
$this->generateReport($order);
$this->notifySlack($order);
// ✅
SendWelcomeMail::dispatch($user);
GenerateReport::dispatch($order)->onQueue('reports');
NotifySlack::dispatch($order)->afterCommit();
| Rule | Why |
|---|---|
afterCommit() on jobs dispatched inside a transaction | Otherwise the worker can pick it up before the row exists |
| Jobs must be idempotent | Retries are guaranteed to happen eventually |
| Pass IDs, never whole models | The payload is serialised; a fat model is a fat queue |
| Separate queues by latency need | A 40-minute export must not sit in front of a password reset |
Set $timeout and $tries explicitly | Defaults are rarely right for either fast or slow jobs |
Verify the worker is actually consuming what you dispatch — a job on a connection Horizon is
not watching sits unclaimed forever (see debugging).
Every Livewire request round-trips the component's public state. That state is the payload.
| Problem | Fix |
|---|---|
| Whole Eloquent model as a public property | Hold the ID; load in render() or a computed property |
| Large collection as a public property | Use #[Computed] — not serialised into the payload |
wire:poll at default 2s on a heavy component | Lengthen the interval, or use wire:poll.visible |
| Every keystroke hitting the server | wire:model.live.debounce.400ms, or plain wire:model |
| A heavy component blocking first paint | #[Lazy] with a placeholder |
| Re-rendering an unchanged expensive subtree | wire:key on list items; split the component |
#[Computed]
public function orders(): Collection // not serialised into the payload
{
return Order::with('customer:id,name')->latest()->take(25)->get();
}
| Budget | Target |
|---|---|
| TTFB | < 200ms (server work — everything above this line) |
| Largest Contentful Paint | < 2.5s |
| Interaction to Next Paint | < 200ms |
| Cumulative Layout Shift | < 0.1 |
| Total JS, compressed | < 300KB |
width/height to stop layout shiftloading="lazy" on below-the-fold imagesTTFB is the only one of these this skill's earlier sections can fix. If TTFB is 1.8s, no amount of front-end work matters — go back to section 2.
The fastest code is the code that does not run. Before adding a cache layer, a queue, a read-replica or a denormalised counter, check the rungs above it: is the query even needed, is an existing index enough, is there a smaller result set to ask for?
ponytail is installed by default with this toolkit and enforces that ordering. A caching
layer added around an unindexed query is two problems where there was one. Add the index
first, re-measure, and often the cache becomes unnecessary. If ponytail is absent, apply
the same ordering by hand.
| Rationalization | Reality |
|---|---|
| "This looks slow, I'll optimise it" | Looks are not a measurement. Optimising an unmeasured path spends real time on an imaginary problem and adds real risk. |
| "It's fast enough locally" | Locally you have 20 seeded rows, no network latency and a warm cache. Production has none of those. |
| "I'll add a cache, that'll fix it" | A cache over a 400-query page still issues 400 queries on every miss, and now serves stale data too. Fix the queries. |
| "Adding indexes on everything is safer" | Every index slows every write and consumes space. Add the one the query plan asks for. |
| "Eager loading everything avoids N+1" | with() on ten relations you do not render loads ten relations you do not render. Eager load what the view uses. |
| "The ORM is slow, I'll write raw SQL" | The ORM issues the query you asked for. Almost always the fix is the query, not the layer. |
| "I changed five things and it's faster" | You cannot report which one worked, or which one is a latent bug. Change one, measure, repeat. |
| "Caching user data with a shared key is fine, it's the same query" | Until it serves customer A's dashboard to customer B. That is a security incident, not a cache miss. |
| "Queueing it is over-engineering" | A three-second synchronous email is three seconds of every user's time and one SMTP outage from a broken checkout. |
| "We'll optimise it when it becomes a problem" | Reasonable — and it is a problem now, which is why you are reading this. It was not reasonable to skip the index at write time. |
Model::all() or an unpaginated list endpointCache::forever with no invalidation path anywhere in the codebaseEXPLAIN showing ALL on a table that is not tinyafterCommit()wire:poll on a component that runs an aggregate queryModel::preventLazyLoading() disabled to make a page workEXPLAIN confirms every new index is actually used by the query it was added forModel::preventLazyLoading() is on in local/CI and the suite passes with it| File | Read When |
|---|---|
references/query-optimisation.md | Hunting N+1s, reading EXPLAIN, choosing indexes, handling large result sets |
references/caching-strategy.md | Choosing a cache tier, writing keys, and designing invalidation that cannot leak across tenants |
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
laravel-performance, n-plus-one, query-optimization, caching, profiling
npx claudepluginhub nasrulhazim/claude --plugin claude-toolkit43 skills in this plugin
/business-cardSVG business card designer that takes contact details and brand preferences, then produces 12 front design concepts with optional back designs, interactive HTML preview galleries, individual card showcases with front/back flip animation, and print-ready SVG exports with bleed area and crop marks. Supports horizontal and vertical orientations, six layout styles (minimal, corporate, creative, elegant, bold, tech), multiple color schemes, QR code placeholders, social media icons, and logo integration. Use this skill whenever the user asks to design a business card, create a name card, make visiting cards, or says "design business card", "buat kad bisnes", "create name card", "reka kad perniagaan", "design kad nama", "I need a business card for X".
/ci-cd-pipelineCI/CD pipeline builder for Laravel projects — extends Kickoff's existing GitHub Actions CI with continuous deployment pipelines (staging/production), Docker containerisation, secret management, and failure notifications. Generates Dockerfiles, docker-compose.yml, deployment configs for VPS via SSH, container registry push workflows, and leverages Kickoff's /bin scripts (deploy.sh, backup.sh, setup.sh) in automated workflows. Use this skill whenever the user asks to set up deployment pipelines, containerise a Laravel app, configure CD for staging or production, push Docker images to a registry, manage deployment secrets, add failure notifications to CI, or integrate /bin scripts with GitHub Actions. Triggers for requests like "set up CD pipeline", "deploy to staging automatically", "dockerise my Laravel app", "add Docker to my project", "push image to registry", "manage secrets in CI", "notify on failure", "extend CI with deployment", "setup deploy pipeline", "nak deploy guna GitHub Actions", "tambah Docker dalam project", "setup CD untuk staging", "nak auto deploy ke production", "dockerise Laravel app aku", "tambah notification kalau CI fail", "macam mana nak manage secrets dalam GitHub Actions", or "integrate bin scripts dengan CI". Assumes Laravel Kickoff as the baseline — GitHub Actions CI (Pint, PHPStan, Rector, Pest) and /bin scripts (deploy.sh, backup.sh) are already configured. This skill extends that baseline with CD, Docker, and deployment automation.
/code-qualityPHP and Laravel code quality toolchain — static analysis with Larastan/PHPStan, code style enforcement with Pint, automated refactoring with Rector, baseline management for legacy codebases, and CI pipeline integration via GitHub Actions. Use this skill whenever the user asks to check code quality, fix linting errors, run static analysis, modernise PHP code, set up CI quality gates, manage PHPStan baselines, configure Pint presets, or apply Rector rules. Triggers for requests like "run quality check", "fix my code style", "analyse with larastan", "update phpstan baseline", "modernise my PHP code", "set up CI for quality", "check code quality", "pint tak jalan", "nak fix phpstan error", "setup rector", "betulkan code style", "tambah quality gate dalam CI", or "baseline phpstan untuk legacy code". Assumes Laravel Kickoff as the baseline — PHPStan, Pint, Rector, and GitHub Actions CI are already configured. This skill extends and customises that baseline.
/courseware-builderInteractive HTML courseware builder — turns any technical topic, flow, or process into a CD-Courseware-style interactive slide deck with animated diagrams, step-by-step simulation, syntax-highlighted code examples, and key points panels. Use this skill whenever the user wants to create teaching materials, interactive slides, animated flow diagrams, or step-by-step technical walkthroughs — even if they say "buatkan slides untuk topik X", "jadikan courseware", "buat interactive tutorial", or "create a lesson on X". Also triggers for "convert my diagram to interactive slides" or "build a visual walkthrough for my training".
/debuggingSystematic debugging and error recovery for Laravel and PHP projects — a five-step triage that goes reproduce, localise, reduce, fix, guard. Covers reading a stack trace properly, bisecting with git, isolating a failure to the smallest reproducer, telling a symptom apart from a root cause, and closing every fix with a regression test. Includes Laravel-specific traps: N+1 masked as a timeout, queue jobs failing silently on the wrong connection, cache and config caches serving stale values, Livewire state desync, and eloquent/model events firing in unexpected order. Use this skill whenever the user reports something broken, failing, flaky, slow-then-erroring, or behaving differently in production than locally — including "this test is flaky", "why is this failing", "debug this error", "it works locally but not on staging", "find the root cause", "this exception makes no sense", "the queue job never runs", "bisect this regression", "kenapa error ni", "tolong debug", "test ni kejap pass kejap fail", "cari punca sebenar", "jalan kat local tapi tak jalan kat production", or "job queue tak jalan". Pairs with kickoff-pest-testing for the regression test and log-monitor for production-log-driven investigations.
/deploy-appDeploys a Kickoff-based Laravel application to its host by running `bin/deploy` over SSH, then verifies the release and knows what each way it can stop means. Use this skill whenever the user asks to deploy an app, push the latest code to production, check what commit production is running, bring a site back up after a failed deploy, or roll back — "deploy latest", "deploy the app", "tolong deploy", "deploy latest dulu", "push to production", "apa commit dekat production", "site down after deploy", "keluarkan maintenance mode", "rollback production", "kenapa 503". Covers the deploy command and its flags, the post-deploy verification checklist, the recovery path for each failure mode, and the production traps that have already cost time. Does NOT cover provisioning a new host from bare metal (`bin/provision-host`), CI/CD pipeline design (`ci-cd-pipeline`), or writing deploy operations.
Other plugins' skills for the same job