Integrating k6 Load Testing with Slack for Real-time Performance Monitoring

Monish Correia
5 min readJul 24, 2023

--

Load testing is a crucial aspect of ensuring the robustness and reliability of web applications.

K6, an open-source load testing tool, has gained popularity for its simplicity and flexibility. One way to enhance the power of k6 is by integrating it with Slack, a popular team collaboration platform. Slack integration enables real-time performance monitoring, making it easier to identify and address performance bottlenecks promptly.

In this article, we’ll explore how to set up the k6 and Slack integration and leverage it to supercharge your load testing process.

Sample K6 script for GET API

import http from 'k6/http';
import { sleep } from 'k6';

export default function () {
http.get('https://test.k6.io');
sleep(1);
}

Run k6 with the following command:

k6 run script.js

Results Output

Combining Slack with k6 Metrics

We have successfully mastered the art of custom-pulling our metrics, and we’re now fully capable of crafting tailor-made Slack messages to suit our needs.

For sending messages to slack, we would need slack bot token.

To obtain a Slack bot token from scratch, follow these steps:

  1. Create a Slack Workspace: If you don’t have a Slack workspace already, you’ll need to create one. Go to the Slack website (https://slack.com/) and sign up for a new workspace by providing the necessary details.

If you have a company slack workspace, you can skip this step

2. Create a New App: Once you have a Slack workspace, log in and go to the Slack API website (https://api.slack.com/apps). Click on the “Create NewApp” button to begin the process of creating a new app for your workspace. Click on “From Scratch” option.

3. App Configuration: Give your app a name and select the Slack workspace where you want to install the app.

4. Permissions: In the app settings, navigate to “OAuth & Permissions.” Under the “Bot Token Scopes” section, you’ll specify the permissions your bot requires to function. Choose the relevant scopes based on the actions your bot needs to perform (e.g., sending messages, reading channels, etc.).

Add all the below scope for your slack app.

5. Install the App to Workspace: In the same “OAuth & Permissions” section, click the “Install to Workspace” button. This will prompt Slack to ask for your permission to install the app in your selected workspace. Click “Allow” to proceed.

6. Bot Token Generation: After installing the app, you’ll receive the bot token. Look for the “Bot User OAuth Access Token” under the “OAuth & Permissions” section. This token serves as the authentication method for your bot to interact with the Slack API.

7. Save the Token Securely: Once you have the bot token, make sure to store it securely. Avoid sharing it publicly or hardcoding it in your code. Instead, use environment variables or a secure configuration method to keep the token safe.

Once we have obtained our Slack bot token, the following steps will guide us in creating the function to send a Slack message:

  1. Identify the specific metrics we need to retrieve from the data object, which is accessible through the handleSummary function.
  2. Craft a custom message that includes the extracted metrics to compose the content of our Slack message.
  3. Utilize the slack chat.postMessage method to send our customized message to the desired Slack channel.
import http from "k6/http";
import { check } from "k6";
import { sleep } from 'k6';
import { htmlReport } from "https://raw.githubusercontent.com/benc-uk/k6-reporter/main/dist/bundle.js";

// Read a token from the environment variables
const token = "YOUR_SLACK_BOT_TOKEN";


export default function () {
http.get('https://test.k6.io');
sleep(1);
}


// Initialize
export function sendSlackMessages(data, testCount) {
// Get the average values for each metric
let avgResponseTime =
data.metrics.http_req_duration.values["avg"].toFixed(2);
let iterationsCount =
data.metrics.http_reqs.values.count;
let p90ResponseTime =
data.metrics.http_req_duration.values["p(90)"].toFixed(2);
let p95ResponseTime =
data.metrics.http_req_duration.values["p(95)"].toFixed(2);
let failedRequests = data.metrics.http_req_failed.values.passes;
let testRunDuration = Math.floor(
(data.state["testRunDurationMs"] / 1000) % 60
);

// Create the payload for the Slack message
const payload = {
channel: "k6-testapi",
attachments: [
{
color: "#9205a2",
blocks: [
{
type: "section",
text: {
type: "mrkdwn",
text:
"#*test passed in " +
testRunDuration +
" sec*",
},
},
{
type: "section",
fields: [
{
type: "mrkdwn",
text:
"*http_req_duration Average:*\n :large_green_circle: " +
avgResponseTime +
" ms",
},
{
type: "mrkdwn",
text:
"*Iterations:*\n :large_green_circle: " +
iterationsCount +
"",
},
{
type: "mrkdwn",
text:
"*90th Percentile:*\n :large_green_circle: " +
p90ResponseTime +
" ms",
},
{
type: "mrkdwn",
text:
"*95th Percentile:*\n :large_green_circle: " +
p95ResponseTime +
" ms",
},
{
type: "mrkdwn",
text:
"*Failed Requests:*\n :red_circle: " +
failedRequests +
"",
},
],
},
{
type: "divider",
},
{
type: "context",
elements: [
{
type: "image",
image_url:
"https://raw.githubusercontent.com/k6io/awesome-k6/master/assets/bert.png",
alt_text: "k6 croc",
},
{
type: "mrkdwn",
text: "*K6* has approved this message.",
},
],
},
],
},
],
};

// Send a message to Slack
const res = http.post(
"https://slack.com/api/chat.postMessage",
JSON.stringify(payload),
{
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
},
}
);

// Check the response
check(res, {
"is status 200": (r) => r.status === 200,
});
// console.log(totalIterations);
}

export function handleSummary(data) {
sendSlackMessages(data);
return {
"summary.html": htmlReport(data),
};

}

We are now ready to run our test.

k6 run script.js

Let’s review Slack; indeed, your message has appeared on your channel. We can see the custom message you sent.

Conclusion:

Integrating k6 with Slack can significantly enhance your load testing process, allowing for real-time monitoring, collaboration, and faster issue resolution. By bringing performance insights directly to your team’s communication platform, you can improve the overall efficiency and reliability of your web applications.

So, why wait? Start integrating k6 with Slack today and take your load testing to the next level!

Happy testing!

Monish Correia — QA Lead

https://www.linkedin.com/in/monishcorreia/

If you like this article, please show your support clicking the clap button below and follow for more. Thank you! ❤️

--

--

Monish Correia

QA Lead | Postman Supernova| K6 Champion| Test Automation | API Testing | Performance Testing | K6 | Need some help? : https://topmate.io/monish_correia