wrk — a HTTP benchmarking tool
wrk is a modern HTTP benchmarking tool capable of generating significant
load when run on a single multi-core CPU. It combines a multithreaded
design with scalable event notification systems such as epoll and kqueue.
An optional LuaJIT script can perform HTTP request generation, response
processing, and custom reporting. Details are available in SCRIPTING and
several examples are located in scripts/.
Basic Usage
wrk -t12 -c400 -d30s http://127.0.0.1:8080/index.html
This runs a benchmark for 30 seconds, using 12 threads, and keeping
400 HTTP connections open.
Output:
Running 30s test @ http://127.0.0.1:8080/index.html
12 threads and 400 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 635.91us 0.89ms 12.92ms 93.69%
Req/Sec 56.20k 8.07k 62.00k 86.54%
22464657 requests in 30.00s, 17.76GB read
Requests/sec: 748868.53
Transfer/sec: 606.33MB
Command Line Options
-c, --connections: total number of HTTP connections to keep open with
each thread handling N = connections/threads
-d, --duration: duration of the test, e.g. 2s, 2m, 2h
-t, --threads: total number of threads to use
-s, --script: LuaJIT script, see SCRIPTING
-H, --header: HTTP header to add to request, e.g. "User-Agent: wrk"
--latency: print detailed latency statistics
--timeout: record a timeout if a response is not received within
this amount of time.
Benchmarking Tips
The machine running wrk must have a sufficient number of ephemeral ports
available and closed sockets should be recycled quickly. To handle the
initial connection burst the server’s listen(2) backlog should be greater
than the number of concurrent connections being tested.
A user script that only changes the HTTP method, path, adds headers or
a body, will have no performance impact. Per-request actions, particularly
building a new HTTP request, and use of response() will necessarily reduce
the amount of load that can be generated.
Acknowledgements
wrk contains code from a number of open source projects including the
‘ae’ event loop from redis, the nginx/joyent/node.js ‘http-parser’,
and Mike Pall’s LuaJIT. Please consult the NOTICE file for licensing
details.
Cryptography Notice
This distribution includes cryptographic software. The country in
which you currently reside may have restrictions on the import,
possession, use, and/or re-export to another country, of encryption
software. BEFORE using any encryption software, please check your
country’s laws, regulations and policies concerning the import,
possession, or use, and re-export of encryption software, to see if
this is permitted. See http://www.wassenaar.org/ for more
information.
The U.S. Government Department of Commerce, Bureau of Industry and
Security (BIS), has classified this software as Export Commodity
Control Number (ECCN) 5D002.C.1, which includes information security
software using or performing cryptographic functions with symmetric
algorithms. The form and manner of this distribution makes it
eligible for export under the License Exception ENC Technology
Software Unrestricted (TSU) exception (see the BIS Export
Administration Regulations, Section 740.13) for both object code and
source code.
Web Server performance testing and benchmarking are essential to understand the load capacity of a web app. The tools highlighted in this article will help you effectively perform load testing and HTTP benchmarking on your web application.
As a Developer and DevOps professional, the performance of your web applications is of high priority. To ensure that the users of your application do not experience glitches and to improve search engine ranking, you must optimize the performance of your application.
Load testing helps to understand the number of requests your application can handle optimally.
Web server benchmarking is the process of testing a web server’s performance to determine how well it can cope with high workloads.
Benchmarking helps you understand which server, tech stacks, and configuration performs best for your application and gives you the benchmark performance when your application will become slow or break down.
The performance benchmark can be shown using various metrics such as the number of requests served within a specified period, the latency for each new connection/request, or the throughput.
To perform load testing and HTTP benchmarking for your application, you need to use tools designed for that purpose. We have highlighted 10 of the most efficient and widely used HTTP benchmarking and load testing tools in this article.
Wrk
If you want a widely used, modern, high performant, and open source benchmarking tool, wrk is your go-to solution.
wrk uses multi-threading, which allows it to leverage multi-core CPU to generate a high workload for testing HTTP connections.
It gives you the liberty to specify the number of HTTP connections, threads, duration, script, and latency for your benchmark.
It is adaptable for various applications and use cases including cryptographic software.
K6
K6 is a popular open source load testing tool written in Golang.
It supports HTTP, gRPC, and WebSocket and provides a flexible test metrics configuration that can be scripted with JavaScript.
It also provides integration with various platforms such as Gitlab, Datadog, Azure, and CircleCI.
You can use K6 on the cloud or install it locally by following the simple installation command for your operating system, provided in its GitHub repository.
Jmeter
Source: https://github.com/apache/jmeter
Apache Jmeter is also one of the most popular tools for load testing.
It is an open source application for load testing and performance measurement. Jmeter is written in Java but supports HTTP(S) protocol for other tech stacks like Node.js, PHP, and ASP.NET.
In addition to the HTTP protocol, Jmeter also supports SOAP/REST web services, FTP, TCP, SMTP, and Java Objects.
Jmeter is a full-featured performance testing application used through the IDE or as a command-line utility.
Autocannon
Source: https://github.com/mcollina/autocannon
Autocannon is a wrk-influenced HTTP benchmarking tool written in node.js. It supports HTTPS and HTTP pipelining and can be used programmatically through an API and as an independent command-line tool.
It can simulate thousands of requests per second and access Node.js worker threads, which makes it even faster than some other tools.
You can easily install it by running:
npm install -g autocannon
Autocannon offers various flexibilities that enable you to specify the number of connections, connection rate, requests, duration, port, maximum connection, timeout, and several other options.
Bombardier
Bombardier is a cross-platform HTTP(S) benchmarking tool written in Go programming language. It uses fasthttp, a Go HTTP implementation for fast and reliable HTTP performance execution.
You can install it by downloading the binaries from the GitHub repository or running;
go get -u github.com/codesenberg/bombardier
SlowHTTPTest
SlowHTTPTest is a flexible and configurable open source testing tool. In contrast to other tools on this list, SlowHTTPTest simulates a Denial of Service (DoS) attack on your web server.
It executes the test by delaying HTTP connections to a server, thereby exposing vulnerabilities and the capacity of concurrent connections the server can run.
Tsung
Written in Erlang, Tsung is developed to simulate high workloads to test the scalability and performance of multiple protocols, including HTTP, SOAP, MySQL, and XMPP.
Tsung is an easy-to-use tool that can generate stately server workloads with high concurrency.
Drill
Drill is a lightweight HTTP load testing tool inspired by the Ansible Syntax. It is an open source tool written in Rust programming language
It is a command-line tool that allows you to specify various conditions, requests, and concurrency in a YAML file.
To install it, you can use cargo or run the following command
cargo install drill
drill --benchmark benchmark.yml --stats
Cassowary
Source: https://github.com/rogerwelin/cassowary
Cassowary is a Go-written cross-platform tool that enables you to test loads on HTTP servers in dual modes.
Cassowary can be installed using the pre-built binary from the official GitHub page or directly using Docker;
$ docker run rogerw/cassowary:v0.14.0 cassowary run -u http://www.example.com -c 1 -n 10
h2load
h2load is a benchmarking tool for HTTP/1 and HTTP/2 with support for SSL and TLS connections. It is a tool built by nghttp2, and it is compiled alongside nghttp2, specifying --enable-app flag and installing the required dependencies.
H2load allows you to specify various benchmark options, including the number of requests, number of concurrent clients, flow control, and multi-threading.
Below is a basic command to perform benchmark to https://localhost using 100 concurrent clients and a max of 9000 requests.
$ h2load -n9000 -c100 https://localhost
Wrk is a powerful HTTP benchmarking tool.
Unfortunately, it does not support Windows OS.
However, we can use WSL (Windows Subsystem for Linux) to run wrk on Windows machine.
You can follow the official guide on how to install WSL.
Open WSL terminal and run the following commands —
sudo apt-get update
sudo apt-get install build-essential libssl-dev unzip git
git clone https://github.com/wg/wrk.git
cd wrk
make
sudo cp wrk /usr/local/bin
Test the installation by running the command wrk.
If you are running your app in Windows on localhost (or 127.0.0.1) it will not be available in the WSL. You have to bind it on 0.0.0.0. It means the server will accept incoming connections from any IP address assigned to the machine.
For example, if you are using Laravel you can use the following command to host your app —
php artisan serve --host=0.0.0.0 --port=8000
To access this inside WSL, use the system’s local IP address. You can find you local IP using the following command —
ipconfig
Look for the IPv4 Address in the output, which will be something like 192.168.0.103.
Now inside WSL, run the following command to start benchmarking —
wrk -t10 -c100 -d1m http://192.168.0.103:8000
The above command will run the benchmark on 10 threads (-t10) with 100 connections/thread (-c100) for the duration of 1 minute (-d1m). You will see the output like —
Running 1m test @ http://192.168.0.103:8000
10 threads and 100 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 56.25ms 55.66ms 714.16ms 90.72%
Req/Sec 219.32 115.31 750.00 65.53%
128562 requests in 1.00m, 19.86MB read
Requests/sec: 2140.40
Transfer/sec: 338.62KB
Открытые бенчмарки для нагрузочного тестирования серверов и веб-приложений
Время на прочтение5 мин
Количество просмотров17K
Это — подборка утилит, составленная на основе рекомендаций резидентов Hacker News и GitHub. В список вошли: Locust, Vegeta, Slow_cooker, k6 и Siege. Ими пользуются инженеры из DICE, EA и Buoyant, а также разработчики Kubernetes и Load Impact. Расскажем об этих инструментах.
Фото — Victor Freitas — Unsplash
Locust.io
Инструмент для нагрузочного тестирования сайтов. Все сценарии пишутся на Python. Специальный веб-интерфейс, построенный на Flask, позволяет мониторить результаты в реальном времени. Авторы Locust — швейцарские инженеры, среди которых числятся сотрудники компаний DICE и EA, занимающихся разработкой и изданием компьютерных игр.
В основу инструмента заложена интересная концепция: Locust («саранча») эмулирует поведение целого роя насекомых (виртуальных пользователей), «атакующих» сайт во время теста. Запросы формируют с помощью сетевой библиотеки для организации параллельных вычислений — gevent. Вот пример простого теста, который приведен на официальном сайте проекта:
from locust import HttpLocust, TaskSet, task
class WebsiteTasks(TaskSet):
def on_start(self):
self.client.post("/login", {
"username": "test_user",
"password": ""
})
@task
def index(self):
self.client.get("/")
@task
def about(self):
self.client.get("/about/")
class WebsiteUser(HttpLocust):
task_set = WebsiteTasks
min_wait = 5000
max_wait = 15000
Locust задействует библиотеку requests. Эта надстройка над стандартными средствами Python упрощает работу с HTTP и SSL и делает код более наглядным. К слову, документацию requests можно использовать в качестве шпаргалки для отладки тестов на Locust.
Этот инструмент для нагрузочного тестирования существует уже более семи лет. За это время вокруг него сформировалось обширное комьюнити — на GitHub более 10 тыс. звезд. Locust использовали при оценке работоспособности сети Battlelog для серии игр Battlefield. Об инструменте положительно отозвался Армин Ронахер (Armin Ronacher), автор фреймворка Flask.
Среди недостатков Locust выделяют довольно низкую производительность и периодические ошибки при оценке времени ответа сайтов. Также инструмент не умеет строить графики, но проблема решается выгрузкой результатов в виде CSV-файлов и отрисовкой графиков в редакторе таблиц.
Если вы хотите поближе познакомиться с Locust, то стоит обратить внимание на документацию инструмента. Также можно рекомендовать выступление Алексея Романова из Wargaming на Python Meetup. Он рассказывает, как писать сценарии, эмулирующие поведение пользователей.
Vegeta
Утилита командной строки для тестирования HTTP-сервисов, написанная на Go. Её можно подключить как библиотеку для создания своих инструментов нагрузочного тестирования. Разработчиком Vegeta выступил один из авторов отрытой платформы Sourcegraph — это движок для рецензирования и навигации по исходному коду, который используют в Lyft, Uber и Yelp.
Vegeta оценивает возможности сетевых ресурсов, «бомбардируя» их запросами с установленной частотой. Например, для проверки localhost достаточно прописать следующую команду:
echo "GET http://localhost/" | vegeta attack -duration=5s | tee results.bin | vegeta report
По умолчанию Vegeta работает со стандартным потоком чтения команд (stdin), поэтому ресурс для тестирования передается через echo. Параметр duration указывает продолжительность теста. Репорт будет сгенерирован в файл results.bin. Отчеты Vegeta генерирует в текстовом формате, но при этом умеет рисовать графики. Сгенерировать их можно следующей командой:
vegeta plot -title=Results results.bin > results-plot.html
Вокруг Vegeta сформировалось крупное сообщество — 12 тыс. звезд на GitHub. Инструмент даже использовали разработчики Kubernetes для оценки производительности своей платформы — тогда Vegeta генерировала около 10 млн запросов в секунду к кластеру из тысячи узлов.
Документация с описанием всех функций и флагов для тестов Vegeta есть в репозитории на GitHub. Там же можно найти предварительно скомпилированные исполняемые файлы.
Slow_cooker
Это — инструмент для нагрузочного тестирования серверов, написанный на Go. Его разработали инженеры из компании Buoyant, которая создает сервисную сеть для Kubernetes — Linkerd. Она является частью Cloud Native Computing Foundation и считается конкурентом Google Istio.
Фото — Joshua Aragon — Unsplash
Обычно утилиты для нагрузочного тестирования проверяют возможности сервера, направляя ему как можно больше запросов за короткое время. Авторы slow_cooker говорят, что их инструмент позволяет оценить работу железа под предсказуемой нагрузкой в течение длительного времени.
Специалисты из Buoyant используют свою разработку для тестирования Linkerd и других сервисов, например nginx. Инструмент довольно молодой — ему около трех — поэтому пока он не обзавелся большим комьюнити. Но в будущем ситуация может измениться, например, его репозиторий уже форкнули в Skysсanner, международном сервисе для поиска авиабилетов.
Исходный код вы можете найти на GitHub.
k6
Инструмент для нагрузочного и регрессионного тестирования микросервисов, контейнеров и сайтов, размещенных в облаке. Он написан на Go и JavaScript разработчиками из Load Impact — это приложение для тестирования «стойкости» сайтов.
Работа с k6 строится по модели everything as code, когда логика тестов и все настройки пишутся на JavaScript. В скриптах отдельные шаги можно объединять в группы (group), что может быть удобно для тех, кто привык следовать принципам BDD. Вот пример такой группы:
import { group } from "k6";
export default function() {
group("user flow: returning user", function() {
group("visit homepage", function() {
// load homepage resources
});
group("login", function() {
// perform login
});
});
};
Также инструмент дает возможность записывать скрипты и строить графики — последняя функция реализована на InfluxDB и Grafana. И у него есть интеграции с CI-системами вроде Jenkins, Circle CI, Team City и GitLab.
Пользователи говорят, что k6 не требователен к ресурсам, и у него удобный API. Но есть и несколько недостатков, в частности, k6 не поддерживает websocket и не умеет проводить тесты на распределенных системах. Хотя разработчики k6 в тематическом треде на Hacker News рассказали, что эти функции появятся в будущем.
Если вы хотите познакомиться с возможностями k6 самостоятельно, резиденты HN рекомендуют начать с технической документации — она подробная и с примерами. Если будут возникать какие-либо вопросы, можно обратиться на официальный форум.
Siege
Siege позволяет провести нагрузочное тестирование веб-серверов. Утилиту создал инженер Джефф Фалмер (Jeff Fulmer), чтобы разработчики могли проверить ресурсоемкость своего кода в условиях, приближенных к боевым. Siege эмулирует непрерывный поток обращений к сайту от множества пользователей, как бы удерживая сервер «под осадой» — отсюда и название инструмента.
После теста утилита показывает: время проверки, число транзакций за секунду, пропускную способность, количество удачных и неудачных запросов, а также их число с ответным кодом 200. Вот пример отчета, генерируемого Siege.
Siege получил довольно широкое распространение в ИТ-сообществе. Например, нагрузочному тестированию с его помощью посвящен целый раздел в книге «NGINX High Performance». Также его используют некоторые облачные провайдеры.
Из недостатков Siege можно выделить нестандартный синтаксис и неочевидные методы подсчета параметров тестирования — например, редиректы считаются успешными транзакциями, поэтому их количество может превышать общее число запросов. Если вы хотите опробовать Siege на практике, изучите онлайн-руководство — там разобраны некоторые «странности» системы.
Дополнительное чтение в блоге 1cloud.ru:
Что нового в Linux kernel 5.3 — графические драйверы, виртуализация и другие обновления
Почему разработчики мейнстрим-браузера снова отказались от отображения поддомена
Почему Apple изменила требования к разработчикам приложений
“This is the 23rd day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021”
Introduction to the
Ab is an Apache Http server benchmark tool. It tests the maximum number of requests the HTTP server can process per second. If you’re testing a Web application service, this translates into how many requests per second the entire application can fulfill.
disadvantages
This is a very simple tool with limited use and can only stress test as fast as possible against a single URL.
How to download and install under Windows (Linux installation is very easy)
Apache HTTP Server Benchmarking Tool (AB
Resource version 2.4
📎 HTTPD 2.4.48 – o111k – x64 – vc15. Zip
Decompress and move to drive C
Run CMD as an administrator, go to the bin directory, and run HTTPD -k install to install Apache as a service.
Port 443 is occupied (everyone may not have the same problem, patience to solve the problem online has a solution!)
What is Port 443
Port 443, or web browsing port, is primarily used for HTTPS services, an alternative HTTP that provides encryption and transport over secure ports. Some websites with high security requirements, such as banks, securities, and shopping, use THE HTTPS service. In this way, other people can capture encrypted data when exchanging information on these websites, ensuring transaction security. The address of the page starts with https://, rather than the usual http://.
Solution Change the number of ports bound to the two configuration files in conf\extra to 444/442
- httpd-ahssl.conf
- httpd-ssl.conf
Netstat -ano checks the port usage and finds that 443 is used. We select a port that is not used in the port
Modify configuration file conf\httpd.conf to change default port 80 to 8080 (or other unused port)
Right-click in the service to start the service
Access the installation address http://localhost:8080/. If the following page is displayed, the login is successful
Parameters that
For details, please refer to the official document AB Parameter Description official website.
Some common parameters are described
| parameter | instructions |
|---|---|
| -n | Root number of requests executed in the test session, default is 1 |
| -c | Number of requests generated at one time, default 1 (concurrent requests) |
| -t | The maximum duration of the test (seconds), with an internal implied value (-n 50000). Can be used to specify a fixed time range for a test. By default, there is no time limit. |
| -p | The file to which the data needs to be posted |
| -T | The Content-Type header used for POST data |
| -v | Set the level of detail displayed – a value of 4 or more displays header information, a value of 3 or more displays response codes (404, 200, etc.), and a value of 2 or more displays warnings and other information. -v Displays the version number and exits. |
| -w | Output the result as an HTML table. Default is a table with two column widths on a white background. |
| -i | Perform HEAD requests instead of GET |
| -C | Cookie-name =value Appends a cookie: line to the request. A pair of arguments to name=value, which can be repeated. |
| -P | Proxy-auth-username :password Provides BASIC authentication trust for a proxy. The username and password are separated by a: and sent base64 encoded. This string is sent whether or not the server needs it (that is, whether or not the 401 authentication requirement code was sent) |
Output code description
In combination with an output sample instructions, ab – 10 – c n 10000 http://localhost:8888/test.html
| The output key | The output value | instructions |
|---|---|---|
| Server Software | Liziba | Server returns the value of Server |
| Server Hostname | localhost | Server host name |
| Server Port | 8888 | Server port |
| Document Path | /test.html | The page document address for the test |
| Document Length | 242313 bytes | Document size |
| Concurrency Level | 10 | concurrency |
| Time taken for tests | 2.661 seconds | The duration of the entire test |
| Complete requests | 10000 | Number of completed requests |
| Failed requests | 0 | Number of failed requests |
| Total transferred | 2423880000 bytes | The amount of network traffic in the entire scenario |
| HTML transferred | 2423130000 bytes | The amount of HTML network traffic in the entire scenario |
| Requests per second | 3757.39 [#/sec] (mean) | Requests completed per second (transactions per second), key indicator, mean means average |
| Time per request | 2.661 [ms] (mean) | Mean indicates the average transaction response time |
| Time per request | 0.266 [ms] (mean, across all concurrent requests) | Average actual elapsed time per request |
| Transfer rate | 889400.26 Kbytes/SEC received | The average traffic per second on the network can help rule out whether the response time is prolonged due to excessive network traffic |
| Connection Times (ms) | min mean[+/-sd] median…… | For a breakdown of time spent on the Web, check out the official website |
| Percentage of the requests served within a certain time (ms) | . | Responses to all requests in the entire scenario. Each request in the scenario has a response time of 50% less than 3ms and 66% less than 3ms… (above) |
