Logo

dev-resources.site

for different kinds of informations.

Load and stress testing with k6

Published at
5/10/2024
Categories
k6
testing
node
Author
zsevic
Categories
3 categories in total
k6
open
testing
open
node
open
Author
6 person written this
zsevic
open
Load and stress testing with k6

k6 is a performance testing tool. This post explains types of performance testing and dives into k6 usage, from configuration to running tests.

Load and stress testing

Load and stress testing are two types of performance testing used to evaluate how well a system performs under various conditions.

Load testing determines how the system performs under expected user loads. The purpose is to identify performance bottlenecks.

Stress testing assesses how the system performs when loads are heavier than usual. The purpose is to find the limit at which the system fails and to observe how it recovers from such failures.

Prerequisites

  • k6 installed

  • Script (Node.js) file with configuration and execution function

Configuration

Configuration is stored inside options variable, which allows you to set up different testing scenarios:

  • constant user load, the number of virtual users (vus) remains constant throughout the test period
export const options = {
  vus: 30,
  duration: '10m'
};
Enter fullscreen mode Exit fullscreen mode
  • variable user load, the number of users increases and decreases over time
export const options = {
  stages: [
    {
      duration: '1m',
      target: 30
    },
    {
      duration: '10m',
      target: 30
    },
    {
      duration: '5m',
      target: 0
    }
  ]
};
Enter fullscreen mode Exit fullscreen mode

Environment variables can be passed through the command line and are accessible within the script via the __ENV object.

k6 -e TOKEN=token run script.js
Enter fullscreen mode Exit fullscreen mode

Execution function

This function defines what virtual users will do during the test. This function is called for each virtual user and typically includes steps that simulate user actions on the app.

export default function() {
  http.get(URL);
  // Add more actions as required
}
Enter fullscreen mode Exit fullscreen mode

Test report

k6 generates a report that provides detailed insights into various benchmarks, such as the number of virtual users, requests per second, request durations and error rates.

Example

This example utilizes k6 to conduct a load test using a variable user load approach:

  • User simulation: The script ramps up to 1,000 users, maintains that level to simulate sustained traffic, and gradually reduces to zero.

  • Request handling: During the test, each virtual user sends a POST request to an API, with pauses between requests to mimic real user behavior.

  • Performance insights: After the test, k6 provides a report that shows key information, such as how fast the app responds and how many requests fail.

Run it via k6 -e TOKEN=1234 run script.js command.

// script.js
import { check, sleep } from 'k6';
import { scenario } from 'k6/execution';
import http from 'k6/http';

export const options = {
  stages: [
    // Ramp up to 1000 users over 10 minutes
    {
      duration: '10m',
      target: 1000
    },
    // Hold 1000 users for 30 minutes
    {
      duration: '30m',
      target: 1000
    },
    // Ramp down to 0 users over 5 minutes
    {
      duration: '5m',
      target: 0
    }
  ]
};

export default () => {
  const response = http.post(
    URL,
    JSON.stringify({
      iteration: scenario.iterationInTest
    }),
    {
      headers: {
        Authorization: __ENV.TOKEN,
        'Content-Type': 'application/json'
      }
    }
  );

  check(response, {
    'response status was 200': (res) => res.status === 200
  });

  sleep(1);
};
Enter fullscreen mode Exit fullscreen mode

Course

Build your SaaS in 2 weeks - Start Now

k6 Article's
30 articles in total
Favicon
Performance testing of OpenAI-compatible APIs (K6+Grafana)
Favicon
A Guide to Scalable and Heavy Load Testing with k6 + Testkube
Favicon
When k6 eats up your RAM: Slashing memory usage in load tests
Favicon
Grafana K6 cheat sheet: everything a performance engineer should know
Favicon
How to send more requests with variable payload size in K6?
Favicon
How to integrate k6 with Xray/Jira
Favicon
Mastering Performance Testing with K6: A Guide for QA Testers
Favicon
Improved k6 Load Test Script with Custom Metrics, Tags, and Labels
Favicon
Como Realizar Testes de Carga com k6
Favicon
Visualização de métricas k6 em tempo real com Prometheus remote write
Favicon
Criando um modulo xk6 para k6
Favicon
Load Testing a Non-API Laravel Web Application with Sanctum Session-Based Authentication Using K6
Favicon
Load and stress testing with k6
Favicon
Enviando notificações com xk6 notification ✉
Favicon
Gerando dados com K6 utilizando xk6-faker
Favicon
Gerando dashboard ao resultado de saida com K6🖼
Favicon
Adicionando percentil ao resultado de saída do K6📊
Favicon
Performance testing Strimzi Kafka in the k8s cluster using xk6-kafka
Favicon
Entendendo as métricas do K6 - Parte 3
Favicon
Node.js Observability Tool: Enhance Visibility Without Performance Impact
Favicon
Optimizing Performance Testing with Docker: K6, InfluxDB, and Grafana Integration
Favicon
Entendendo as métricas do K6 - Parte 2
Favicon
Entendendo as métricas do K6 - Parte 1
Favicon
K6 Development: Beyond The Basic Setup
Favicon
Load Testing Serverless Application using k6
Favicon
Load Testing using K6 in AWS and Terraform
Favicon
Utilizando módulos do xk6 com k6
Favicon
Abortando testes com falhas no K6
Favicon
Utilizando AWS Secret Manager com K6🔐
Favicon
Realizando requisições com query params com K6

Featured ones: