Token导航 LogoToken导航

Agent Skill · 开发规范

k6-best-practices(k6 最佳实践)

k6-best-practices 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

k6-best-practices 是开发规范类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为接触敏感数据;许可证信息还不明确,第三方扫描有提醒项,按安装量在开发规范类的 1,265 个 Skill 里排第 631。

总安装 696周安装 29GitHub Stars 5下载 232核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:k6-best-practices(k6 最佳实践)
来源仓库:https://github.com/rcampos09/performance-testing-skills
仓库路径:skills/k6-best-practices
安装命令:
npx skills add https://github.com/rcampos09/performance-testing-skills --skill k6-best-practices
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/rcampos09/performance-testing-skills --skill k6-best-practices

这个 Skill 是做什么的

开发规范类 Skill 用来统一代码风格、目录结构和评审口径,产出多为检查清单或改写建议。

k6-best-practices 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在开发协作中整理项目状态和变更记录。适用于需要跟踪 k6 性能测试最佳实践相关的项目进展和代码变更。通过 npx skills add 命令从指定仓库安装,需确认权限范围和维护状态后再使用。

安装前建议核实是否会触发联网、命令执行或文件读写操作,避免影响系统安全。具体用法请结合原始 README 文档进一步核验功能细节和使用限制。

来源仓库内路径:skills/k6-best-practices

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/rcampos09/performance-testing-skills --skill k…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要接触敏感数据,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

k6-best-practices 怎么安装?

在终端执行 npx skills add https://github.com/rcampos09/performance-testing-skills --skill k6-best-pra…。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

k6-best-practices 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

k6-best-practices 需要什么权限?

权限级别是接触敏感数据。该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

k6-best-practices 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

k6-best-practices 用的人多吗?

公开数据是累计安装 696 次,近一周安装 29 次,下载 232 次,GitHub 5 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

k6-best-practices 安全吗?

第三方扫描有提醒项,说明存在需要人工确认的行为。安装前请打开源码看清它读了什么、联网到哪里。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。

先想清楚的地方

  • 需要接触敏感数据,装到常用环境前要先评估影响面。
  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方扫描存在提醒项或未通过项,需要人工逐条确认。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理开发规范类任务、又不想每次都手写提示词的人。

不太适合

  • 环境里有大量密钥、凭证,不方便给第三方 Skill 读取的人。
  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

开发规范类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
vercel-react-best-practices

Vercel React 最佳实践 · Codex、Claude

8,490,72025,918操作浏览器MIT通过
web-design-guidelines

网页设计指南 · Codex、Claude

6,686,01625,885需要联网MIT有提醒
remotion-best-practices

Remotion 最佳实践 · Codex、Claude

6,505,6323,027操作浏览器MIT有提醒
supabase-postgres-best-practices

Supabase Postgres 最佳实践 · Codex、Claude

3,175,5232,030需要联网MIT通过
next-best-practices

Next.js 最佳实践 · Codex、Claude

1,848,240841操作浏览器MIT通过
k6-best-practices

k6 最佳实践 · 本页

6965接触敏感数据未明确有提醒

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

k6 Scenario Builder

Enforces a consistent, production-ready pattern for k6 load test scripts using JavaScript or TypeScript, covering HTTP/REST, WebSocket, and gRPC protocols.

Output Format

When producing or fixing a script, always deliver three things:

  1. A complete, runnable script file — never a partial snippet.
  2. The exact run command with the environment variables needed.
  3. A one-line explanation of the executor chosen and why it fits the load goal.

