N+1 Query Detection
Detect N+1 query patterns in GORM repository and service code — identify loops that execute queries, missing preloads, and unbounded fetches
Best use case
N+1 Query Detection is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Detect N+1 query patterns in GORM repository and service code — identify loops that execute queries, missing preloads, and unbounded fetches
Teams using N+1 Query Detection should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/n-1-query-detection/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How N+1 Query Detection Compares
| Feature / Agent | N+1 Query Detection | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Detect N+1 query patterns in GORM repository and service code — identify loops that execute queries, missing preloads, and unbounded fetches
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# N+1 Query Detection Skill
Scan repository and service code for N+1 query patterns that cause performance degradation.
## Trigger Conditions
- Repository or service files are modified
- Performance review is requested
- New data access patterns are introduced
- User invokes with "N+1 check" or "n-plus-1-query-detection"
## Input Contract
- **Required:** Path to repository and/or service files
- **Optional:** GORM configuration for preload analysis
## Output Contract
- List of N+1 patterns found with file:line references
- Severity assessment (critical for high-volume paths, low for admin-only)
- Fix recommendation (Preload, Joins, or batch query)
- Unbounded query warnings (missing Limit)
## Tool Permissions
- **Read:** Repository files, service files, model relationship definitions
- **Write:** None (read-only analysis)
- **Search:** Grep for loop patterns, `.Find()`, `.First()`, relationship access
## Execution Steps
1. **Scan for loops with queries**: Find patterns where a database query is inside a `for` loop
2. **Check preloads**: For each query that accesses relationships, verify `Preload()` or `Joins()` is used
3. **Check unbounded queries**: Find `.Find()` calls without `.Limit()` on list endpoints
4. **Assess severity**: Rate each finding by the expected data volume (high-traffic endpoints are critical)
5. **Recommend fixes**: Suggest specific GORM patterns (`Preload`, `Joins`, `SelectinLoad`)
6. **Report**: Produce findings with code examples for the fix
## Common Patterns (Anti-patterns)
```go
// N+1: Query inside loop
users, _ := db.Find(&users)
for _, u := range users {
db.Where("user_id = ?", u.ID).Find(&orders) // N+1!
}
// Fix: Preload
db.Preload("Orders").Find(&users)
```
## References
- `.cursor/rules/122-gorm-conventions.mdc`
- `.cursor/rules/047-performance-optimization.mdc`Related Skills
googlebigquery-automation
Automate Google BigQuery tasks via Rube MCP (Composio): run SQL queries, explore datasets and metadata, execute MBQL queries via Metabase integration. Always search tools first for current schemas.
database-query
Natural language database queries with multi-database support, query optimization, and visual results
context-detection
Automatically detect project tech stack, frameworks, and development context
ai-problems-detection
Protocolo de autodiagnostico contra os 5 problemas mais comuns da IA ao programar. Detecta overengineering, codigo duplicado, reinvencao da roda, falta de documentacao e arquivos monoliticos. Use SEMPRE antes de implementar, ao planejar mudancas, quando criar funcoes novas, ao escrever codigo, para revisar implementacoes. Palavras-chave - simples, duplicado, repetido, existe, separar, modular, documentacao, complexo, refatorar, engenharia demais, roda, reutilizar.
ai-pattern-detection
Detects AI-generated writing patterns and suggests authentic alternatives. Auto-applies when reviewing content, editing documents, generating text, or when user mentions writing quality, AI detection, authenticity, or natural voice.
AI Maestro Code Graph Query
PROACTIVELY query the code graph database to understand relationships and impact of changes. Use this skill WHEN READING any file to understand context, when searching for files, when exploring the codebase, or when you need to understand what depends on a component. This is your primary tool for understanding code structure and avoiding breaking changes.
ActiveRecord Query Patterns
Complete guide to ActiveRecord query optimization, associations, scopes, and PostgreSQL-specific patterns. Use this skill when writing database queries, designing model associations, creating migrations, optimizing query performance, or debugging N+1 queries and grouping errors.
Quick Query
Execute simple network status queries that require 1-2 commands. Use when user asks to "check device status", "show interface", "query routing table", "display BGP neighbors", or needs simple read-only information retrieval.
moai-alfred-language-detection
Auto-detects project language and framework from package.json, pyproject.toml, etc.
performing-steganography-detection
Detect and extract hidden data embedded in images, audio, and other media files using steganalysis tools to uncover covert communication channels.
ai-writing-detection
Comprehensive AI writing detection patterns and methodology. Provides vocabulary lists, structural patterns, model-specific fingerprints, and false positive prevention guidance. Use when analyzing text for AI authorship or understanding detection patterns.
bio-metagenomics-amr-detection
Detect antimicrobial resistance genes using AMRFinderPlus, ResFinder, and CARD. Screen isolates and metagenomes for resistance determinants. Use when characterizing resistance profiles in clinical isolates, surveillance samples, or metagenomic data.