agentleFS
krzysztofsurdykrzysztofsurdy/code-virtuoso/skills/knowledge/performance/SKILL.md

performance

Skill22 starsChanged 9 months agoMITView on GitHub

Application performance optimization patterns and profiling-driven methodology. Use when the user asks to optimize application speed, reduce latency, diagnose slow queries, fix N+1 problems, implement caching layers, profile memory usage, tune database queries, apply lazy loading, configure connection pooling, or set performance budgets. Covers CPU and memory profiling, caching strategies (application, HTTP, CDN), query optimization, indexing, and load testing approaches.

45 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use web-quality-audit, core-web-vitals and 6 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • RodrigoTomeESSkill

    web-quality-audit

    Comprehensive web quality audit covering performance, accessibility, SEO, and best practices. Use when asked to "audit my site", "review web quality", "run lighthouse audit", "check page quality", or "optimize my website".

    Also in 5 projects that use this

  • thisisAhsanIqbalSkill

    core-web-vitals

    Audits HTML patterns that affect Core Web Vitals (LCP, CLS, INP). Checks for layout shift causes, largest contentful paint blockers, and interaction responsiveness issues. Use when optimising page performance or fixing Google PageSpeed Insights warnings.

    Also in 6 projects that use this

  • kpbraySkill

    best-practices

    Applies Power BI best practices, BPA rules, and enterprise standards. Use for quality validation, naming conventions, and performance optimization.

    Also in 5 projects that use this

  • VercelSkill

    remotion

    Remotion renderer for json-render that turns JSON timeline specs into videos. Use when working with @json-render/remotion, building video compositions from JSON, creating video catalogs, or rendering AI-generated video timelines.

    Also in 3 projects that use this

  • ffsshhttiikkSkill

    i18n

    Internationalization and localization

    Also in 4 projects that use this

  • JohnJBorenSkill

    ci-cd

    CI/CD pipeline design, GitHub Actions, testing automation, and deployment strategies

    Also in 3 projects that use this

The file

We split this skill into the rules it gives an agent

9 rules. 0 are common, 9 are distinctive, and 0 are very specific to this project.

  • 0

    Common

    Most of the 24 edited versions we read keep these.

  • 9

    Distinctive

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    When a popular cache key expires, many concurrent requests may all try to regenerate it at once, overwhelming the backend.

    line 83
  2. Distinctive:

    Locking: - Only one request regenerates.

    line 85
  3. Distinctive:

    Create indexes on columns used in WHERE, JOIN, and ORDER BY clauses

    line 99
  4. Distinctive:

    Use composite indexes that match your most frequent query patterns (leftmost prefix rule)

    line 100
  5. Distinctive:

    Always return connections to the pool promptly - leaked connections exhaust the pool

    line 123
  6. Distinctive:

    Use external poolers (like PgBouncer for PostgreSQL) when application-level pooling is insufficient

    line 125
  7. Distinctive:

    When the deferred work always happens anyway (just adds overhead)

    line 153
  8. Distinctive:

    When it moves latency from a predictable startup phase to unpredictable user interactions

    line 154
  9. Distinctive:

    When it creates N+1 query patterns (see Database Optimization above)

    line 155

“Common” is measured: kept by at least 6 in 10 of the 24 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Performance Optimization

Performance work follows one rule above all others: measure before you change anything. Intuition about bottlenecks is wrong more often than it is right. Every optimization should start with profiling, produce a hypothesis, apply a targeted fix, and verify with another measurement.

Core Principles

PrincipleMeaning
Measure firstNever optimize without profiling data - gut feelings about bottlenecks are unreliable
Optimize the critical pathFocus on the code that runs most frequently or blocks user-visible latency
Set budgetsDefine acceptable latency, throughput, and resource usage before you start
Avoid premature optimizationReadable, correct code first - optimize only when measurements show a real problem
Know your tradeoffsEvery optimization trades something (memory for speed, complexity for throughput, freshness for latency)

Profiling and Benchmarking

Profiling identifies where time and resources are spent. Without it, you are guessing.

Types of Profiling

TypeWhat It RevealsWhen to Use
CPU profilingHot functions, call frequency, execution time distributionSlow request handling, high CPU usage
Memory profilingAllocation rates, heap size, object retention, leaksGrowing memory usage, OOM errors, GC pressure
I/O profilingDisk reads/writes, network calls, blocking waitsSlow file operations, external service latency
Database profilingQuery execution time, query count per request, slow queriesHigh DB load, N+1 patterns, missing indexes

The Profiling Workflow

  1. Baseline - Capture metrics under normal conditions before any changes
  2. Identify - Find the hotspot consuming the most time or resources
  3. Hypothesize - Form a specific theory about why it is slow
  4. Fix - Apply a single, targeted change
  5. Verify - Measure again to confirm improvement and check for regressions

Performance Budgets

Define limits that trigger action when exceeded:

  • Response time: P50, P95, P99 latency targets per endpoint
  • Throughput: Minimum requests per second under expected load
  • Resource usage: CPU, memory, and connection limits per service
  • Page weight: Maximum transfer size for frontend assets

See Profiling Patterns Reference for detailed profiling workflows, bottleneck signatures, and load testing strategies.


Caching Strategies

Caching eliminates redundant computation and data fetching by storing results closer to where they are needed.

Cache Layers

