惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

C
Cisco Blogs
Cyberwarzone
Cyberwarzone
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
SecWiki News
SecWiki News
Martin Fowler
Martin Fowler
T
Tor Project blog
N
Netflix TechBlog - Medium
C
Cybersecurity and Infrastructure Security Agency CISA
V
Vulnerabilities – Threatpost
V
Visual Studio Blog
GbyAI
GbyAI
PCI Perspectives
PCI Perspectives
D
DataBreaches.Net
Jina AI
Jina AI
H
Heimdal Security Blog
云风的 BLOG
云风的 BLOG
P
Privacy International News Feed
A
About on SuperTechFans
J
Java Code Geeks
美团技术团队
H
Hackread – Cybersecurity News, Data Breaches, AI and More
N
News | PayPal Newsroom
有赞技术团队
有赞技术团队
MyScale Blog
MyScale Blog
博客园 - 司徒正美
C
Check Point Blog
T
Threat Research - Cisco Blogs
Attack and Defense Labs
Attack and Defense Labs
宝玉的分享
宝玉的分享
AI
AI
Simon Willison's Weblog
Simon Willison's Weblog
C
Cyber Attacks, Cyber Crime and Cyber Security
I
Intezer
P
Proofpoint News Feed
Blog — PlanetScale
Blog — PlanetScale
Apple Machine Learning Research
Apple Machine Learning Research
Hugging Face - Blog
Hugging Face - Blog
The Last Watchdog
The Last Watchdog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Vercel News
Vercel News
I
InfoQ
阮一峰的网络日志
阮一峰的网络日志
Cisco Talos Blog
Cisco Talos Blog
W
WeLiveSecurity
Hacker News: Ask HN
Hacker News: Ask HN
Recent Commits to openclaw:main
Recent Commits to openclaw:main
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
D
Docker
博客园 - Franky
Security Archives - TechRepublic
Security Archives - TechRepublic

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Grafana k6: A Complete Practical Guide for Automating Performance Tests
Md. Niaz Mor · 2026-05-02 · via DEV Community

What is Grafana k6?

Grafana k6 (commonly just called k6) is an open-source, QA/SDET-friendly, and extensible load testing tool built by Grafana Labs. It lets you write performance test scripts in JavaScript or TypeScript and execute them against your APIs.

It is designed for:

  • QA Engineers and SDETs who need reliable, repeatable load scenarios
  • Developers who want to write tests as code
  • SREs who want to validate SLOs before and after deployments

k6 is built in Go, which means the test runner itself is blazing fast and extremely memory-efficient — it can simulate thousands of virtual users on a single machine without breaking a sweat.


Why k6 Over Other Tools?

JMeter has been the industry default for years. But the ecosystem has moved on. Here's why k6 is the modern choice:

Feature k6 JMeter Locust
Script Language JavaScript / TypeScript XML (GUI) Python
Resource Efficiency Very High (Go runtime) Low (JVM overhead) Medium
CI/CD Integration Native Plugins required Manual
Code Reusability ES6 modules, imports Limited Medium
Built-in Metrics Rich, structured Verbose Basic
Threshold/Pass-Fail First-class Plugin-based Manual
HTML/Cloud Reports Built-in + plugins Plugins Manual
Browser Testing Yes (k6 browser API) Via WebDriver No

Key Advantages of k6

1. Scripted in JavaScript — No proprietary DSL. If you know JS, you're ready. Tests live in your codebase alongside unit and e2e tests.

2. Extremely resource-efficient — k6 is written in Go. Unlike JMeter (which runs on the JVM), a single instance of k6 can run 30,000 to 40,000 virtual users depending on the available resources.

3. Built-in thresholds — You define pass/fail criteria directly in your test script. k6 exits with a non-zero code if thresholds are violated, making it CI/CD-native.

4. Real-time web dashboard — Since v0.49.0, k6 ships with a built-in live web dashboard. No extra tooling needed for real-time monitoring.

5. Grafana ecosystem — k6 integrates natively with Grafana dashboards, Prometheus, InfluxDB, and Grafana Cloud for enterprise-grade observability.


Installation

k6 has no runtime dependencies. There's no JVM, no Node.js — just a single binary.

Windows

Via Chocolatey (recommended):

choco install k6

Enter fullscreen mode Exit fullscreen mode

Via winget:

winget install k6 --source winget

