Skip to main content
  1. Today I learned/

Simple Load Testing with k6

·261 words·2 mins· loading · loading · ·
Marius Kimmina
Author
Marius Kimmina
IT Infrastructure at scale

first steps with k6
#

k6 is an open-source load testing tool (recently aquired by Grafana labs) that allows you to define load tests as code and while I am a big fan of all things as code, it supporting only JavaScript reduces my excitement a little bit.

That being said, you don’t have to write that much of it, of course this will depend on the complexity of the tests you want to perform but for most people are relatively simple script will get them a long way already.

The following is a simple (and very light) load test that you could (but shouldn’t) run against example.com.

import http from "k6/http";
import { check } from "k6";

export const options = {
  thresholds: settings.thresholds,
  scenarios: {
    constantRate: {
      // 100 requests per second constant rate
      executor: "constant-arrival-rate",
      duration: "60s",
      rate: 100,
      timeUnit: "1s",
      preAllocatedVUs: 20,
      maxVUs: 10,
    },
  },
};

export default function () {
  const url =
    "https://example.com"; // please don't run actual load tests against example.com
  const params = {
    headers: {
      "My-Custom-Header": "test123",
    },
  };

  const data = newRequest();

  const response = http.post(url, data, params);

  console.info(response.status);

  check(response, {
    "status is OK": (r) => r && r.status === 200,
  });
}

export function newRequest() {
  return {
    RequestBody: "testtest",
  };
}

To execute it simply

k6 run script.js

This makes it also very easy to run load tests as part of a CI/CD Pipeline. Furthermore k6 can send realtime data about it’s load tests to Prometheus so you can visualize the resutls with Grafana.

Further reading
#

https://k6.io/