LayerLocationLatencyUse Case
L1 - In-processApplication memory (object cache, memoization)NanosecondsHot data accessed many times per request
L2 - DistributedRedis, Memcached, shared cacheSub-millisecond to low millisecondsData shared across application instances
HTTP cacheBrowser, reverse proxy (Varnish, Nginx)Zero network round-trip for client cacheStatic assets, cacheable API responses
CDNEdge servers worldwideLow latency from geographic proximityStatic files, pre-rendered pages, media
Database cacheQuery result cache, buffer poolVariesRepeated identical queries

Invalidation Approaches

StrategyHow It WorksBest For
TTL-basedCache entries expire after a fixed durationData that tolerates bounded staleness
Event-basedCache is cleared when the source data changesData that must stay fresh after writes
Write-throughWrites update both the cache and the backing store simultaneouslyRead-heavy workloads needing strong consistency
Write-behindWrites update the cache immediately; backing store is updated asynchronouslyHigh write throughput where eventual consistency is acceptable

Cache Stampede Prevention

When a popular cache key expires, many concurrent requests may all try to regenerate it at once, overwhelming the backend. Three approaches prevent this:

  • Locking - Only one request regenerates; others wait or serve stale data
  • Probabilistic early recomputation - Requests randomly refresh the cache before expiration, spreading regeneration over time
  • Request coalescing - Duplicate in-flight requests are collapsed into a single backend call

See Caching Strategies Reference for implementation patterns with multi-language examples.


Database Optimization

Database queries are the most common performance bottleneck in web applications.

Index Strategy

  • Create indexes on columns used in WHERE, JOIN, and ORDER BY clauses
  • Use composite indexes that match your most frequent query patterns (leftmost prefix rule)
  • Covering indexes include all columns a query needs, avoiding table lookups entirely
  • Monitor unused indexes - they slow down writes without helping reads

N+1 Query Prevention

The N+1 problem occurs when code fetches a list of N records, then issues one additional query per record to load related data. Instead of 1 query, you execute N+1.

Detection signals:

  • Query count scales linearly with result set size
  • Many nearly identical queries differing only in a single parameter
  • Profiler shows dozens or hundreds of queries for a single page load

Prevention strategies:

  • Eager loading (JOIN or separate batch query upfront)
  • Batch loading (collect IDs, fetch all related records in one query)
  • DataLoader pattern (automatic batching and deduplication within a request)

Connection Pooling

Opening a database connection is expensive (TCP handshake, authentication, TLS negotiation). Connection pools maintain a set of reusable connections:

  • Size the pool based on expected concurrency - too small causes queueing, too large overwhelms the database
  • Always return connections to the pool promptly - leaked connections exhaust the pool
  • Set idle timeouts to reclaim unused connections
  • Use external poolers (like PgBouncer for PostgreSQL) when application-level pooling is insufficient

See Database Optimization Reference for query patterns, explain plan analysis, and multi-language examples.


Memory and Resource Management

Memory Optimization Patterns

PatternDescription
Object poolingReuse expensive objects instead of allocating and discarding them
StreamingProcess large datasets as streams instead of loading everything into memory
Lazy initializationDefer creation of expensive objects until they are actually needed
Weak referencesHold references that do not prevent garbage collection
Buffer reuseAllocate buffers once and reuse them across operations

Lazy Loading

Lazy loading defers work until the result is actually needed. It reduces startup time and memory usage but adds complexity and can cause unexpected latency later.

Where lazy loading helps:

  • Loading related database records only when accessed
  • Initializing expensive service connections on first use
  • Loading UI components or assets only when they become visible

Where lazy loading hurts:

  • When the deferred work always happens anyway (just adds overhead)
  • When it moves latency from a predictable startup phase to unpredictable user interactions
  • When it creates N+1 query patterns (see Database Optimization above)

Batch Operations

Replace individual operations with batch alternatives wherever possible:

  • Batch inserts instead of inserting one row at a time
  • Batch API calls instead of calling an external service N times
  • Bulk file operations instead of processing files individually

Quick Reference: Common Bottleneck Patterns

SymptomLikely CauseFirst Investigation Step
Slow response times, low CPUI/O waits (database, network, disk)Profile I/O and check query logs
High CPU, normal response timesInefficient algorithms or excessive computationCPU profile to find hot functions
Growing memory over timeMemory leak (unreleased references, unbounded caches)Heap dump comparison over time
Intermittent slowness under loadResource contention (locks, connection pool exhaustion)Check pool sizes and lock wait times
Fast locally, slow in productionNetwork latency, missing caches, different data volumesCompare profiling data between environments

Reference Files

ReferenceContents
Caching StrategiesCache layers, invalidation patterns, stampede prevention with multi-language examples
Database OptimizationQuery optimization, N+1 prevention, connection pooling, batch operations with multi-language examples
Profiling PatternsProfiling workflows, bottleneck signatures, performance budgets, load testing strategies

Integration with Other Skills

SituationRecommended Skill
Performance issues caused by poor architectureInstall knowledge-virtuoso from krzysztofsurdy/code-virtuoso for clean architecture guidance
Need to refactor slow code pathsInstall knowledge-virtuoso from krzysztofsurdy/code-virtuoso for refactoring techniques
API response time optimizationInstall knowledge-virtuoso from krzysztofsurdy/code-virtuoso for API design principles
Database schema and query designInstall knowledge-virtuoso from krzysztofsurdy/code-virtuoso for testing strategies to verify optimizations

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.