Enter fullscreen mode Exit fullscreen mode

Or download the installer directly from the k6 GitHub Releases page and run the .msi file.

macOS

Via Homebrew (recommended):

brew install k6

Enter fullscreen mode Exit fullscreen mode

Verify installation:

k6 version
# k6 v1.x.x (go1.x.x, ...)

Enter fullscreen mode Exit fullscreen mode


Project Folder Structure

k6 is just JavaScript files — but a clean structure makes your test suite maintainable and team-friendly. While k6 does not enforce a strict, mandatory folder structure, Grafana recommends adopting a modular and organized approach, particularly for complex projects. The following folder structure can be followed:

my-k6-project/
│
├── config/
│   ├── smoke.json          # Smoke test options (1 VU, 1 iteration)
│   ├── load.json           # Normal load test options
│   └── stress.json         # Stress test options (high VUs)
│
├── helpers/
│   ├── auth.js             # Reusable login / token helpers
│   ├── request.js          # Base HTTP request wrappers
│   └── utils.js            # Utility functions (random data, etc.)
│
├── scenarios/
│   ├── login-flow.js       # End-to-end login scenario
│   └── checkout-flow.js    # End-to-end checkout scenario
│
├── reports/                # Auto-generated HTML/JSON reports go here
│
├── .env                    # Environment variables (BASE_URL, tokens, etc.)
├── main.js                 # Main entry point — imports & runs scenarios
└── README.md

Enter fullscreen mode Exit fullscreen mode

What Each Folder/File Does

  • config/ — Separates test configuration (VUs, duration, stages) from test code. Switch between smoke, load, and stress tests by just changing the config JSON, not the scripts.
  • helpers/ — Reusable utility code: authentication flows, HTTP wrappers, random data generators. Import these in your scenarios to keep things DRY.
  • scenarios/ — Each file represents a meaningful user journey (login, checkout, search). These contain the actual test logic.
  • reports/ — Where generated HTML and JSON output lands after a test run.
  • main.js — The orchestrator. It imports scenarios and wires them up with configuration.

Configuration & Utilities

Environment Variables

k6 reads environment variables via __ENV. This lets you keep base URLs and secrets out of your scripts:

// main.js
export const BASE_URL = __ENV.BASE_URL || 'https://api.staging.example.com';

Enter fullscreen mode Exit fullscreen mode

Load Configuration (Stages):

BASE_URL=https://api.prod.example.com k6 run main.js

Enter fullscreen mode Exit fullscreen mode

Or use a config JSON:

// config/load.json
{
  "vus": 50,
  "duration": "5m",
  "thresholds": {
    "http_req_duration": ["p(95)<500"],
    "http_req_failed": ["rate<0.01"]
  }
}

Enter fullscreen mode Exit fullscreen mode

Load it at runtime:

k6 run --config config/load.json main.js

Enter fullscreen mode Exit fullscreen mode

Load Configuration (Stages)

Stages let you ramp virtual users up and down, simulating realistic traffic patterns:

// main.js
export const options = {
  stages: [
    { duration: '1m', target: 20 },   // Ramp up to 20 VUs
    { duration: '3m', target: 20 },   // Hold at 20 VUs
    { duration: '1m', target: 50 },   // Spike to 50 VUs
    { duration: '2m', target: 50 },   // Hold the spike
    { duration: '1m', target: 0 },    // Ramp down
  ],
};

Enter fullscreen mode Exit fullscreen mode

Reusable Helper — helpers/auth.js

// helpers/auth.js
import http from 'k6/http';
import { check } from 'k6';

export function getAuthToken(baseUrl, username, password) {
  const payload = JSON.stringify({ username, password });
  const params = { headers: { 'Content-Type': 'application/json' } };

  const res = http.post(`${baseUrl}/auth/login`, payload, params);

  check(res, {
    'login successful': (r) => r.status === 200,
  });

  return res.json('token');
}

Enter fullscreen mode Exit fullscreen mode

Reusable Request Wrapper — helpers/request.js

// helpers/request.js
import http from 'k6/http';

