[TERMINAL · SKILLS]
> mounting /skills...
> indexing skill manifests...
> linking agents: claude · codex · gemini · cursor
> ready.
[░░░░░░░░░░░░░░░░░░░░░░░░░░░░] 0%
Use Cases/Build an Automated Load Testing Framework

Build an Automated Load Testing Framework

Catch performance regressions before production with automated load tests that run on every PR — simulating 10K concurrent users and comparing latency against baselines to prevent the next outage.

Development#typescript#tsconfig#type-checking#type-safety#javascript-migration
Works with:claude-codeopenai-codexgemini-clicursor

Skills stack · 7 skills

Avg quality 97/100·All SAFE
>

typescript

v1.0.0

Sets up and repairs TypeScript projects: picks tsconfig.json settings for a Node.js service, an npm library or a bundled web app, runs type-checking in CI, and replaces `any` and unsafe casts with types the compiler can verify. Use when someone asks to "set up TypeScript", "fix this tsconfig", "fix a TypeScript error", "upgrade to TypeScript 6 or 7", "migrate JavaScript to TypeScript", "publish types for a package", "run .ts files in Node" or "make this type-safe". Covers the changed defaults in TypeScript 6.0 and 7.0, module and moduleResolution, strict mode, project references, declaration output, narrowing, satisfies and common compiler errors.

93/100 quality
7.30× impact
SAFE· stale score
View skill
>

github-actions

v1.1.0

GitHub Actions runs CI/CD pipelines defined as YAML workflows inside a GitHub repository. Use when someone asks to "set up CI", "add a GitHub Actions workflow", "run tests on every pull request", "cache dependencies", "build a matrix", "deploy from Actions", "push a Docker image to ghcr.io" or "reuse a workflow", or needs triggers, secrets, environments, artifacts and permissions explained.

100/100 quality
2.66× impact
SAFE· stale score
View skill
>

docker-helper

v1.1.0

Build, debug, and optimize Docker configurations. Use when a user asks to create a Dockerfile, fix Docker build errors, optimize image size, write docker-compose files, debug container issues, set up multi-stage builds, or troubleshoot networking between containers. Covers Dockerfile best practices and compose orchestration.

100/100 quality
1.44× impact
SAFE· stale score
View skill
>

redis

v1.1.0

Redis is an in-memory data store used as a cache, session store, message broker and counter service. Use when adding a cache layer, storing sessions, rate limiting an API, running pub/sub or Streams with consumer groups, taking a distributed lock, building a leaderboard, or configuring Redis for production (persistence, maxmemory, eviction).

93/100 quality
1.79× impact
SAFE· stale score
View skill
>

postgresql

v1.1.0

Assists with designing schemas, writing performant queries, managing indexes, and operating PostgreSQL databases. Use when working with JSONB, full-text search, window functions, CTEs, row-level security, replication, or performance tuning. Trigger words: postgresql, postgres, sql, database, jsonb, rls, window functions, cte.

100/100 quality
5.15× impact
SAFE· stale score
View skill
>

zod

v1.1.0

Zod is a TypeScript-first schema library that validates data at runtime and infers static types from the same schema. Use when validating API request bodies, form input, environment variables or config files, parsing untrusted JSON, or migrating from Zod 3 to Zod 4. Covers z.object, safeParse, z.infer, coercion, discriminated unions, refinements, JSON Schema output and the v4 API changes.

93/100 quality
3.87× impact
SAFE· stale score
View skill
>

hono

v1.1.0

Hono is a small web framework built on Web Standards (Request/Response) that runs unchanged on Cloudflare Workers, Deno, Bun, Node.js, AWS Lambda and Vercel. Use it when the user asks to build a Hono API, add Zod validation, JWT auth, CORS or middleware, use the type-safe RPC client (hc), render JSX, stream responses, or deploy one codebase to several runtimes.

100/100 quality
6.20× impact
SAFE· stale score
View skill
$

The Problem

A SaaS API handles 5K requests/second at peak. Performance issues are only discovered in production: last month, a new database query doubled p99 latency from 200ms to 400ms, triggering SLA violations for 3 enterprise customers ($15K in credits). The team has a k6 script someone wrote 8 months ago, but nobody runs it. Manual load testing happens "when we remember" — roughly never. Every deployment is a gamble.

