agentleFS
SwastikPandey1024SwastikPandey1024/agentic-engineering-os/.agents/skills/performance-optimization/SKILL.md

performance-optimization

Skill1 starsChanged 3 months agoMITView on GitHub

Systematic profiling, bottleneck isolation, latency reduction, memory optimization, and benchmarking without premature guesswork.

125 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use constraint-driven-development, git-workflow-and-versioning and 10 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.
  • MrCipherSmithSkill

    constraint-driven-development

    Use when a project needs a persistent, measurable quality bar — starting a project without documented standards, 'set up constraints', or when coverage/perf/a11y thresholds get re-debated per-PR. Produces CONSTRAINTS.md with enforceable numbers, ratchets, and a guard against silent weakening. NOT for throwaway prototypes or a one-off CI setup.

    Also in 15 projects that use this

  • LLl0k0laDSkill

    git-workflow-and-versioning

    Use when making any code change. Use when committing, branching, resolving conflicts, or when you need to organize work across multiple parallel streams.

    Also in 42 projects that use this

  • LLl0k0laDSkill

    using-agent-skills

    Use when starting a session or when you need to discover which skill applies to the current task. This is the meta-skill that governs how all other skills are discovered and invoked.

    Also in 33 projects that use this

  • HK-hubSkill

    deprecation-and-migration

    Manages deprecation and migration. Use when removing old systems, APIs, or features. Use when migrating users from one implementation to another. Use when deciding whether to maintain or sunset existing code.

    Also in 39 projects that use this

  • ukanwatSkill

    input-systems

    Architect game input — action mapping (abstracting keys into named actions), rebinding with conflict detection and persistence, multi-device support (keyboard, gamepad, touch), analog deadzones, and feel features like input buffering and coyote time, plus accessibility. Engine-neutral. Use when the user mentions input mapping, rebind controls, gamepad support, deadzone, input buffering, coyote time, or accessible controls.

    Also in 4 projects that use this

  • HK-hubSkill

    observability-and-instrumentation

    Instruments code so production behavior is visible and diagnosable. Use when adding logging, metrics, tracing, or alerting. Use when shipping any feature that runs in production and you need evidence it works. Use when production issues are reported but you can't tell what happened from the available data.

    Also in 31 projects that use this

  • +6 more from LLl0k0laD

The file

We split this skill into the rules it gives an agent

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

  • 0

    Common

    Most of the 110 edited versions we read keep these.

  • 3

    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:

    Use this skill when:

    line 10
  2. Distinctive:

    Never optimize by guessing.

    line 16
  3. Distinctive:

    NEVER micro-optimize before profiling: Don't waste time rewriting readable string formatting when 95% of the time is spent waiting on a …

    line 112

“Common” is measured: kept by at least 6 in 10 of the 110 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 Skill

1. When Should I Use This?

Use this skill when:

  • API response latency exceeds acceptable SLAs (> 200-500ms for standard CRUD, > 2s for complex RAG/inference).
  • Investigating high memory consumption, CPU saturation, or GPU starvation.
  • Optimizing slow SQL queries, database indexing, or ORM object serialization.
  • Profiling Python execution time with cProfile, py-spy, or line_profiler.

Never optimize by guessing. Every optimization must begin with empirical measurement and end with benchmarking.


2. What Should I Inspect First?

  1. Bottleneck Domain:
    • Is the bottleneck in Database I/O (unindexed queries, N+1 joins)?
    • Is it in Network / External API calls (synchronous HTTP requests, sequential LLM calls)?
    • Is it in CPU Computation (complex loops in Python, unvectorized Pandas/NumPy operations)?
    • Is it in Memory / Garbage Collection (holding giant DataFrames or tensors in RAM)?
    • Is it in Frontend Rendering (unnecessary re-renders, unmemoized heavy lists)?
  2. Current Baseline Metrics: Record the current p50, p95, and p99 latency or memory watermark before making any edits.

3. What Workflow Should I Follow?

1. MEASURE: Establish baseline performance with concrete metrics.
      ↓
2. PROFILE: Run profiler to locate the exact hot function or query.
      ↓
3. ISOLATE: Identify the architectural or algorithmic cause.
      ↓
4. OPTIMIZE: Apply targeted optimization (e.g. indexing, vectorization, caching).
      ↓
5. BENCHMARK: Rerun measurement under identical conditions.
      ↓
6. REGRESSION CHECK: Verify all unit and integration tests still pass.

Python Profiling with cProfile

# scripts/profile_hotspot.py
import cProfile
import pstats
from app.services.rag_service import VectorStore

def run_workload():
    store = VectorStore()
    dummy_chunks = [{"text": f"Document snippet {i}", "page_num": 1} for i in range(1000)]
    store.add_documents(dummy_chunks)
    for _ in range(50):
        store.search("Document query")

if __name__ == "__main__":
    profiler = cProfile.Profile()
    profiler.enable()
    run_workload()
    profiler.disable()

    stats = pstats.Stats(profiler).sort_stats("cumulative")
    stats.print_stats(20)  # Print top 20 time-consuming functions

Database Optimization: Eliminating N+1 Queries

# SLOW (N+1 queries: 1 query for users + N queries for documents)
users = db.query(User).all()
for u in users:
    print(u.documents) # Triggers a separate SQL query per user!

# FAST (Eager joined loading: 1 single SQL query)
from sqlalchemy.orm import selectinload
users = db.query(User).options(selectinload(User.documents)).all()

Pandas / NumPy Vectorization

# SLOW (Python iterative loop: ~250ms on 100k rows)
for idx, row in df.iterrows():
    df.at[idx, 'adjusted'] = row['val'] * 1.05 if row['flag'] == 1 else row['val']

# FAST (Vectorized boolean indexing: ~2ms on 100k rows - 125x faster)
df['adjusted'] = np.where(df['flag'] == 1, df['val'] * 1.05, df['val'])

4. What Decisions Should I Make?

Bottleneck TypeHighest-ROI Optimization
Slow Database QueryAdd B-Tree composite index on queried columns (WHERE a = ? AND b = ?).
Repetitive Expensive ComputationAdd In-Memory Cache with TTL (functools.lru_cache or Redis).
Slow JSON SerializationUse Pydantic v2 (Rust-backed core) or orjson instead of standard json.dumps.
Large DataFrame ProcessingSwitch from Pandas to Polars for multithreaded Arrow-backed query execution.

5. What Should I Avoid?

  • NEVER micro-optimize before profiling: Don't waste time rewriting readable string formatting when 95% of the time is spent waiting on a database query.
  • NEVER sacrifice code correctness or readability for negligible (< 5%) speedups.
  • NEVER cache without an invalidation or TTL strategy: Unbounded caches cause memory leaks and serve stale data.

6. How Should I Verify Success?

# 1. Benchmark endpoint response time
python -c "
import time, httpx
times = []
for _ in range(20):
    start = time.perf_counter()
    r = httpx.get('http://localhost:8000/api/v1/health')
    times.append(time.perf_counter() - start)
print(f'Average Latency: {sum(times)/len(times)*1000:.2f}ms | Min: {min(times)*1000:.2f}ms | Max: {max(times)*1000:.2f}ms')
"

# 2. Run full regression test suite
pytest -v

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.