[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79EYHMS49DT1YCCWYJB2Y73":3,"skill-same:01M79EYHMS49DT1YCCWYJB2Y73":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M79EYHMS49DT1YCCWYJB2Y73","k6-and-locust-load-testing",null,"Production-grade load, stress, spike, and endurance testing using Grafana k6 and Python Locust. Use when designing performance test suites, defining SLAs\u002FSLOs, simulating distributed user traffic, and automating performance regression gates in CI\u002FCD pipelines.","hamzabellouch\u002Fagent-skills","hamzabellouch","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F237856042?v=4","01M79BRYW7XAMK3YDWQEMTWGWS","Hamza Bellouch","01M79BRYWXQV3JK2TGVTX8GN2A",8,"MIT","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FProgramming\u002FTesting_and_QA\u002FPerformance_and_Load_Testing\u002Fk6-and-locust-load-testing\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: k6-and-locust-load-testing\ndescription: Production-grade load, stress, spike, and endurance testing using Grafana k6 and Python Locust. Use when designing performance test suites, defining SLAs\u002FSLOs, simulating distributed user traffic, and automating performance regression gates in CI\u002FCD pipelines.\n---\n\n# k6 & Locust Load Testing Architecture & Best Practices\n\nThis skill provides comprehensive patterns, architectural guidelines, SLA validation thresholds, anti-patterns, and enterprise-grade code examples for high-throughput load and performance testing using **Grafana k6** (JavaScript\u002FTypeScript ES6) and **Python Locust**.\n\n---\n\n## 1. Core Concepts & Framework Selection\n\n| Capability | Grafana k6 | Python Locust |\n| :--- | :--- | :--- |\n| **Runtime \u002F Engine** | Go VM with JavaScript (Goja) | Python (Gevent async co-routines) |\n| **Resource Efficiency** | Extremely High (~1,000s of VUs per CPU core) | High (~100s-1000s VUs per worker node) |\n| **Scripting Language** | ES6 JavaScript \u002F TypeScript | Native Python |\n| **Protocol Support** | HTTP\u002F1.1, HTTP\u002F2, WebSockets, gRPC, Redis | Any protocol via Python SDK (HTTP, gRPC, WebSockets, Kafka, SQL) |\n| **CI\u002FCD Integration** | CLI native, exit codes on threshold breaches, k6 Cloud | CLI native, Locust Web UI \u002F Headless mode |\n| **Best Used For** | Protocol-level performance testing, high-concurrency benchmarks, CI\u002FCD automated gates | Complex user flows, Python ecosystem integration (ML models, Custom protocols, DB validation) |\n\n---\n\n## 2. Grafana k6 Implementation Standard\n\n### Architectural Principles\n1. **Separation of Concerns**: Split scenarios, test data generators, API client helpers, and SLA threshold definitions into modular files.\n2. **Deterministic Stages**: Model ramp-up, steady-state (plateau), and ramp-down using `scenarios` with specific executors (`ramping-arrival-rate`, `ramping-vus`).\n3. **Strict Thresholds**: Map metrics to strict Service Level Agreements (SLAs) so CI pipelines automatically fail when p95\u002Fp99 latency or error rates exceed budgets.\n\n### Production k6 Framework Example\n\n```javascript\nimport http from 'k6\u002Fhttp';\nimport { check, sleep } from 'k6';\nimport { Rate, Trend, Counter } from 'k6\u002Fmetrics';\n\n\u002F\u002F Custom Metrics\nconst errorRate = new Rate('custom_error_rate');\nconst apiLatency = new Trend('api_transaction_latency');\nconst totalOrders = new Counter('total_orders_created');\n\n\u002F\u002F SLA Thresholds & Execution Scenarios\nexport const options = {\n  scenarios: {\n    \u002F\u002F Ramping Arrival Rate (Open Model: controls throughput independent of target response times)\n    checkout_load_test: {\n      executor: 'ramping-arrival-rate',\n      startRate: 10,\n      timeUnit: '1s',\n      preAllocatedVUs: 50,\n      maxVUs: 500,\n      stages: [\n        { duration: '2m', target: 50 },  \u002F\u002F Ramp up to 50 req\u002Fsec\n        { duration: '5m', target: 50 },  \u002F\u002F Sustained load at 50 req\u002Fsec\n        { duration: '2m', target: 150 }, \u002F\u002F Spike to 150 req\u002Fsec\n        { duration: '5m', target: 150 }, \u002F\u002F Sustained spike\n        { duration: '2m', target: 0 },   \u002F\u002F Cool down\n      ],\n      gracefulStop: '30s',\n    },\n  },\n  thresholds: {\n    \u002F\u002F Global SLAs\n    'http_req_failed': ['rate\u003C0.01'],             \u002F\u002F Error rate \u003C 1%\n    'http_req_duration': ['p(95)\u003C300', 'p(99)\u003C800'], \u002F\u002F 95% \u003C 300ms, 99% \u003C 800ms\n    'custom_error_rate': ['rate\u003C0.005'],          \u002F\u002F Application error rate \u003C 0.5%\n    'api_transaction_latency': ['p(95)\u003C250'],     \u002F\u002F Transaction-specific SLA\n  },\n};\n\nconst BASE_URL = __ENV.BASE_URL || 'https:\u002F\u002Fapi.staging.example.com';\nconst AUTH_TOKEN = __ENV.AUTH_TOKEN || 'bearer-secret-token';\n\nexport function setup() {\n  \u002F\u002F Pre-test setup: Fetch reference data or seed test DB\n  const res = http.get(`${BASE_URL}\u002Fv1\u002Fhealth`, {\n    headers: { Authorization: AUTH_TOKEN },\n  });\n  check(res, { 'system healthy': (r) => r.status === 200 });\n  return { startTime: new Date().toISOString() };\n}\n\nexport default function (data) {\n  const payload = JSON.stringify({\n    item_id: 'prod_99182',\n    quantity: 1,\n    idempotency_key: `idempotency_${__VU}_${__ITER}_${Date.now()}`,\n  });\n\n  const params = {\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'Authorization': AUTH_TOKEN,\n      'X-Correlation-ID': `k6-test-${__VU}-${__ITER}`,\n    },\n    tags: { name: 'POST \u002Fv1\u002Forders' },\n  };\n\n  const startTime = Date.now();\n  const res = http.post(`${BASE_URL}\u002Fv1\u002Forders`, payload, params);\n  const duration = Date.now() - startTime;\n\n  \u002F\u002F Record metrics\n  apiLatency.add(duration);\n\n  const success = check(res, {\n    'status is 201 Created': (r) => r.status === 201,\n    'order ID present': (r) => r.json('order_id') !== undefined,\n    'response under 500ms': (r) => r.timings.duration \u003C 500,\n  });\n\n  if (success) {\n    totalOrders.add(1);\n    errorRate.add(false);\n  } else {\n    errorRate.add(true);\n  }\n\n  \u002F\u002F Pacing \u002F Think Time (Random jitter between 1s and 3s)\n  sleep(1 + Math.random() * 2);\n}\n\nexport function teardown(data) {\n  \u002F\u002F Clean up resources or output test execution metadata\n  console.log(`Test completed. Started at: ${data.startTime}`);\n}\n```\n\n---\n\n## 3. Python Locust Implementation Standard\n\n### Architectural Principles\n1. **User Behavior Modeling**: Group API flows into task sets with weights representing real user path distributions.\n2. **State Management**: Maintain user session state (auth tokens, basket contents) on the `User` instance.\n3. **Event Hooks**: Use `events.request` and `events.quitting` for customized SLA verification, metric shipping, or telemetry injection.\n\n### Production Locust Framework Example\n\n```python\nimport time\nimport uuid\nimport logging\nfrom locust import HttpUser, task, between, events, SequentialTaskSet\nfrom locust.exception import StopUser\n\nlogger = logging.getLogger(\"locust.loadtest\")\n\nclass UserCheckoutJourney(SequentialTaskSet):\n    \"\"\"Sequential tasks simulating an e-commerce purchasing journey.\"\"\"\n    \n    def on_start(self):\n        \"\"\"Executed when a Virtual User initiates this TaskSet.\"\"\"\n        self.client.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"User-Agent\": \"LocustLoadTest\u002F2.0\",\n        })\n        self.auth_token = self._authenticate()\n\n    def _authenticate(self) -> str:\n        with self.client.post(\n            \"\u002Fapi\u002Fv1\u002Fauth\u002Flogin\",\n            json={\"username\": \"load_user\", \"password\": \"secure_password\"},\n            catch_response=True,\n            name=\"\u002Fapi\u002Fv1\u002Fauth\u002Flogin\"\n        ) as response:\n            if response.status_code == 200:\n                token = response.json().get(\"access_token\")\n                self.client.headers[\"Authorization\"] = f\"Bearer {token}\"\n                return token\n            else:\n                response.failure(f\"Auth failed with status {response.status_code}\")\n                raise StopUser()\n\n    @task(3)\n    def browse_catalog(self):\n        with self.client.get(\n            \"\u002Fapi\u002Fv1\u002Fproducts?category=electronics&limit=20\",\n            catch_response=True,\n            name=\"\u002Fapi\u002Fv1\u002Fproducts\"\n        ) as response:\n            if response.status_code != 200:\n                response.failure(f\"Expected 200 OK, got {response.status_code}\")\n            elif response.elapsed.total_seconds() > 0.4:\n                response.failure(f\"SLA Breach: Latency > 400ms ({response.elapsed.total_seconds()}s)\")\n\n    @task(2)\n    def add_to_cart(self):\n        payload = {\"product_id\": \"p_88721\", \"quantity\": 1}\n        self.client.post(\"\u002Fapi\u002Fv1\u002Fcart\u002Fitems\", json=payload, name=\"\u002Fapi\u002Fv1\u002Fcart\u002Fitems\")\n\n    @task(1)\n    def checkout(self):\n        idempotency_key = str(uuid.uuid4())\n        headers = {\"X-Idempotency-Key\": idempotency_key}\n        \n        with self.client.post(\n            \"\u002Fapi\u002Fv1\u002Fcheckout\",\n            json={\"payment_method\": \"credit_card\"},\n            headers=headers,\n            catch_response=True,\n            name=\"\u002Fapi\u002Fv1\u002Fcheckout\"\n        ) as response:\n            if response.status_code == 201:\n                response.success()\n            else:\n                response.failure(f\"Checkout error: {response.text}\")\n\n\nclass ECommerceLoadUser(HttpUser):\n    \"\"\"Virtual User runner with weighted task distributions.\"\"\"\n    wait_time = between(1.5, 3.5)\n    tasks = [UserCheckoutJourney]\n    host = \"https:\u002F\u002Fapi.staging.example.com\"\n\n\n# Event Hooks for Custom Automated SLA Verification in Headless \u002F CI mode\n@events.quitting.add_listener\ndef verify_slas(environment, **kwargs):\n    stats = environment.stats.total\n    fail_ratio = stats.fail_ratio\n    p95 = stats.get_response_time_percentile(0.95)\n    p99 = stats.get_response_time_percentile(0.99)\n    \n    logger.info(f\"Test summary: Fail Ratio={fail_ratio:.4f}, p95={p95}ms, p99={p99}ms\")\n\n    # Automated Gate Criteria\n    sla_failed = False\n    if fail_ratio > 0.01:\n        logger.error(f\"SLA VIOLATION: Failure rate {fail_ratio * 100:.2f}% exceeds limit of 1.0%\")\n        sla_failed = True\n    if p95 > 300:\n        logger.error(f\"SLA VIOLATION: 95th percentile latency {p95}ms exceeds limit of 300ms\")\n        sla_failed = True\n    if p99 > 800:\n        logger.error(f\"SLA VIOLATION: 99th percentile latency {p99}ms exceeds limit of 800ms\")\n        sla_failed = True\n\n    if sla_failed:\n        environment.process_exit_code = 1\n```\n\n---\n\n## 4. SLA Verification & Threshold Metrics\n\nWhen designing enterprise performance tests, define SLAs based on standard 4 Golden Signals (Latency, Traffic, Errors, Saturation):\n\n| Metric | Target SLA Standard | k6 Threshold Expression | Locust Verification logic |\n| :--- | :--- | :--- | :--- |\n| **Http Failure Rate** | `\u003C 0.5%` | `'http_req_failed': ['rate\u003C0.005']` | `stats.fail_ratio \u003C 0.005` |\n| **p95 Latency** | `\u003C 250 ms` | `'http_req_duration': ['p(95)\u003C250']` | `stats.get_response_time_percentile(0.95) \u003C 250` |\n| **p99 Latency** | `\u003C 500 ms` | `'http_req_duration': ['p(99)\u003C500']` | `stats.get_response_time_percentile(0.99) \u003C 500` |\n| **Throughput (RPS)** | `> 500 RPS` | `'http_reqs': ['count>300000']` | `stats.total_rps >= 500` |\n\n---\n\n## 5. Anti-Patterns & Pitfalls to Avoid\n\n### 1. Closed Model vs Open Model Misunderstanding\n* **Anti-Pattern**: Using VU-based ramping (Closed Model) when simulating public HTTP endpoints. As response latency increases under load, VUs spend more time waiting for responses, decreasing throughput (RPS) and hiding performance degradation.\n* **Solution**: Use `ramping-arrival-rate` in k6 or Constant Throughput Timer models in Locust to enforce RPS regardless of system latency.\n\n### 2. Lack of Pacing \u002F Think Time\n* **Anti-Pattern**: Executing infinite tight loops without think times (`sleep()`), causing unrealistically high request rates per VU and overloading load generator network cards before target system limits are reached.\n* **Solution**: Apply realistic Poisson or uniform random think times (`sleep(1 + Math.random() * 2)` in k6 or `between(1, 3)` in Locust).\n\n### 3. Hardcoded Test Data & Shared Session IDs\n* **Anti-Pattern**: Re-using the same user ID or authentication token across 500 VUs, causing DB lock contention on a single row or hitting single-user rate limits.\n* **Solution**: Parameterize test data using JSON data files, synthetic UUID generation, or unique VU iteration identifiers (`__VU`, `__ITER`).\n\n### 6. Logging Overhead During High Load\n* **Anti-Pattern**: Using `console.log()` or `print()` inside the main test function for every request during a 10,000 VU load test, maxing out CPU I\u002FO.\n* **Solution**: Log only on failure conditions (`if (!success) { ... }`).\n","# k6 & Locust Load Testing Architecture & Best Practices\n\nThis skill provides comprehensive patterns, architectural guidelines, SLA validation thresholds, anti-patterns, and enterprise-grade code examples for high-throughput load and performance testing using **Grafana k6** (JavaScript\u002FTypeScript ES6) and **Python Locust**.\n\n---\n\n## 1. Core Concepts & Framework Selection\n\n| Capability | Grafana k6 | Python Locust |\n| :--- | :--- | :--- |\n| **Runtime \u002F Engine** | Go VM with JavaScript (Goja) | Python (Gevent async co-routines) |\n| **Resource Efficiency** | Extremely High (~1,000s of VUs per CPU core) | High (~100s-1000s VUs per worker node) |\n| **Scripting Language** | ES6 JavaScript \u002F TypeScript | Native Python |\n| **Protocol Support** | HTTP\u002F1.1, HTTP\u002F2, WebSockets, gRPC, Redis | Any protocol via Python SDK (HTTP, gRPC, WebSockets, Kafka, SQL) |\n| **CI\u002FCD Integration** | CLI native, exit codes on threshold breaches, k6 Cloud | CLI native, Locust Web UI \u002F Headless mode |\n| **Best Used For** | Protocol-level performance testing, high-concurrency benchmarks, CI\u002FCD automated gates | Complex user flows, Python ecosystem integration (ML models, Custom protocols, DB validation) |\n\n---\n\n## 2. Grafana k6 Implementation Standard\n\n### Architectural Principles\n1. **Separation of Concerns**: Split scenarios, test data generators, API client helpers, and SLA threshold definitions into modular files.\n2. **Deterministic Stages**: Model ramp-up, steady-state (plateau), and ramp-down using `scenarios` with specific executors (`ramping-arrival-rate`, `ramping-vus`).\n3. **Strict Thresholds**: Map metrics to strict Service Level Agreements (SLAs) so CI pipelines automatically fail when p95\u002Fp99 latency or error rates exceed budgets.\n\n### Production k6 Framework Example\n\n```javascript\nimport http from 'k6\u002Fhttp';\nimport { check, sleep } from 'k6';\nimport { Rate, Trend, Counter } from 'k6\u002Fmetrics';\n\n\u002F\u002F Custom Metrics\nconst errorRate = new Rate('custom_error_rate');\nconst apiLatency = new Trend('api_transaction_latency');\nconst totalOrders = new Counter('total_orders_created');\n\n\u002F\u002F SLA Thresholds & Execution Scenarios\nexport const options = {\n  scenarios: {\n    \u002F\u002F Ramping Arrival Rate (Open Model: controls throughput independent of target response times)\n    checkout_load_test: {\n      executor: 'ramping-arrival-rate',\n      startRate: 10,\n      timeUnit: '1s',\n      preAllocatedVUs: 50,\n      maxVUs: 500,\n      stages: [\n        { duration: '2m', target: 50 },  \u002F\u002F Ramp up to 50 req\u002Fsec\n        { duration: '5m', target: 50 },  \u002F\u002F Sustained load at 50 req\u002Fsec\n        { duration: '2m', target: 150 }, \u002F\u002F Spike to 150 req\u002Fsec\n        { duration: '5m', target: 150 }, \u002F\u002F Sustained spike\n        { duration: '2m', target: 0 },   \u002F\u002F Cool down\n      ],\n      gracefulStop: '30s',\n    },\n  },\n  thresholds: {\n    \u002F\u002F Global SLAs\n    'http_req_failed': ['rate\u003C0.01'],             \u002F\u002F Error rate \u003C 1%\n    'http_req_duration': ['p(95)\u003C300', 'p(99)\u003C800'], \u002F\u002F 95% \u003C 300ms, 99% \u003C 800ms\n    'custom_error_rate': ['rate\u003C0.005'],          \u002F\u002F Application error rate \u003C 0.5%\n    'api_transaction_latency': ['p(95)\u003C250'],     \u002F\u002F Transaction-specific SLA\n  },\n};\n\nconst BASE_URL = __ENV.BASE_URL || 'https:\u002F\u002Fapi.staging.example.com';\nconst AUTH_TOKEN = __ENV.AUTH_TOKEN || 'bearer-secret-token';\n\nexport function setup() {\n  \u002F\u002F Pre-test setup: Fetch reference data or seed test DB\n  const res = http.get(`${BASE_URL}\u002Fv1\u002Fhealth`, {\n    headers: { Authorization: AUTH_TOKEN },\n  });\n  check(res, { 'system healthy': (r) => r.status === 200 });\n  return { startTime: new Date().toISOString() };\n}\n\nexport default function (data) {\n  const payload = JSON.stringify({\n    item_id: 'prod_99182',\n    quantity: 1,\n    idempotency_key: `idempotency_${__VU}_${__ITER}_${Date.now()}`,\n  });\n\n  const params = {\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'Authorization': AUTH_TOKEN,\n      'X-Correlation-ID': `k6-test-${__VU}-${__ITER}`,\n    },\n    tags: { name: 'POST \u002Fv1\u002Forders' },\n  };\n\n  const startTime = Date.now();\n  const res = http.post(`${BASE_URL}\u002Fv1\u002Forders`, payload, params);\n  const duration = Date.now() - startTime;\n\n  \u002F\u002F Record metrics\n  apiLatency.add(duration);\n\n  const success = check(res, {\n    'status is 201 Created': (r) => r.status === 201,\n    'order ID present': (r) => r.json('order_id') !== undefined,\n    'response under 500ms': (r) => r.timings.duration \u003C 500,\n  });\n\n  if (success) {\n    totalOrders.add(1);\n    errorRate.add(false);\n  } else {\n    errorRate.add(true);\n  }\n\n  \u002F\u002F Pacing \u002F Think Time (Random jitter between 1s and 3s)\n  sleep(1 + Math.random() * 2);\n}\n\nexport function teardown(data) {\n  \u002F\u002F Clean up resources or output test execution metadata\n  console.log(`Test completed. Started at: ${data.startTime}`);\n}\n```\n\n---\n\n## 3. Python Locust Implementation Standard\n\n### Architectural Principles\n1. **User Behavior Modeling**: Group API flows into task sets with weights representing real user path distributions.\n2. **State Management**: Maintain user session state (auth tokens, basket contents) on the `User` instance.\n3. **Event Hooks**: Use `events.request` and `events.quitting` for customized SLA verification, metric shipping, or telemetry injection.\n\n### Production Locust Framework Example\n\n```python\nimport time\nimport uuid\nimport logging\nfrom locust import HttpUser, task, between, events, SequentialTaskSet\nfrom locust.exception import StopUser\n\nlogger = logging.getLogger(\"locust.loadtest\")\n\nclass UserCheckoutJourney(SequentialTaskSet):\n    \"\"\"Sequential tasks simulating an e-commerce purchasing journey.\"\"\"\n    \n    def on_start(self):\n        \"\"\"Executed when a Virtual User initiates this TaskSet.\"\"\"\n        self.client.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"User-Agent\": \"LocustLoadTest\u002F2.0\",\n        })\n        self.auth_token = self._authenticate()\n\n    def _authenticate(self) -> str:\n        with self.client.post(\n            \"\u002Fapi\u002Fv1\u002Fauth\u002Flogin\",\n            json={\"username\": \"load_user\", \"password\": \"secure_password\"},\n            catch_response=True,\n            name=\"\u002Fapi\u002Fv1\u002Fauth\u002Flogin\"\n        ) as response:\n            if response.status_code == 200:\n                token = response.json().get(\"access_token\")\n                self.client.headers[\"Authorization\"] = f\"Bearer {token}\"\n                return token\n            else:\n                response.failure(f\"Auth failed with status {response.status_code}\")\n                raise StopUser()\n\n    @task(3)\n    def browse_catalog(self):\n        with self.client.get(\n            \"\u002Fapi\u002Fv1\u002Fproducts?category=electronics&limit=20\",\n            catch_response=True,\n            name=\"\u002Fapi\u002Fv1\u002Fproducts\"\n        ) as response:\n            if response.status_code != 200:\n                response.failure(f\"Expected 200 OK, got {response.status_code}\")\n            elif response.elapsed.total_seconds() > 0.4:\n                response.failure(f\"SLA Breach: Latency > 400ms ({response.elapsed.total_seconds()}s)\")\n\n    @task(2)\n    def add_to_cart(self):\n        payload = {\"product_id\": \"p_88721\", \"quantity\": 1}\n        self.client.post(\"\u002Fapi\u002Fv1\u002Fcart\u002Fitems\", json=payload, name=\"\u002Fapi\u002Fv1\u002Fcart\u002Fitems\")\n\n    @task(1)\n    def checkout(self):\n        idempotency_key = str(uuid.uuid4())\n        headers = {\"X-Idempotency-Key\": idempotency_key}\n        \n        with self.client.post(\n            \"\u002Fapi\u002Fv1\u002Fcheckout\",\n            json={\"payment_method\": \"credit_card\"},\n            headers=headers,\n            catch_response=True,\n            name=\"\u002Fapi\u002Fv1\u002Fcheckout\"\n        ) as response:\n            if response.status_code == 201:\n                response.success()\n            else:\n                response.failure(f\"Checkout error: {response.text}\")\n\n\nclass ECommerceLoadUser(HttpUser):\n    \"\"\"Virtual User runner with weighted task distributions.\"\"\"\n    wait_time = between(1.5, 3.5)\n    tasks = [UserCheckoutJourney]\n    host = \"https:\u002F\u002Fapi.staging.example.com\"\n\n\n# Event Hooks for Custom Automated SLA Verification in Headless \u002F CI mode\n@events.quitting.add_listener\ndef verify_slas(environment, **kwargs):\n    stats = environment.stats.total\n    fail_ratio = stats.fail_ratio\n    p95 = stats.get_response_time_percentile(0.95)\n    p99 = stats.get_response_time_percentile(0.99)\n    \n    logger.info(f\"Test summary: Fail Ratio={fail_ratio:.4f}, p95={p95}ms, p99={p99}ms\")\n\n    # Automated Gate Criteria\n    sla_failed = False\n    if fail_ratio > 0.01:\n        logger.error(f\"SLA VIOLATION: Failure rate {fail_ratio * 100:.2f}% exceeds limit of 1.0%\")\n        sla_failed = True\n    if p95 > 300:\n        logger.error(f\"SLA VIOLATION: 95th percentile latency {p95}ms exceeds limit of 300ms\")\n        sla_failed = True\n    if p99 > 800:\n        logger.error(f\"SLA VIOLATION: 99th percentile latency {p99}ms exceeds limit of 800ms\")\n        sla_failed = True\n\n    if sla_failed:\n        environment.process_exit_code = 1\n```\n\n---\n\n## 4. SLA Verification & Threshold Metrics\n\nWhen designing enterprise performance tests, define SLAs based on standard 4 Golden Signals (Latency, Traffic, Errors, Saturation):\n\n| Metric | Target SLA Standard | k6 Threshold Expression | Locust Verification logic |\n| :--- | :--- | :--- | :--- |\n| **Http Failure Rate** | `\u003C 0.5%` | `'http_req_failed': ['rate\u003C0.005']` | `stats.fail_ratio \u003C 0.005` |\n| **p95 Latency** | `\u003C 250 ms` | `'http_req_duration': ['p(95)\u003C250']` | `stats.get_response_time_percentile(0.95) \u003C 250` |\n| **p99 Latency** | `\u003C 500 ms` | `'http_req_duration': ['p(99)\u003C500']` | `stats.get_response_time_percentile(0.99) \u003C 500` |\n| **Throughput (RPS)** | `> 500 RPS` | `'http_reqs': ['count>300000']` | `stats.total_rps >= 500` |\n\n---\n\n## 5. Anti-Patterns & Pitfalls to Avoid\n\n### 1. Closed Model vs Open Model Misunderstanding\n* **Anti-Pattern**: Using VU-based ramping (Closed Model) when simulating public HTTP endpoints. As response latency increases under load, VUs spend more time waiting for responses, decreasing throughput (RPS) and hiding performance degradation.\n* **Solution**: Use `ramping-arrival-rate` in k6 or Constant Throughput Timer models in Locust to enforce RPS regardless of system latency.\n\n### 2. Lack of Pacing \u002F Think Time\n* **Anti-Pattern**: Executing infinite tight loops without think times (`sleep()`), causing unrealistically high request rates per VU and overloading load generator network cards before target system limits are reached.\n* **Solution**: Apply realistic Poisson or uniform random think times (`sleep(1 + Math.random() * 2)` in k6 or `between(1, 3)` in Locust).\n\n### 3. Hardcoded Test Data & Shared Session IDs\n* **Anti-Pattern**: Re-using the same user ID or authentication token across 500 VUs, causing DB lock contention on a single row or hitting single-user rate limits.\n* **Solution**: Parameterize test data using JSON data files, synthetic UUID generation, or unique VU iteration identifiers (`__VU`, `__ITER`).\n\n### 6. Logging Overhead During High Load\n* **Anti-Pattern**: Using `console.log()` or `print()` inside the main test function for every request during a 10,000 VU load test, maxing out CPU I\u002FO.\n* **Solution**: Log only on failure conditions (`if (!success) { ... }`).\n",{"name":5,"description":7},"main","e905af21e5f1e1c3ca605e9656c3a7930360a84e","Programming\u002FTesting_and_QA\u002FPerformance_and_Load_Testing\u002Fk6-and-locust-load-testing",1,"https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills","https:\u002F\u002Fhamzabellouch.github.io\u002F","https:\u002F\u002Fgithub.com\u002Fhamzabellouch","hamzabellouch.github.io","CEO & Founder of @tknoglobal | Researcher in Technology & Applied Sciences.","2026-10-17 03:20:19",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add hamzabellouch\u002Fagent-skills --skill k6-and-locust-load-testing",{"tool":40,"command":41},"bunx","bunx skills add hamzabellouch\u002Fagent-skills --skill k6-and-locust-load-testing",{"tool":43,"command":44},"pnpm","pnpm dlx skills add hamzabellouch\u002Fagent-skills --skill k6-and-locust-load-testing","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FProgramming\u002FTesting_and_QA\u002FPerformance_and_Load_Testing\u002Fk6-and-locust-load-testing\u002FSKILL.md",true,[],[49,56,63,70,77,84],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":19},"01M79FHH2H815A9TAP6WNKH4Q8","security-audit","Comprehensive security guidance, source code audit, vulnerability assessment, and penetration test review for codebases, APIs, microservices, CLI tools, libraries, and LLM-backed applications. Triggers on requests to audit a codebase, conduct security reviews, find vulnerabilities or flaws, pen-test source code, or when the user asks in Arabic (فحص أمني، تدقيق الكود أمنياً، مراجعة الثغرات، فحص أمان المشروع). Supports Guidance mode (focused review) and Full Audit mode (deterministic 6-phase harness).","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FSecurity\u002FSecurity_Audit_and_Code_Review\u002Fsecurity-audit\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":59,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":60,"categories":61,"keywords":62,"publishedAt":19},"01M79FHBGXVBY6VQ1X7ETAZMF1","malware-analysis-reversing","Production malware analysis workflows, reverse engineering methodologies, isolated sandbox triage, static\u002Fdynamic binary analysis, memory forensics, and YARA detection rule authoring.","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FSecurity\u002FOffensive_Security_and_Pentesting\u002Fmalware-analysis-reversing\u002FSKILL.md",[],[],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":19},"01M79FH6EACDR801TZCE4R8SAC","application-security-pentesting","Production Application Security (AppSec) standards, OWASP Top 10 vulnerability remediation, SAST\u002FDAST pipeline integration, secure code review, threat modeling, and defensive security posture.","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FSecurity\u002FOffensive_Security_and_Pentesting\u002Fapplication-security-pentesting\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M79FH0VKVT44FK923K520ZQA","oauth2-oidc-security-flows","Implement enterprise OAuth 2.1 and OpenID Connect (OIDC) authorization code flow with Proof Key for Code Exchange (PKCE), state and nonce verification, refresh token rotation, token revocation, and centralized IdP federation (Keycloak, Auth0, Okta). Trigger when building secure authentication, single sign-on (SSO), or third-party delegated authorization.","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FSecurity\u002FIdentity_and_Access_Management_IAM\u002Foauth2-oidc-security-flows\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":19},"01M79FGVVB3R4T88XXD8FRSV5B","jwt-session-management-hardening","Harden JWT-based authentication and session lifecycles using asymmetric signing (RS256\u002FEdDSA), JWKS rotation, strict claims validation, Redis-backed sliding window sessions, revocation lists, and secure HttpOnly cookie storage. Trigger when implementing token validation, session revocation, or hardening API authentication.","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FSecurity\u002FIdentity_and_Access_Management_IAM\u002Fjwt-session-management-hardening\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M79FGNCPZ85CVEY0B3NE4H3B","soc2-compliance-automation","Best practices for implementing SOC 2 Type II compliance controls, continuous evidence collection, infrastructure policy-as-code, and automated security monitoring. Use when automating Trust Services Criteria (Security, Availability, Confidentiality, Processing Integrity, Privacy), audit logging, IAM least privilege, or CI\u002FCD security gates.","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FSecurity\u002FGovernance_Compliance_and_Legal_Tech\u002Fsoc2-compliance-automation\u002FSKILL.md",[],[]]