Step 1: Test Scenario Definition

typescript
// src/loadtest/scenarios.ts
import { z } from 'zod';

const LoadTestScenario = z.object({
  name: z.string(),
  description: z.string(),
  stages: z.array(z.object({
    duration: z.string(),       // "30s", "2m"
    target: z.number().int(),   // concurrent users
  })),
  endpoints: z.array(z.object({
    method: z.enum(['GET', 'POST', 'PUT', 'DELETE', 'PATCH']),
    path: z.string(),
    weight: z.number().min(0).max(1), // traffic distribution
    body: z.unknown().optional(),
    headers: z.record(z.string(), z.string()).optional(),
    expectedStatus: z.number().int().default(200),
  })),
  thresholds: z.object({
    p95LatencyMs: z.number(),
    p99LatencyMs: z.number(),
    errorRate: z.number(),       // max acceptable (e.g., 0.01 = 1%)
    rps: z.number().optional(),  // minimum requests/second
  }),
});

export const scenarios: z.infer<typeof LoadTestScenario>[] = [
  {
    name: 'api-smoke',
    description: 'Quick smoke test for PR validation (30s)',
    stages: [
      { duration: '10s', target: 50 },
      { duration: '10s', target: 100 },
      { duration: '10s', target: 0 },
    ],
    endpoints: [
      { method: 'GET', path: '/api/v1/users/me', weight: 0.3, expectedStatus: 200 },
      { method: 'GET', path: '/api/v1/projects', weight: 0.25, expectedStatus: 200 },
      { method: 'POST', path: '/api/v1/tasks', weight: 0.15, body: { title: 'Load test task', projectId: '{{projectId}}' }, expectedStatus: 201 },
      { method: 'GET', path: '/api/v1/tasks?limit=20', weight: 0.2, expectedStatus: 200 },
      { method: 'GET', path: '/api/v1/search?q=test', weight: 0.1, expectedStatus: 200 },
    ],
    thresholds: {
      p95LatencyMs: 300,
      p99LatencyMs: 500,
      errorRate: 0.01,
    },
  },
  {
    name: 'api-soak',
    description: 'Full soak test for release candidates (10m)',
    stages: [
      { duration: '1m', target: 500 },
      { duration: '5m', target: 1000 },
      { duration: '2m', target: 2000 },
      { duration: '2m', target: 0 },
    ],
    endpoints: [
      { method: 'GET', path: '/api/v1/users/me', weight: 0.2, expectedStatus: 200 },
      { method: 'GET', path: '/api/v1/projects', weight: 0.2, expectedStatus: 200 },
      { method: 'POST', path: '/api/v1/tasks', weight: 0.1, body: { title: 'Soak test' }, expectedStatus: 201 },
      { method: 'GET', path: '/api/v1/tasks?limit=50', weight: 0.2, expectedStatus: 200 },
      { method: 'GET', path: '/api/v1/search?q=test', weight: 0.15, expectedStatus: 200 },
      { method: 'GET', path: '/api/v1/analytics/dashboard', weight: 0.15, expectedStatus: 200 },
    ],
    thresholds: {
      p95LatencyMs: 250,
      p99LatencyMs: 500,
      errorRate: 0.005,
      rps: 2000,
    },
  },
];

Step 2: Load Generator

typescript
// src/loadtest/runner.ts
import { z } from 'zod';

interface RunResult {
  scenario: string;
  duration: number;
  totalRequests: number;
  successfulRequests: number;
  failedRequests: number;
  rps: number;
  latency: {
    min: number; max: number; avg: number; median: number; p95: number; p99: number;
  };
  errorRate: number;
  thresholdsPassed: boolean;
  endpointResults: Array<{
    endpoint: string;
    requests: number;
    avgLatency: number;
    p95Latency: number;
    errorRate: number;
  }>;
}

