Skip to content
cccskills
FreePublished on GitHub

performance-tuner

Performance optimization, profiling, caching strategies, lazy loading, bundle optimization, and monitoring. Use when optimizing application performance, reducing bundle size, implementing caching, or analyzing bottlenecks.

The English summary is being prepared. Showing the original description.

Works withRedis
See how to install

Files included (1)

  • SKILL.md5.4 KB

SKILL.md (original)

Review the instructions the agent will receive before you install.

Performance Tuner

Caching Strategies

Redis Caching

import { Redis } from 'ioredis';

export class CacheManager {
  private redis = new Redis(process.env.REDIS_URL);
  
  async get<T>(key: string): Promise<T | null> {
    const data = await this.redis.get(key);
    return data ? JSON.parse(data) : null;
  }
  
  async set<T>(key: string, value: T, ttl: number): Promise<void> {
    await this.redis.setex(key, ttl, JSON.stringify(value));
  }
  
  async getOrSet<T>(
    key: string,
    factory: () => Promise<T>,
    ttl: number
  ): Promise<T> {
    const cached = await this.get<T>(key);
    if (cached) return cached;
    
    const value = await factory();
    await this.set(key, value, ttl);
    return value;
  }
}

// Usage with stale-while-revalidate
export class SWRCache {
  async get<T>(key: string): Promise<T> {
    const [fresh, stale] = await Promise.all([
      this.redis.get(`fresh:${key}`),
      this.redis.get(`stale:${key}`)
    ]);
    
    if (fresh) return JSON.parse(fresh);
    
    // Trigger revalidation in background
    if (stale) {
      this.revalidate(key);
      return JSON.parse(stale);
    }
    
    return this.fetchAndCache(key);
  }
}

HTTP Caching Headers

export function setCacheHeaders(
  res: Response,
  options: CacheOptions
) {
  if (options.swr) {
    res.setHeader('Cache-Control', 
      `public, s-maxage=${options.stale}, stale-while-revalidate=${options.revalidate}`
    );
  } else if (options.immutable) {
    res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
  } else {
    res.setHeader('Cache-Control', `public, max-age=${options.maxAge}`);
  }
}

Bundle Optimization

Dynamic Imports

// Lazy load heavy components
const HeavyChart = dynamic(() => import('./HeavyChart'), {
  loading: () => <ChartSkeleton />,
  ssr: false // Disable SSR for browser-only libraries
});

// Preload on hover
function LinkWithPreload({ href, children }) {
  return (
    <Link 
      href={href}
      onMouseEnter={() => {
        const Component = dynamic(() => import(`./pages${href}`));
      }}
    >
      {children}
    </Link>
  );
}

Tree Shaking

// ✅ Good: Named imports
import { map, filter } from 'lodash-es';

// ❌ Bad: Full import
import _ from 'lodash';

// ✅ Good: Barrel exports with care
export { Button } from './Button';
export { Input } from './Input';

Database Query Optimization

Query Analysis

// Explain query plans
const explain = await db.execute(sql`
  EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)
  SELECT * FROM users WHERE email = ${email}
`);

// Index usage check
const indexUsage = await db.execute(sql`
  SELECT 
    schemaname,
    tablename,
    attname as column,
    n_tup_read,
    n_tup_fetch
  FROM pg_stats
  WHERE tablename = 'users'
`);

Connection Pooling

import { Pool } from 'pg';

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  max: 20,                    // Maximum pool size
  idleTimeoutMillis: 30000,   // Close idle connections
  connectionTimeoutMillis: 2000,
  application_name: 'trinity_app'
});

// Monitor pool
pool.on('connect', () => console.log('New client connected'));
pool.on('error', (err) => console.error('Pool error:', err));

Image Optimization

Next.js Image

import Image from 'next/image';

<Image
  src="/hero.jpg"
  alt="Hero"
  width={1200}
  height={600}
  priority // Above-the-fold images
  placeholder="blur"
  blurDataURL="data:image/jpeg;base64,..."
