> For the complete documentation index, see [llms.txt](https://developer.harness.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developer.harness.io/resilience-testing/chaos-testing/chaos-faults/load/k6-loadgen.md). Agents can also search and read this documentation through its [MCP server](https://developer.harness.io/~gitbook/mcp).

# K6 loadgen

Generate a configurable load against a target endpoint with a k6 script for a configurable duration so you can test how the workload behaves under sustained traffic.

K6 loadgen runs a [k6](https://k6.io) load-test script against a target endpoint from a helper pod inside the chaos infrastructure cluster for `TOTAL_CHAOS_DURATION` seconds, then stops. The script is read from a Kubernetes secret (`SCRIPT_SECRET_NAME`/`SCRIPT_SECRET_KEY`) and run by the official Grafana k6 runner image (`LOAD_IMAGE`), so the load profile (smoke, spike, stress, soak) is fully driven by the script.

Use K6 loadgen to test how a target workload behaves under sustained synthetic load: whether application latency stays inside the SLA, whether autoscaling kicks in, whether circuit breakers and rate limiters work as expected, and whether monitoring detects the saturation within the alerting SLA.

| Property                   | Value                                                                                                                                          |
| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| **Fault ID**               | `k6-loadgen`                                                                                                                                   |
| **Target**                 | HTTP endpoints reachable from the cluster                                                                                                      |
| **Failure type**           | Resource                                                                                                                                       |
| **Chaos infrastructure**   | Kubernetes                                                                                                                                     |
| **Supported environments** | All [Kubernetes environments](https://developer.harness.io/resilience-testing/chaos-testing/chaos-faults/kubernetes.md#supported-environments) |
| **Reversible**             | Yes. The fault stops the load and deletes its runner pods when it ends.                                                                        |

***

## Use cases

Run the fault when you want to answer questions such as:

* **API latency under load:** When the script drives `N` virtual users against a REST endpoint, does p95/p99 stay inside the SLA?
* **Autoscaling fidelity:** Does HPA, KEDA, or a custom autoscaler add capacity inside the alerting SLA?
* **Rate limiting:** Does the rate limiter return `429`s correctly under sustained burst traffic without leaking errors downstream?
* **Continuous validation in pipelines:** Catch performance regressions early by running k6 scripts as part of a CI/CD pipeline.

***

## Before you begin

* **Chaos infrastructure:** A Kubernetes chaos infrastructure on Kubernetes 1.21 or later. Go to [Get started](https://developer.harness.io/resilience-testing/chaos-testing/get-started.md) to install one and run an experiment end to end.
* **k6 script secret:** A Kubernetes secret in the chaos runner namespace containing the k6 JavaScript file. The default key is `script.js`. Create it with:

  ```bash
  kubectl create secret generic k6-script \
    --from-file=script.js=<path-to-script>.js \
    -n <chaos-namespace>
  ```
* **Target endpoint reachable:** The endpoint addressed in the k6 script (`http.get('https://...')`) is reachable from the chaos infrastructure cluster.
* **Image accessible:** `LOAD_IMAGE` (default `ghcr.io/grafana/k6-operator:latest-runner`) is pullable from the cluster, or mirror it to your own registry and override the tunable.

### Permissions

The fault needs no container privileges. The fault runs on a namespace-scoped or cluster-scoped install with only the [core permissions](https://developer.harness.io/resilience-testing/chaos-testing/chaos-faults/kubernetes/permissions.md#core-permissions), which cover reading the k6 script secret and creating the runner pod in the chaos runner namespace.

Go to [Kubernetes fault permissions](https://developer.harness.io/resilience-testing/chaos-testing/chaos-faults/kubernetes/permissions.md) for the core rules and the container privileges each fault needs.

***

## Fault tunables

Configure the following tunables when you add K6 loadgen to an experiment in Chaos Studio.

**Required**

| Tunable              | Description                                                                                    | Default  |
| -------------------- | ---------------------------------------------------------------------------------------------- | -------- |
| `SCRIPT_SECRET_NAME` | Name of the Kubernetes secret in the chaos runner namespace that holds the k6 JavaScript file. | Required |
| `SCRIPT_SECRET_KEY`  | Key inside the secret that points to the k6 script (for example `script.js`).                  | Required |

**Chaos**

| Tunable                | Description                                                                                                             | Default |
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------- | ------- |
| `TOTAL_CHAOS_DURATION` | Total duration of the fault, in seconds. k6 runs for this period regardless of the duration declared inside the script. | `60`    |

**Advanced**

| Tunable      | Description                                           | Default                                     |
| ------------ | ----------------------------------------------------- | ------------------------------------------- |
| `LOAD_IMAGE` | Container image used to run k6 inside the helper pod. | `ghcr.io/grafana/k6-operator:latest-runner` |

The fault also supports the [common tunables](https://developer.harness.io/resilience-testing/chaos-testing/chaos-faults/common-tunables.md) shared by every fault.

### Sample k6 script

The contents of the secret are passed straight to k6. Any script supported by the runner image works.

```javascript
import http from "k6/http";
import { check, sleep } from "k6";

export const options = {
  vus: 50,
  duration: "60s",
};

export default function () {
  const res = http.get("https://api.example.com/health");
  check(res, { "status is 200": (r) => r.status === 200 });
  sleep(0.3);
}
```

Go to the [k6 documentation](https://grafana.com/docs/k6/latest/) to read the script reference and the [test-type catalog](https://grafana.com/docs/k6/latest/testing-guides/test-types/) (smoke, load, stress, spike, soak).

***

## How the fault works

The fault reads the k6 script from `SCRIPT_SECRET_NAME`/`SCRIPT_SECRET_KEY`, mounts it into a helper pod that runs `LOAD_IMAGE`, executes `k6 run` for `TOTAL_CHAOS_DURATION` seconds, then tears the helper pod down.

* The target endpoint sees sustained synthetic traffic for `TOTAL_CHAOS_DURATION` seconds at the rate driven by the script's `vus` and `duration` settings.
* Application metrics on the target (latency, throughput, error rate) shift in line with the load profile.
* Autoscalers (HPA, KEDA) may add capacity if CPU/RPS thresholds are reached.
* After the duration ends, the helper pod is deleted; traffic from the fault stops within seconds.

### Signals to watch

Attach [resilience probes](https://developer.harness.io/resilience-testing/chaos-testing/probes.md) to assert each layer:

* **Application latency:** Use a [Prometheus probe](https://developer.harness.io/resilience-testing/chaos-testing/probes/apm-probes.md) on the application's request-duration histogram and assert p95/p99 stays inside the SLA.
* **Error rate:** Use a Prometheus probe on the application's 5xx counter and assert it stays below threshold.
* **Autoscaling reaction:** Use a [command probe](https://developer.harness.io/resilience-testing/chaos-testing/probes/command-probe.md) running `kubectl get hpa <name>` to assert replicas grew.

***

## Verify the fault effect

While the experiment is running, confirm the fault takes effect and then clears:

1. Watch the helper pod logs for k6 output.

   ```bash
   kubectl logs -n <chaos-namespace> -l name=k6-load-generator -f
   ```

   You should see k6's checks-passed / failed lines and the final summary table.
2. Inspect target metrics.

   Use your APM tool (Prometheus, Datadog, New Relic) to confirm RPS and latency rose during the chaos window and recovered afterwards.
3. Confirm the helper pod was cleaned up.

   ```bash
   kubectl get pods -n <chaos-namespace> -l name=k6-load-generator
   ```

   The pod should be gone after the experiment ends.

***

## Recovery and cleanup

The fault reverts its change automatically when it ends. Observe the following cases:

* **End of duration:** The chaos pod stops k6 and deletes the helper pod when `TOTAL_CHAOS_DURATION` elapses.
* **Abort the experiment early:** Stopping the experiment from Chaos Studio also stops k6 and cleans up the helper pod.
* **Manual recovery:** If the helper pod survives an abort, delete it with `kubectl delete pods -n <chaos-namespace> -l name=k6-load-generator`.
* **Workload recovery:** Application metrics recover as soon as synthetic traffic stops; HPA-driven replicas scale back in over the autoscaler cooldown.

***

## Limitations

The fault is not appropriate in the following scenarios:

* **Single endpoint per script:** The script controls the targets; running k6 against many endpoints requires that the script address them.
* **Cluster network egress:** Synthetic traffic leaves the chaos infrastructure cluster; egress costs and per-host rate limits apply.
* **No mid-flight reconfigure:** Script changes require re-uploading the secret and re-running the experiment.
* **Image hosted on GHCR:** The default `LOAD_IMAGE` pulls from `ghcr.io`. If your cluster cannot reach GHCR, mirror the image to your own registry and override `LOAD_IMAGE`.
* **Script-driven duration:** If the script declares a longer `duration` than `TOTAL_CHAOS_DURATION`, the fault still terminates at `TOTAL_CHAOS_DURATION`; align both for accurate reporting.

***

## Troubleshooting

<details>

<summary>K6 loadgen secret not found</summary>

The secret `SCRIPT_SECRET_NAME` must exist in the chaos runner namespace (the namespace where the chaos infrastructure runs). Create it with `kubectl create secret generic <secret-name> --from-file=script.js=<path-to-script>.js -n <chaos-namespace>`.

</details>

<details>

<summary>K6 loadgen helper pod stuck in ImagePullBackOff</summary>

`LOAD_IMAGE` defaults to `ghcr.io/grafana/k6-operator:latest-runner`. If your cluster cannot reach `ghcr.io`, mirror the image to a registry you can reach and set `LOAD_IMAGE` to that path.

</details>

<details>

<summary>Target endpoint not reachable from the chaos infrastructure cluster</summary>

Confirm the URL inside the k6 script is reachable from inside the cluster: `kubectl run debug --image=alpine --rm -it -n <chaos-namespace> -- wget -qO- <target-url>`. Adjust network policies, security groups, or egress rules to allow traffic from the chaos runner namespace.

</details>

<details>

<summary>K6 loadgen exits with unknown protocol</summary>

The script must use a supported k6 module (`k6/http`, `k6/grpc`, `k6/ws`). Validate the script locally with `k6 run script.js` before pushing it as a secret.

</details>

***

## Related faults

The following faults test related failure paths:

* [Locust loadgen](https://developer.harness.io/resilience-testing/chaos-testing/chaos-faults/load/locust-loadgen.md): Generate load with Locust (Python-based) instead of k6.
* [Pod HTTP latency](https://developer.harness.io/resilience-testing/chaos-testing/chaos-faults/kubernetes/pod/pod-http-latency.md): Inject latency on the server side instead of driving load from outside.
* [Pod CPU hog](https://developer.harness.io/resilience-testing/chaos-testing/chaos-faults/kubernetes/pod/pod-cpu-hog.md): Stress server CPU instead of driving traffic.

{% @harness-feedback/feedback %}
