Skip to content
Skills Library
Programming · Analysis

eloquent-performance

/eloquent-performance

The query-performance cookbook — reading EXPLAIN plans, diagnosing + fixing N+1 without overfetching, pagination and chunking choices, the caching decision tree (remember vs flexible vs lock), measurement discipline. Use when an endpoint or query is slow, before adding an index or cache, or when reviewing query-shape changes. Diagnosis recipes — the fix lands with the owning builder (backend / database developer).

Licence
MIT
Last repository change
28.09.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
1
Scripts
0
HTML comments
0
URLs in SKILL.md
0
Deprecation

No signals detected. Repository changed on 28.09.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What it does and when to use it

The query-performance cookbook — reading EXPLAIN plans, diagnosing + fixing N+1 without overfetching, pagination and chunking choices, the caching decision tree (remember vs flexible vs lock), measurement discipline. Use when an endpoint or query is slow, before adding an index or cache, or when reviewing query-shape changes. Diagnosis recipes — the fix lands with the owning builder (backend / database developer).

Original author description

The query-performance cookbook — reading EXPLAIN plans, diagnosing + fixing N+1 without overfetching, pagination and chunking choices, the caching decision tree (remember vs flexible vs lock), measurement discipline. Use when an endpoint or query is slow, before adding an index or cache, or when reviewing query-shape changes. Diagnosis recipes — the fix lands with the owning builder (backend / database developer).

How it works

  1. Reading EXPLAIN
  2. N+1
  3. Reading big, writing big
  4. Caching decision tree
  5. Measurement discipline
Original SKILL.md headings · 47 lines, 587 words
SKILL.md preview
---
name: eloquent-performance
description: "The query-performance cookbook — reading EXPLAIN plans, diagnosing + fixing N+1 without overfetching, pagination and chunking choices, the caching decision tree (remember vs flexible vs lock), measurement discipline. Use when an endpoint or query is slow, before adding an index or cache, or when reviewing query-shape changes. Diagnosis recipes — the fix lands with the owning builder (backend / database developer)."
---

# Eloquent + Query Performance

Measure first. A number without a baseline is a guess; p95/p99, not mean. Reproduce under realistic volume — a plan on 100 rows lies about 10M. One probe decides run-vs-static: no `vendor/` (or the first bootstrap fails) → static analysis only, declared as such — never retry-flail an unrunnable app.

## Reading EXPLAIN

`EXPLAIN ANALYZE <query>` (MySQL 8+ / Postgres). Red flags, in order of blood pressure:

- **rows examined ≫ rows returned** — the query scans and discards; index or rewrite.
- **type=ALL / Seq Scan** on a large table — full scan. Check: is there an index the planner *can't* use? Function-on-column (`WHERE DATE(created_at) = …`) and leading-wildcard `LIKE '%x'` kill index use — rewrite as a range (`created_at BETWEEN …`).
- **filesort / temporary table** — sort not served by an index; composite index matching `WHERE` + `ORDER BY` order.
- **Postgres**: `Rows Removed by Filter` high → same discard problem; check `work_mem` spills on sorts/hashes.

Index handoff to `database-developer`: the EXPLAIN plan, the query pattern + frequency, and the target verdict — never "add an index" bare.

## N+1

- Detect: `Model::preventLazyLoading(! app()->isProduction())` (plus `preventSilentlyDiscardingAttributes()`) in `AppServiceProvider::boot` throws on lazy loads in non-prod; Pulse Slow Queries / Telescope Queries tab show the repeat pattern; `DB::listen(fn ($q) => Log::info('sql', ['sql' => $q->sql, 'ms' => $q->time]))` around a reproduction counts them.
- Fix at source: `with()`, `withCount`, `withExists`, `withAggregate` on the list query; `loadMissing()` post-hoc; `whereRelation()` for single-column constraints; multi-column OR chains → `whereAny` / `whereAll` / `whereNone` instead of PHP filtering.
- L13 safety net: `Model::automaticallyEagerLoadRelationships()` globally, or `$collection->withRelationshipAutoloading()` per collection — auto lazy-eager-loads for the whole collection instead of per row. A net, not a substitute for explicit `with()` on known paths.
- **Check overfetch after the fix**: eager-loading a fat relation to render one field, on 10k rows, trades N+1 for a memory bomb. Constrain: `with('author:id,name')`. Measure both ways.

## Reading big, writing big

- Iterate large sets: `chunkById()` (safe under mutation — `chunk()` is not), `lazy()`, `cursor()` (single query, no eager loads).
- Bulk writes: `upsert()`, `insertOrIgnore()` — no model events fire; if Observers matter, loop in a transaction and say why.
- Select only needed columns. Cursor pagination for infinite scroll / large offsets; offset pagination only when total counts matter and the table is small.

## Caching decision tree

1. Recomputed per request, cheap to invalidate → `Cache::remember($key, $ttl, $fn)`.
2. Stampede-prone (hot key, expensive recompute) → `Cache::flexible($key, [$fresh, $stale], $fn)` — serves stale, recomputes in background.
   - Same key hit repeatedly within one request/job → `Cache::memo()->get($key)` (L13) — resolves once, then from memory. Sliding expiration → `Cache::touch($key, $ttl)` extends TTL without get+put.
3. Staleness unacceptable → `Cache::lock($key)->block($seconds, $fn)` around the recompute.

Every cache entry states three things or it doesn't ship: **key, TTL, exact invalidation trigger**. A cache without an invalidation story is a bug with latency. Capture hit ratio for any cache added or touched.

Redis: pipeline batched ops, tag caches for group invalidation, know the eviction policy (`maxmemory-policy`) before trusting TTLs.

## Measurement discipline

- Wall-clock endpoints: `wrk -t4 -c50 -d30s <url>` or a k6 script → p50/p95/p99 + req/s. Local or dedicated staging only; shared/prod targets need human sign-off.
- PHP-level: Xdebug → KCachegrind, or Blackfire / Tideways for call graph + memory.
- State every result as a number with units, before and after. No before/after delta → it didn't happen.
- Cheapest win first: eager-load > index > cache > rewrite > scale. Exhaust a layer before escalating.

Versions

The database has no other skills named eloquent-performance.

Identical content appears in 2 other GitHub folders. We show one copy with the highest score.

Database snapshot: 13.11.2026 · package version 302c33f08c31 (SHA-256 digest of the entire package)

Downloads in the last 30 days: 0 · ranking

: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 100laravel-database-optimization
    Laravel database optimization patterns. Use when writing Eloquent queries, creating migrations, configuring caching, debugging slow queries, or optimizing database performance. Triggers on tasks involving N+1 queries, indexing, Redis caching, pagination, or database transactions.
  • 87performance-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…
  • 90database-query-performance
    Diagnose database latency with explain plans, index ownership, and query-shape review. Use when a query is slow, an index is missing, or scans and N+1 patterns appear.
  • 100laravel-eloquent
    Eloquent and query-layer engineering rules for Laravel — eliminating N+1, choosing a pagination strategy, short atomic transactions, casts and scopes on the model, where raw SQL is allowed, and how migrations declare the schema those queries depend on. Use when writing or…
  • 100eloquent
    Use when writing Eloquent models, relationships, scopes, or queries via Model:: — 'fetch users with their orders'. NOT for PHPStan output, non-Eloquent services, or raw SQL questions.
  • 100eloquent-patterns
    Eloquent ORM best practices: query builders, scopes, relations, N+1 prevention, batch operations, soft deletes, model events, raw queries when needed. Apply when: writing or reviewing Eloquent queries and model interactions. Activated automatically by laravel-plugin/stack.md as…

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.