/>

Responsive Images

<Image
  src="/photo.jpg"
  alt="Photo"
  sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
  fill
  className="object-cover"
/>

Performance Monitoring

Web Vitals

import { getCLS, getFID, getFCP, getLCP, getTTFB } from 'web-vitals';

function sendToAnalytics(metric) {
  const body = JSON.stringify(metric);
  (navigator.sendBeacon && navigator.sendBeacon('/analytics', body)) ||
    fetch('/analytics', { body, method: 'POST', keepalive: true });
}

getCLS(sendToAnalytics);
getFID(sendToAnalytics);
getFCP(sendToAnalytics);
getLCP(sendToAnalytics);
getTTFB(sendToAnalytics);

Custom Metrics

export class PerformanceMonitor {
  measure(name: string, fn: () => Promise<T>): Promise<T> {
    const start = performance.now();
    
    return fn().finally(() => {
      const duration = performance.now() - start;
      
      // Send to monitoring
      this.report({
        name: `timing.${name}`,
        value: duration,
        unit: 'ms'
      });
    });
  }
}

Memory Management

WeakRef for Caching

class WeakCache<K, V extends object> {
  private cache = new Map<K, WeakRef<V>>();
  private finalizer = new FinalizationRegistry<K>(key => {
    this.cache.delete(key);
  });
  
  set(key: K, value: V) {
    this.cache.set(key, new WeakRef(value));
    this.finalizer.register(value, key);
  }
  
  get(key: K): V | undefined {
    const ref = this.cache.get(key);
    return ref?.deref();
  }
}

Reviews

No reviews yet. Tell others what you thought.

Comments

No login needed. Share how it worked for you, ask a question, or note where it did not run.

No comments yet. Be the first to write one.

Comments are published right away. Do not include personal information such as email addresses or phone numbers. Up to 2 URLs.

0 / 1,000 characters

This form is protected by reCAPTCHA, and the Google Privacy Policy and Terms of Service apply.

More skills from this repository

ai-sdk

Free

Vercel AI SDK expert guidance. Use when building AI-powered features — chat interfaces, text generation, structured output, tool calling, agents, MCP integration, streaming, embeddings, reranking, image generation, or working with any LLM provider.

The English summary is being prepared. Showing the original description.

garochee33/DSH4Updated Oct 19, 2026

Algorithm design and analysis skill for DSH; use when working on optimization, data structures, or computational procedures.

The English summary is being prepared. Showing the original description.

garochee33/DSH4Updated Oct 19, 2026

Design and implement scalable API gateways, RESTful APIs, GraphQL endpoints, WebSocket handlers, and microservice communication patterns. Use when creating API routes, designing endpoints, implementing middleware, or setting up service mesh architectures.

The English summary is being prepared. Showing the original description.

garochee33/DSH4Updated Oct 19, 2026

Implement a task N ways in parallel and pick the best. Spawns multiple subagents in isolated worktrees, evaluates all candidates, and applies the winner. Use when asked to "best of n", "try multiple approaches", "parallel implementations", "/best-of-n", or "/bon".

The English summary is being prepared. Showing the original description.

garochee33/DSH4Updated Oct 19, 2026

check

Free

Check your work with a verification subagent. Spawns a verifier that reviews diffs, runs builds and tests, and evaluates correctness. Use when asked to "check work", "verify changes", "self-verify", "/check", "/verify", "/check-work", or "/self-verify".

The English summary is being prepared. Showing the original description.

garochee33/DSH4Updated Oct 19, 2026

CI/CD pipeline design, GitHub Actions workflows, deployment automation, infrastructure as code, and release management. Use when setting up CI/CD, automating deployments, configuring build pipelines, or managing releases.

The English summary is being prepared. Showing the original description.

garochee33/DSH4Updated Oct 19, 2026

See all skills by garochee33

Report a problem with this skill