export function get(url, token) {
  return http.get(url, {
    headers: {
      Authorization: `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
  });
}

export function post(url, body, token) {
  return http.post(url, JSON.stringify(body), {
    headers: {
      Authorization: `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
  });
}

Enter fullscreen mode Exit fullscreen mode

A Complete Test Script

// scenarios/login-flow.js
import { check, sleep } from 'k6';
import { getAuthToken } from '../helpers/auth.js';
import { get } from '../helpers/request.js';

const BASE_URL = __ENV.BASE_URL || 'https://api.example.com';

export default function () {
  // Step 1: Login and get token
  const token = getAuthToken(BASE_URL, 'testuser', 'password123');

  // Step 2: Use token to call a protected endpoint
  const res = get(`${BASE_URL}/api/v1/profile`, token);

  check(res, {
    'profile status 200': (r) => r.status === 200,
    'has user id':        (r) => r.json('id') !== undefined,
  });

  sleep(1); // Think time between iterations
}

Enter fullscreen mode Exit fullscreen mode


HTML Reporter Setup

k6 offers two built-in ways to generate HTML reports, plus a popular community plugin.

Option 1 — Built-in Web Dashboard (Recommended since v0.49.0)

This is the officially supported approach from Grafana. No dependencies needed.

K6_WEB_DASHBOARD=true \
K6_WEB_DASHBOARD_EXPORT=reports/html-report.html \
k6 run main.js

Enter fullscreen mode Exit fullscreen mode

While the test runs, open http://localhost:5665 in your browser to see real-time metrics. At the end, an HTML report is saved to reports/html-report.html.

Customize the port if needed:

K6_WEB_DASHBOARD=true \
K6_WEB_DASHBOARD_PORT=8080 \
K6_WEB_DASHBOARD_EXPORT=reports/html-report.html \
k6 run main.js

Enter fullscreen mode Exit fullscreen mode

Option 2 — benc-uk/k6-reporter (Community Plugin)

This plugin produces a standalone HTML file with charts, check results, and threshold pass/fail indicators — great for sharing with stakeholders.

Add this to your test script:

// main.js
import { htmlReport } from 'https://raw.githubusercontent.com/benc-uk/k6-reporter/main/dist/bundle.js';
import { textSummary } from 'https://jslib.k6.io/k6-summary/0.1.0/index.js';

export { default } from './scenarios/login-flow.js';

export function handleSummary(data) {
  return {
    'reports/summary.html': htmlReport(data),
    stdout: textSummary(data, { indent: ' ', enableColors: true }),
  };
}

Enter fullscreen mode Exit fullscreen mode

Run normally:

k6 run main.js

Enter fullscreen mode Exit fullscreen mode

A reports/summary.html file is generated automatically after the run.


Running Your Tests

Basic Run

k6 run main.js

Enter fullscreen mode Exit fullscreen mode

Specify VUs and Duration via CLI

k6 run --vus 20 --duration 2m main.js

Enter fullscreen mode Exit fullscreen mode

Run with a Config File

k6 run --config config/load.json main.js

Enter fullscreen mode Exit fullscreen mode

Pass Environment Variables

BASE_URL=https://staging.example.com k6 run main.js

Enter fullscreen mode Exit fullscreen mode

Run with JSON Output

k6 run --out json=reports/results.json main.js

Enter fullscreen mode Exit fullscreen mode

Multiple Outputs at Once

k6 run --out json=reports/results.json --out csv=reports/results.csv main.js

Enter fullscreen mode Exit fullscreen mode

Test Types Reference

Test Type Purpose Typical Config
Smoke Sanity check — does it work at all? 1 VU, 1-2 min
Load Normal expected traffic 50–100 VUs, 5–10 min
Stress Push beyond normal limits 200+ VUs, ramp up
Spike Sudden traffic surge 0 → 500 VUs instantly
Soak Long-running reliability check 50 VUs, 1–8 hours
# Smoke
k6 run --config config/smoke.json main.js

# Load
k6 run --config config/load.json main.js

# Stress
k6 run --config config/stress.json main.js

Enter fullscreen mode Exit fullscreen mode


Understanding the Output

After a test run, k6 prints a summary to the terminal. Here's what a real output looks like:

          /\      |‾‾| /‾‾/   /‾‾/
     /\  /  \     |  |/  /   /  /
    /  \/    \    |     (   /   ‾‾\
   /          \   |  |\  \ |  (‾)  |
  / __________ \  |__| \__\ \_____/ .io

     execution: local
        script: main.js

✓ login successful
✓ profile status 200

checks.........................: 100.00% ✓ 14820   ✗ 0
http_req_duration..............: avg=220ms  min=105ms  med=195ms  max=4.51s  p(90)=360ms  p(95)=430ms
http_req_failed................: 0.00%   ✓ 0   ✗ 7410
http_reqs......................: 7410    24.7/s
vus............................: 1       min=1   max=50

Enter fullscreen mode Exit fullscreen mode

Statistical Values Explained

Stat What it Means
avg Arithmetic mean — useful overview but can be skewed by outliers
min Fastest observed value — best-case scenario
max Slowest observed value — worst-case, often an outlier
med Median (50th percentile) — half of requests were faster than this
p(90) 90% of requests completed within this time
p(95) Industry standard SLO target
p(99) Tail latency — how bad is the worst user experience?

💡 Pro Tip: Always use p(95) or p(99) for your thresholds, not avg. Average hides slow outliers. If p(95) is 430ms, it means 95% of your users got a response within 430ms — that's the metric that reflects real user experience.

Key Metrics Explained

Metric Description
http_req_duration Total time for the request. This is your main performance indicator.
http_req_waiting Time waiting for the server's first byte (TTFB). Reflects server processing time.
http_req_connecting Time to establish TCP connection. High values indicate network issues.
http_req_tls_handshaking TLS/SSL handshake time. Only relevant for HTTPS.
http_req_failed Percentage of non-2xx/3xx responses. Keep this at 0% or very low.
http_reqs Total number of requests made.
vus Current active virtual users.
iterations Total number of times the default function was executed.
data_received / data_sent Bandwidth — useful for spotting payload issues.
checks Pass/fail count of your check() assertions.

Success Criteria with Thresholds

Thresholds are k6's built-in pass/fail mechanism. You define what "passing" means, and k6 exits with code 1 if any threshold is breached — making it perfect for CI/CD pipelines.

Basic Thresholds

export const options = {
  thresholds: {
    // 95% of requests must complete below 500ms
    http_req_duration: ['p(95)<500'],

    // 99% of requests must complete below 1000ms
    'http_req_duration{expected_response:true}': ['p(99)<1000'],

    // Less than 1% of requests can fail
    http_req_failed: ['rate<0.01'],

    // All checks must pass
    checks: ['rate==1.0'],
  },
};

Enter fullscreen mode Exit fullscreen mode

Thresholds Per Endpoint (using Tags)

export default function () {
  const loginRes = http.post(
    `${BASE_URL}/auth/login`,
    JSON.stringify({ username: 'user', password: 'pass' }),
    { tags: { endpoint: 'login' } }
  );

  const profileRes = http.get(
    `${BASE_URL}/api/profile`,
    { tags: { endpoint: 'profile' } }
  );
}

export const options = {
  thresholds: {
    'http_req_duration{endpoint:login}':   ['p(95)<300'],
    'http_req_duration{endpoint:profile}': ['p(95)<200'],
  },
};

Enter fullscreen mode Exit fullscreen mode

Using Thresholds in CI/CD

# GitHub Actions example
- name: Run k6 load test
  run: k6 run --config config/load.json main.js
  # If thresholds fail, this step fails and the pipeline stops

Enter fullscreen mode Exit fullscreen mode

Recommended Threshold Starting Points

Metric Suggested Threshold
http_req_duration p(95) < 500ms for APIs, < 2000ms for pages
http_req_duration p(99) < 1500ms for APIs
http_req_failed < 0.01 (less than 1% errors)
checks == 1.0 (100% of checks pass)

Conclusion

Grafana k6 represents a significant shift in how engineering teams approach performance testing. By treating tests as code — written in JavaScript, versioned in Git, and embedded in CI/CD pipelines — k6 removes the friction that traditionally kept load testing siloed in QA teams or skipped altogether.

Quick summary of what we covered:

  • k6 is modern and QA/SDET/developer-native — no Java, no XML, no GUI dependency
  • Installation is a single binary — works on Windows, macOS, and Linux
  • Project structure matters — separate config from code, keep helpers reusable
  • Built-in HTML dashboard (since v0.49.0) gives real-time visual feedback with zero dependencies
  • Focus on p(95) and p(99) over averages for realistic SLO validation
  • Thresholds are your CI gate — define pass/fail criteria in code, automate quality enforcement

The most important step? Start small. A smoke test with 1 VU is infinitely better than no test at all.


Official Resources