Overview of autocannon
masterwrk and wrk2 and provides support for HTTP pipelining and HTTPS. It is designed to generate high load for performance testing.repository·master·Indexed 25 days ago
https://github.com/mcollina/autocannonA high-performance HTTP/1.1 benchmarking tool written in Node.js, designed to test server performance with support for HTTPS and HTTP pipelining. It can be used as a command-line tool or programmatically via its API to generate high load for performance testing. Version 8.0.0.
wrk and wrk2 and provides support for HTTP pipelining and HTTPS. It is designed to generate high load for performance testing.Autocannon is a JavaScript-based tool for the Node.js runtime and is CPU-bound. Because it is single-threaded, it may saturate the CPU (reaching 100% load) sooner than binary-compiled tools like wrk.
Key considerations:
autocannon process reaches 100% CPU, it may become the bottleneck. In such cases, consider using wrk2.wrk.You can use a HAR (HTTP Archive) file to drive the benchmark using --har FILE.
CAUTION: You must specify one or more domains using the URL option; autocannon will only consider HAR requests that match those domains. When using a HAR file, -m/--method, -F/--form, -i/--input, and -b/--body are ignored, though you can still add extra headers using -H/--headers.
autocannon globally to use it as a command-line tool, or install it as a local dependency if you intend to use its API programmatically within your Node.js applications.The --on-port flag allows autocannon to automatically detect when a server has started by spawning the process itself. This is useful for benchmarking a server script directly.
When --on-port is used, autocannon spawns the command provided after the -- delimiter. It uses a socket to communicate the port to the benchmark runner.
Example usage:
0x --on-port 'autocannon /path' -- node server.js
Note: This requires the async_hooks built-in module (Node 8.1+).
0x --on-port 'autocannon /path' -- node server.jsThe Client object is passed to the setupClient option and the response event. Use it to dynamically mutate headers, bodies, or the entire request for each connection/request.
Methods:
client.setHeaders(headers): Set request headers (Object or undefined to remove).client.setBody(body): Set request body (String, Buffer, or undefined to remove).client.setHeadersAndBody(headers, body): Set both simultaneously.client.setRequest(request): Mutate the entire request object (attributes: headers, body, method, path).client.setRequests(newRequests): Overwrite the entire requests array.Client Events:
headers: Emitted when request headers are received (passes Object).body: Emitted when response body is received (passes Buffer).response: Emitted when a complete response is received (passes statusCode, resBytes, responseTime).reset: Emitted when the requests pipeline was reset.'use strict'
const autocannon = require('autocannon')
const instance = autocannon({
url: 'http://localhost:3000',
setupClient: setupClient
}, (err, result) => handleResults(result))
instance.on('done', handleResults)
instance.on('tick', () => console.log('ticking'))
instance.on('response', handleResponse)
function setupClient (client) {
client.on('body', console.log) // log response body
}
function handleResponse (client, statusCode, resBytes, responseTime) {
console.log(`Got response with code ${statusCode} in ${responseTime} milliseconds`)
// update the body or headers for the next request
client.setHeaders({new: 'header'})
client.setBody('new body')
client.setHeadersAndBody({new: 'header'}, 'new body')
}
function handleResults(result) {
// ...
}To utilize multiple threads, set the workers parameter. Autocannon divides amount and connections among workers.
Important: When using workers, any option that accepts a function (like setupClient, verifyBody, onResponse, or setupRequest) must be passed as an absolute file path to a script that can be required, because functions cannot be cloned across worker threads.
'use strict'
const autocannon = require('autocannon')
autocannon({
url: 'http://localhost:3000',
connections: 10,
duration: 10,
workers: 4,
setupClient: '/full/path/to/setup-client.js',
verifyBody: '/full/path/to/verify-body.js',
requests: [
{
onResponse: '/full/path/to/on-response.js',
setupRequest: '/full/path/to/setup-request.js'
}
]
}, console.log)Import autocannon to run load tests within your Node.js application. You can use a callback pattern or async/await.
'use strict'
const autocannon = require('autocannon')
// Callback pattern
autocannon({
url: 'http://localhost:3000',
connections: 10,
pipelining: 1,
duration: 10
}, console.log)
// async/await pattern
async function foo () {
const result = await autocannon({
url: 'http://localhost:3000',
connections: 10,
pipelining: 1,
duration: 10
})
console.log(result)
}Start a benchmark against a target URL by calling autocannon(opts[, cb]).
Parameters:
opts: Configuration object (Required).cb: Callback function called on completion. Receives (err, results).If cb is omitted, the function returns an EventEmitter instance that can also be used as a Promise.
Key Configuration Options (opts):
url (Required): The target HTTP or HTTPS URL. Multiple URLs are allowed.connections: Number of concurrent connections (default: 10).duration: Seconds to run (default: 10). Can be a timestring.amount: Total number of requests to make. Overrides duration.method: HTTP method (default: 'GET').headers: Object containing request headers.body: String or Buffer for the request body. Use [<id>] for random ID replacement if idReplacement: true is set.workers: Number of worker threads.pipelining: Number of pipelined requests per connection (default: 1).overallRate: Rate of requests per second from all connections.connectionRate: Rate of requests per second from each individual connection.idReplacement: Boolean to enable [<id>] tag replacement in the body (default: false).forever: Boolean to restart the instance indefinitely after the done event (default: false).Use autocannon.track(instance, opts) to programmatically monitor the progress of an active benchmark instance. This is useful for rendering progress bars or tables to the terminal.
Options (opts):
outputStream: Stream to output to (default: process.stderr).renderProgressBar: Enable/disable progress bar (default: true).renderResultsTable: Enable/disable results table on completion (default: true).renderLatencyTable: Enable/disable advanced latency table (default: false).progressBarString: Format for the progress display (must be valid progress module syntax).'use strict'
const autocannon = require('autocannon')
const instance = autocannon({
url: 'http://localhost:3000'
}, console.log)
// this is used to kill the instance on CTRL-C
process.once('SIGINT', () => {
instance.stop()
})
// just render results
autocannon.track(instance, {renderProgressBar: false})Convert an autocannon result object into a formatted text string containing result tables using autocannon.printResult(resultObject, opts).
"use strict";
const { stdout } = require("node:process");
const autocannon = require("autocannon");
function print(result) {
stdout.write(autocannon.printResult(result));
}
autocannon({ url: "http://localhost:3000" }, (err, result) => print(result));Aggregate results from multiple autocannon instances into a single report. This is intended for advanced use cases like load testing across multiple machines.
Note: The input results must be from instances that were run with the skipAggregateResult: true option.
Parameters:
results: Array of autocannon instance results.opts: Configuration options (subset of autocannon(opts)). url is Required.