export async function runLoadTest(
  baseUrl: string,
  scenario: any,
  authToken: string
): Promise<RunResult> {
  const latencies: number[] = [];
  const errors: string[] = [];
  const endpointStats = new Map<string, { latencies: number[]; errors: number; total: number }>();

  const startTime = Date.now();
  let totalRequests = 0;

  for (const stage of scenario.stages) {
    const durationMs = parseDuration(stage.duration);
    const stageEnd = Date.now() + durationMs;
    const concurrency = stage.target;

    while (Date.now() < stageEnd) {
      const batch = Array.from({ length: Math.min(concurrency, 50) }, async () => {
        // Pick endpoint by weight
        const endpoint = pickWeighted(scenario.endpoints);
        const key = `${endpoint.method} ${endpoint.path}`;

        if (!endpointStats.has(key)) {
          endpointStats.set(key, { latencies: [], errors: 0, total: 0 });
        }
        const stats = endpointStats.get(key)!;

        const reqStart = Date.now();
        try {
          const res = await fetch(`${baseUrl}${endpoint.path}`, {
            method: endpoint.method,
            headers: {
              Authorization: `Bearer ${authToken}`,
              'Content-Type': 'application/json',
              ...endpoint.headers,
            },
            body: endpoint.body ? JSON.stringify(endpoint.body) : undefined,
            signal: AbortSignal.timeout(10000),
          });

          const latency = Date.now() - reqStart;
          latencies.push(latency);
          stats.latencies.push(latency);
          stats.total++;
          totalRequests++;

          if (res.status !== endpoint.expectedStatus) {
            errors.push(`${key}: expected ${endpoint.expectedStatus}, got ${res.status}`);
            stats.errors++;
          }
        } catch (err: any) {
          stats.errors++;
          stats.total++;
          errors.push(`${key}: ${err.message}`);
          totalRequests++;
        }
      });

      await Promise.allSettled(batch);
      await new Promise(r => setTimeout(r, 100)); // pace
    }
  }

  const duration = Date.now() - startTime;
  latencies.sort((a, b) => a - b);

  const result: RunResult = {
    scenario: scenario.name,
    duration,
    totalRequests,
    successfulRequests: totalRequests - errors.length,
    failedRequests: errors.length,
    rps: Math.round(totalRequests / (duration / 1000)),
    latency: {
      min: latencies[0] ?? 0,
      max: latencies[latencies.length - 1] ?? 0,
      avg: Math.round(latencies.reduce((a, b) => a + b, 0) / latencies.length || 0),
      median: latencies[Math.floor(latencies.length * 0.5)] ?? 0,
      p95: latencies[Math.floor(latencies.length * 0.95)] ?? 0,
      p99: latencies[Math.floor(latencies.length * 0.99)] ?? 0,
    },
    errorRate: totalRequests > 0 ? errors.length / totalRequests : 0,
    thresholdsPassed: false,
    endpointResults: [...endpointStats.entries()].map(([endpoint, stats]) => ({
      endpoint,
      requests: stats.total,
      avgLatency: Math.round(stats.latencies.reduce((a, b) => a + b, 0) / stats.latencies.length || 0),
      p95Latency: stats.latencies.sort((a, b) => a - b)[Math.floor(stats.latencies.length * 0.95)] ?? 0,
      errorRate: stats.total > 0 ? stats.errors / stats.total : 0,
    })),
  };

  // Check thresholds
  result.thresholdsPassed =
    result.latency.p95 <= scenario.thresholds.p95LatencyMs &&
    result.latency.p99 <= scenario.thresholds.p99LatencyMs &&
    result.errorRate <= scenario.thresholds.errorRate;

  return result;
}

function parseDuration(d: string): number {
  const match = d.match(/^(\d+)(s|m|h)$/);
  if (!match) return 10000;
  const val = parseInt(match[1]);
  const unit = match[2];
  return val * (unit === 's' ? 1000 : unit === 'm' ? 60000 : 3600000);
}

function pickWeighted(endpoints: any[]): any {
  const r = Math.random();
  let sum = 0;
  for (const ep of endpoints) {
    sum += ep.weight;
    if (r < sum) return ep;
  }
  return endpoints[endpoints.length - 1];
}

Results

  • The 2x latency regression: caught in PR CI — PR blocked before merge
  • p99 latency regression detection: automated baseline comparison on every PR
  • SLA violations: zero in 6 months (was 3 incidents causing $15K credits)
  • Load test coverage: every PR runs 30-second smoke test, releases get 10-minute soak
  • Performance budgets: team discusses p95 targets, not "it feels fast enough"
  • Confidence: Friday deploys are no longer scary
  • Historical trends: latency data stored — see performance over time

Related use cases