When fixing any OOM error or open() misuse, cover both failure modes — even if the user only mentioned one:

  • Plain variable at init context → OOM (data copied per VU). Fix: SharedArray.
  • open() inside default() → immediate runtime error (can't call open() in the VU context). Fix: move to init context.

Step 1 — Gather Context

Ask only what is unknown:

  • Language: JavaScript (default) · TypeScript
  • Protocol: HTTP/REST · WebSocket · gRPC
  • Goal: New script · Fix existing script · Specific DSL question
  • Workload model: Fixed concurrent users (closed) or fixed arrival rate in RPS (open)?

Only load references/EXECUTORS.md when the user asks about executor types, workload models, scenario configuration, multi-scenario orchestration, or startTime/exec/gracefulStop parameters.

Only load references/PROTOCOLS.md when the user mentions WebSocket or gRPC. Contains connection setup, event handling, streaming DSL, and gotchas.

Only load references/DESIGN-PATTERNS.md when the user asks about folder structure, project architecture, sharing data between VUs, TypeScript setup, scaling beyond a single file, modular structure, reusable helpers, multi-step user flows (e-commerce, checkout, login+browse), or multiple scenarios sharing common logic.


Step 2 — Apply the 5-Block Pattern

Every k6 script must have these five blocks in order. Generate the complete skeleton first, then fill in details.

Block 1 → Options     scenarios + thresholds (executor, VUs, duration, SLA gates)
Block 2 → Data        SharedArray for parameterized inputs — loaded once, shared across VUs
Block 3 → Setup       one-time auth or preparation — runs once before VUs start
Block 4 → Default fn  the VU workload: requests, checks, groups, sleep
Block 5 → Teardown    cleanup (optional — required for gRPC/WS connection close)

Common Mistakes — Check Every Script for These

1. No sleep() between requests — generates unrealistic load

Without think time, VUs hammer the server at maximum speed. Always add sleep() between logical steps.

// Wrong — zero think time, unrealistic throughput
export default function() {
  http.get(`${BASE_URL}/api/products`);
  http.get(`${BASE_URL}/api/cart`);
}

// Correct — realistic think time between steps
import { sleep } from 'k6';

export default function() {
  http.get(`${BASE_URL}/api/products`);
  sleep(Math.random() * 2 + 1);  // 1–3s think time
  http.get(`${BASE_URL}/api/cart`);
  sleep(1);
}

2. check() as a test gate — it never fails the test

check() records pass/fail statistics but never stops or fails the test. This is the most common k6 misconception. Use thresholds to actually fail.

// Wrong — test always exits 0 even if every request returns 500
check(res, { 'status is 200': (r) => r.status === 200 });

// Correct — thresholds fail the test; check() provides per-request diagnostics
export const options = {
  thresholds: {
    http_req_failed:   ['rate<0.01'],   // < 1% errors — fails test if breached
    http_req_duration: ['p(95)<500'],   // p95 < 500ms — fails test if breached
    checks:            ['rate>0.99'],   // > 99% checks pass
  },
};
check(res, { 'status is 200': (r) => r.status === 200 });  // keep for diagnostics

Three failure mechanisms:

  • check() — per-iteration assertion, records stats, never stops the test
  • threshold — aggregate SLA gate, fails the test on breach (exit code 99)
  • fail(msg) — stops the current iteration immediately, use for unrecoverable errors

3. Hardcoded base URL — breaks multi-environment usage

// Wrong
const res = http.get('https://hardcoded-prod.example.com/api/users');

// Correct — parameterize all environment-specific values
const BASE_URL = __ENV.BASE_URL || 'https://staging.example.com';

Run: k6 run --env BASE_URL=https://prod.example.com script.js

4. Storing test data in a plain variable — multiplied per VU

Any variable declared at init context scope is copied once per VU. For a 50 MB JSON file with 200 VUs, that is 10 GB of RAM. Use SharedArray — loaded once, shared across all VUs as read-only.

// Wrong — 50 MB × 200 VUs = 10 GB RAM
import { open } from 'k6';  // open() is init-context only
const users = JSON.parse(open('./data/users.json'));  // per-VU copy

// Correct — 50 MB total regardless of VU count
import { SharedArray } from 'k6/data';
const users = new SharedArray('users', () => JSON.parse(open('./data/users.json')));

Two open() errors to always explain together:

  • Plain variable at init context → OOM (per-VU copy). Fix: SharedArray.
  • open() inside default() → runtime error (can't call open() in the VU context). Fix: move to init context.

5. Imports not at the top of the file — breaks convention and readability

All import statements must be the very first lines of the file — before export const options, before SharedArray, before any other code. ES modules technically hoist imports regardless of position, but placing them anywhere else creates scripts that are hard to read and breaks the init-context mental model.

// Wrong — imports scattered between blocks
export const options = { ... };         // ❌ options before imports

import { SharedArray } from 'k6/data'; // ❌ import mid-file
const users = new SharedArray(...);

import http from 'k6/http';            // ❌ another import even later
import { check, sleep } from 'k6';

// Correct — all imports first, then options, then data, then functions
import http                        from 'k6/http';
import { check, group, sleep, fail } from 'k6';
import { SharedArray }             from 'k6/data';

export const options = { ... };

const users = new SharedArray('users', () => JSON.parse(open('./data/users.json')));

export default function() { ... }

6. ramping-vus for a fixed RPS target — wrong workload model

ramping-vus controls concurrent users (closed model). Throughput varies with response time. For a fixed RPS goal, use constant-arrival-rate.

// Wrong for "maintain 100 RPS" — actual RPS drops when server is slow
executor: 'ramping-vus', stages: [{ duration: '5m', target: 100 }]

// Correct — arrival rate is constant regardless of response time
executor: 'constant-arrival-rate',
rate: 100,
timeUnit: '1s',
duration: '5m',
preAllocatedVUs: 50,   // rule: ceil(rate × p95_seconds × 1.2)
maxVUs: 200,

7. Under-sized preAllocatedVUs — silent dropped iterations

constant-arrival-rate drops iterations when VUs run out. Monitor dropped_iterations in output.

preAllocatedVUs = ceil(rate × p95_response_time_in_seconds × 1.2)
Example: 100 RPS, p95 = 400ms → ceil(100 × 0.4 × 1.2) = 48 → use 50

8. gracefulStop shorter than p99 response time — inflated errors

k6 waits gracefulStop duration after the test ends for in-flight iterations to complete. If p99 is 2s and gracefulStop is the default 30s, you are fine. But if p99 is 45s (batch job), set gracefulStop: '60s' explicitly.

scenarios: {
  load: {
    executor: 'constant-vus',
    vus: 100,
    duration: '5m',
    gracefulStop: '60s',   // set to at least 2× p99 response time
  }
}

9. One shared token for all VUs — all users share the same identity

setup() runs once before all VUs start. A token returned from setup() is shared by every VU — they all authenticate as the same user, producing unrealistic server-side behavior (single session, no per-user data isolation).

// Wrong — 100 VUs, all acting as the same user
export function setup() {
  const res = http.post(`${BASE_URL}/auth/login`, JSON.stringify({ username: 'admin', password: 'secret' }), ...);
  return { token: res.json('access_token') };  // shared by all VUs
}

// Correct — each VU logs in with its own credentials from SharedArray
import { SharedArray } from 'k6/data';
const credentials = new SharedArray('creds', () => JSON.parse(open('./data/users.json')));

export default function() {
  const cred = credentials[(__VU - 1) % credentials.length];  // deterministic per VU
  const res = http.post(`${BASE_URL}/auth/login`,
    JSON.stringify({ username: cred.username, password: cred.password }),
    { headers: { 'Content-Type': 'application/json' } }
  );
  const token = res.json('access_token');
  // use token for subsequent requests in this iteration
}

Use setup() only for shared, stateless initialization (e.g., seeding a test dataset via an admin API call).

10. Missing Content-Type on POST — server returns 415

// Wrong — 415 Unsupported Media Type
http.post(`${BASE_URL}/api/users`, JSON.stringify({ name: 'Alice' }));

// Correct
http.post(`${BASE_URL}/api/users`, JSON.stringify({ name: 'Alice' }), {
  headers: { 'Content-Type': 'application/json' },
});

The 5-Block Pattern — Reference

Block 1: Options

export const options = {
  scenarios: {
    load: {
      executor:         'ramping-vus',
      startVUs:         0,
      stages: [
        { duration: '2m', target: 50 },   // ramp up
        { duration: '5m', target: 50 },   // hold
        { duration: '2m', target: 0  },   // ramp down
      ],
      gracefulRampDown: '30s',
      gracefulStop:     '30s',
    },
  },
  thresholds: {
    http_req_duration: ['p(95)<500', 'p(99)<1000'],
    http_req_failed:   ['rate<0.01'],
    checks:            ['rate>0.99'],
  },
};

Block 2: Data (SharedArray)

import { SharedArray } from 'k6/data';

// JSON file
const users = new SharedArray('users', () => JSON.parse(open('./data/users.json')));

// CSV file (manual parse — k6 has no built-in CSV parser)
const csvUsers = new SharedArray('csv-users', () =>
  open('./data/users.csv')
    .split('\n')
    .slice(1)                                   // skip header row
    .filter(line => line.trim().length > 0)
    .map(line => {
      const [username, password] = line.split(',');
      return { username: username.trim(), password: password.trim() };
    })
);

// Access pattern — deterministic: each VU always uses the same record
const user = users[(__VU - 1) % users.length];

// Access pattern — random: any VU may pick any record
const user = users[Math.floor(Math.random() * users.length)];

Block 3: Setup

const BASE_URL = __ENV.BASE_URL || 'https://staging.example.com';

export function setup() {
  // Use only for stateless, shared initialization — NOT per-VU auth
  const res = http.post(`${BASE_URL}/api/seed`, null, {
    headers: { Authorization: `Bearer ${__ENV.ADMIN_TOKEN}` },
  });
  if (res.status !== 200) {
    fail(`Seed failed: ${res.status} — aborting test`);
  }
  return { seedId: res.json('id') };
}

Block 4: Default Function (VU workload)

import http         from 'k6/http';
import { group, check, sleep } from 'k6';

export default function(data) {
  const cred  = users[(__VU - 1) % users.length];
  const token = login(cred);   // per-VU auth

  group('Browse', () => {
    const res = http.get(`${BASE_URL}/api/products`, {
      headers: { Authorization: `Bearer ${token}` },
      tags:    { endpoint: 'products' },
    });
    check(res, {
      'products 200':       (r) => r.status === 200,
      'products not empty': (r) => r.json('#') > 0,
      'products < 500ms':   (r) => r.timings.duration < 500,
    });
    sleep(Math.random() * 2 + 1);
  });

  group('Checkout', () => {
    const res = http.post(`${BASE_URL}/api/orders`,
      JSON.stringify({ productId: data.seedId }),
      { headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
        tags: { endpoint: 'checkout' } }
    );
    check(res, {
      'order created 201': (r) => r.status === 201,
      'order has id':      (r) => r.json('id') !== undefined,
    });
    sleep(1);
  });
}

Block 5: Teardown

export function teardown(data) {
  // Clean up seed data
  http.del(`${BASE_URL}/api/seed/${data.seedId}`, null, {
    headers: { Authorization: `Bearer ${__ENV.ADMIN_TOKEN}` },
  });
}

Executor Selection Guide

Closed model — controls concurrent users. Use when connection count or session state matters.

ExecutorWhen to useRequired params
constant-vusSteady-state, fixed concurrencyvus, duration
ramping-vusRamp up/down, standard load teststages, startVUs
per-vu-iterationsEach VU runs exactly N iterationsvus, iterations, maxDuration
shared-iterationsExactly N total iterations across all VUsvus, iterations, maxDuration

Open model — controls arrival rate. Use for public APIs where RPS is the goal.

ExecutorWhen to useRequired params
constant-arrival-rateFixed RPS targetrate, timeUnit, preAllocatedVUs, maxVUs, duration
ramping-arrival-rateEscalating RPS (stress test)stages, timeUnit, preAllocatedVUs, maxVUs
externally-controlledLive VU adjustment via REST APIvus, maxVUs, duration

Default choice: ramping-vus. Switch to constant-arrival-rate when the SLA is expressed in RPS.


Thresholds Reference

export const options = {
  thresholds: {
    // Global response time
    http_req_duration: ['p(95)<500', 'p(99)<1000'],

    // Per-tagged endpoint (tag set on the request)
    'http_req_duration{endpoint:checkout}': ['p(99)<2000'],

    // Error rate
    http_req_failed: ['rate<0.01'],

    // Check pass rate
    checks: ['rate>0.99'],

    // Throughput floor
    http_reqs: ['rate>50'],

    // Custom metric
    'checkout_duration_ms': ['p(95)<300'],
  },
};

// Abort test early if a threshold is breached:
export const options = {
  thresholds: {
    http_req_duration: [
      { threshold: 'p(95)<500', abortOnFail: true, delayAbortEval: '1m' },
      // delayAbortEval: wait 1m before evaluating — avoids aborting during ramp-up
    ],
  },
};

Custom Metrics

import { Counter, Gauge, Trend, Rate } from 'k6/metrics';

const checkoutMs   = new Trend('checkout_duration_ms');
const authErrors   = new Counter('auth_errors_total');
const cacheHits    = new Rate('cache_hit_rate');

export default function(data) {
  const start = Date.now();
  const body  = JSON.stringify({ productId: '123' });
  const res   = http.post(`${BASE_URL}/api/orders`, body, {
    headers: { 'Content-Type': 'application/json',
               Authorization: `Bearer ${data.token}` },
    tags: { endpoint: 'checkout' },
  });

  checkoutMs.add(Date.now() - start, { step: 'payment' });
  if (res.status === 401) authErrors.add(1);
  cacheHits.add(res.headers['X-Cache'] === 'HIT');
}

Run Commands

# Basic run
k6 run script.js

# Override VUs and duration from CLI (useful for quick smoke test)
k6 run --vus 2 --duration 30s script.js

# Pass environment variables
k6 run --env BASE_URL=https://staging.example.com \
       --env USERNAME=perf_user \
       --env PASSWORD=secret \
       script.js

# Output to JSON for post-analysis
k6 run --out json=results.json script.js

# Output to InfluxDB + Grafana
k6 run --out influxdb=http://localhost:8086/k6 script.js

# TypeScript — compile first, then run the output
npx esbuild src/load.ts --bundle --outfile=dist/load.js --target=es2015
k6 run dist/load.js

# Grafana Cloud execution
k6 cloud run script.js

References

平台分布

Codex

37.05%
按下载量换算86

Claude

30.9%
按下载量换算72

Cursor

18.45%
按下载量换算43

Gemini CLI

9.43%
按下载量换算22

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

可疑

权限和风险

接触敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在提醒或未通过项,安装前请自行复核。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills