### Start Test Server Source: https://github.com/alexfernandez/loadtest/blob/main/doc/tcp-sockets.md Starts the test server. This is a prerequisite for running load tests. ```bash $ node bin/testserver.js ``` -------------------------------- ### Start test server Source: https://github.com/alexfernandez/loadtest/blob/main/README.md Start the test server with a specified number of cores. The server will listen on http://localhost:7357/. ```bash testserver-loadtest --cores 2 Listening on http://localhost:7357/ Listening on http://localhost:7357/ ``` -------------------------------- ### Install Node.js Source: https://github.com/alexfernandez/loadtest/blob/main/doc/cloud-performance.md Install Node.js on Ubuntu using apt. Refer to nodesource for detailed instructions. ```shell sudo apt install nodejs ``` -------------------------------- ### Start Test Server with Callback Source: https://github.com/alexfernandez/loadtest/blob/main/doc/api.md Starts a test server using `startServer` with an optional callback for error handling. This is a legacy approach and does not use async/await. ```javascript const server = startServer({port: 8000}, error => console.error(error)) ``` -------------------------------- ### Start Test Server API Source: https://github.com/alexfernandez/loadtest/blob/main/doc/api.md API for starting a test server with configurable options for simulating load. ```APIDOC ## POST /startServer ### Description Starts a test server that can be used for load testing. It returns a server object with a `close()` method. ### Method `startServer(options, [callback])` ### Parameters #### Options Object - **port** (number) - Optional. The port to use for the server. Defaults to 7357. - **delay** (number) - Optional. The number of milliseconds to wait before answering each request. - **error** (string|number) - Optional. An HTTP error code to return. - **percent** (number) - Optional. The percentage of requests for which to return an HTTP error code. Defaults to 500 if no error code is specified. - **logger** (function) - Optional. A function called after every request served by the test server. It receives `request` and `response` objects. #### Callback Function (Optional) - **error** (Error) - If provided, the function will not behave as async and will call this callback with an error if one occurs. ### Request Example (Async/Promise) ```javascript import { startServer } from 'loadtest'; const server = await startServer({ port: 8000 }); // Perform your load testing await server.close(); ``` ### Request Example (Callback) ```javascript import { startServer } from 'loadtest'; const server = startServer({ port: 8000 }, (error) => { if (error) { console.error(error); } }); // Perform your load testing // server.close() would be called elsewhere ``` ### Response - **server** (object) - An object representing the test server with a `close()` method. - **close()**: Closes the test server. ``` -------------------------------- ### Start Basic Test Server Source: https://context7.com/alexfernandez/loadtest/llms.txt Starts a basic test server for local load testing. Set 'quiet: false' to log requests. ```javascript import { startServer, loadTest } from 'loadtest'; // Start a basic test server const server = await startServer({ port: 8000, quiet: false // Log requests }); console.log('Test server running on http://localhost:8000'); // Run load test against it const result = await loadTest({ url: 'http://localhost:8000', maxRequests: 1000, concurrency: 10, quiet: true }); result.show(); // Cleanup await server.close(); ``` -------------------------------- ### Start Test Server with Async/Await Source: https://github.com/alexfernandez/loadtest/blob/main/doc/api.md Initiates a test server using `startServer` and returns a server object that can be closed. This is the recommended approach using Promises. ```javascript import {startServer} from 'loadtest' const server = await startServer({port: 8000}) // do your thing await server.close() ``` -------------------------------- ### Install Loadtest CLI and API Source: https://context7.com/alexfernandez/loadtest/llms.txt Install the loadtest package globally for CLI usage or as a development dependency for API integration. ```bash npm install -g loadtest ``` ```bash npm install --save-dev loadtest ``` -------------------------------- ### Full `statusCallback` Example Source: https://github.com/alexfernandez/loadtest/blob/main/doc/status-callback.md Demonstrates how to implement and use the `statusCallback` function within the loadtest configuration. This example logs latency, result, and error details for each request. ```javascript import {loadTest} from 'loadtest' function statusCallback(error, result, latency) { console.log('Current latency %j, result %j, error %j', latency, result, error) console.log('----') console.log('Request elapsed milliseconds: ', result.requestElapsed) console.log('Request index: ', result.requestIndex) console.log('Request loadtest() instance index: ', result.instanceIndex) } const options = { url: 'http://localhost:8000', maxRequests: 1000, statusCallback: statusCallback } loadTest(options, function(error) { if (error) { return console.error('Got an error: %s', error) } console.log('Tests run successfully') }) ``` -------------------------------- ### Get Online Help Source: https://github.com/alexfernandez/loadtest/blob/main/README.md Display the help message for the loadtest command by running it without any parameters. ```bash $ loadtest ``` -------------------------------- ### Run TCP Performance Benchmark Source: https://github.com/alexfernandez/loadtest/blob/main/doc/cloud-performance.md Clone the loadtest repository, install dependencies, and run the TCP performance benchmark script. ```shell $ git clone https://github.com/alexfernandez/loadtest $ cd loadtest $ npm install $ node bin/tcp-performance.js ``` -------------------------------- ### Run Test Server with Delay Source: https://github.com/alexfernandez/loadtest/blob/main/README.md Start the bundled test server with a specified delay in milliseconds before answering each request using the --delay option to simulate a busy server. ```bash testserver-loadtest --delay 1000 ``` -------------------------------- ### Custom Request Generator Example Source: https://github.com/alexfernandez/loadtest/blob/main/doc/api.md Provides an example of a custom request generator function. This function should synchronously generate and return the request, setting necessary headers and writing the message body. ```javascript function(params, options, client, callback) { const message = generateMessage(); const request = client(options, callback); options.headers['Content-Length'] = message.length; options.headers['Content-Type'] = 'application/x-www-form-urlencoded'; request.write(message); request.end(); return request; } ``` -------------------------------- ### Start Server with Custom Logger Source: https://context7.com/alexfernandez/loadtest/llms.txt Logs all incoming requests to the test server using a custom logger function. The logger receives request and response objects for inspection. ```javascript import { startServer, loadTest } from 'loadtest'; const requestLog = []; const server = await startServer({ port: 8000, quiet: true, logger: (request, response) => { requestLog.push({ method: request.method, url: request.url, headers: request.headers, body: request.body, timestamp: Date.now() }); } }); await loadTest({ url: 'http://localhost:8000/api/test', maxRequests: 10, method: 'POST', body: { test: 'data' }, contentType: 'application/json', quiet: true }); console.log('Received requests:', requestLog.length); console.log('Sample request:', JSON.stringify(requestLog[0], null, 2)); await server.close(); ``` -------------------------------- ### Start Server with Delay Simulation Source: https://context7.com/alexfernandez/loadtest/llms.txt Simulates slow server responses by introducing a delay. Useful for testing timeout handling. Ensure the load test 'timeout' is greater than the server 'delay'. ```javascript import { startServer, loadTest } from 'loadtest'; // Server with 100ms response delay const server = await startServer({ port: 8000, delay: 100, // Wait 100ms before responding quiet: true }); const result = await loadTest({ url: 'http://localhost:8000', maxRequests: 100, concurrency: 20, timeout: 5000, // 5 second timeout per request quiet: true }); console.log(`Mean latency with 100ms delay: ${result.meanLatencyMs}ms`); // Should be approximately 100ms + network overhead await server.close(); ``` -------------------------------- ### Run Test Server in Multi-Process Mode Source: https://github.com/alexfernandez/loadtest/blob/main/README.md Start the test server in multi-process mode using the --cores option. Since v6.3.0, it defaults to half the available cores; use --cores 1 for single-process mode. ```bash testserver-loadtest --cores 4 ``` -------------------------------- ### Start Server with Custom Body Source: https://context7.com/alexfernandez/loadtest/llms.txt Returns a custom response body from the test server. Use 'body' for string responses or 'file' to read from a file. The 'statusCallback' in loadTest can capture response bodies. ```javascript import { startServer, loadTest } from 'loadtest'; // Server returning custom JSON response const server = await startServer({ port: 8000, body: JSON.stringify({ status: 'ok', message: 'Test response', timestamp: Date.now() }), quiet: true }); let responseBodies = []; await loadTest({ url: 'http://localhost:8000', maxRequests: 5, quiet: true, statusCallback: (error, result) => { responseBodies.push(JSON.parse(result.body)); } }); console.log('Response sample:', responseBodies[0]); await server.close(); ``` -------------------------------- ### Install loadtest Globally Source: https://github.com/alexfernandez/loadtest/blob/main/README.md Install the loadtest package globally using npm. This allows you to run loadtest commands directly from your terminal. ```bash npm install -g loadtest ``` -------------------------------- ### Custom Request Generator Example Source: https://github.com/alexfernandez/loadtest/blob/main/doc/api.md Provides an example of a custom request generator function for advanced use cases. ```APIDOC ## Custom Request Generator ### Description This section provides an example of a custom `requestGenerator` function that can be used to create complex request logic, such as generating dynamic request bodies. ### Method `requestGenerator(params, options, client, callback)` ### Parameters - **params** (object) - Parameters passed to the generator. - **options** (object) - Request options. - **client** (function) - A function to create the client request. - **callback** (function) - A callback function to handle the request. ### Request Example ```javascript function requestGenerator(params, options, client, callback) { const message = generateMessage(); // Assume generateMessage() creates the request body const request = client(options, callback); // Set Content-Length and Content-Type headers dynamically options.headers['Content-Length'] = message.length; options.headers['Content-Type'] = 'application/x-www-form-urlencoded'; request.write(message); request.end(); return request; } // Usage within loadTest options: const options = { url: 'http://localhost:8000', requestGenerator: requestGenerator, // other options... }; // loadTest(options); ``` ### Notes - The request must be generated synchronously. - Refer to [`sample/request-generator.js`](sample/request-generator.js) or [`sample/request-generator.ts`](sample/request-generator.ts) for more detailed examples. ``` -------------------------------- ### Set request method with loadtest Source: https://github.com/alexfernandez/loadtest/blob/main/README.md Use the `-m` or `--method` flag to specify the HTTP method (GET, POST, PUT, DELETE, PATCH). Default is GET. ```bash -m POST ``` -------------------------------- ### Start Server with Error Simulation Source: https://context7.com/alexfernandez/loadtest/llms.txt Simulates server errors by returning a specified HTTP error code for a percentage of requests. Useful for testing error handling. The 'percent' option controls the error rate. ```javascript import { startServer, loadTest } from 'loadtest'; // Server that returns 500 error for 10% of requests const server = await startServer({ port: 8000, error: 503, // HTTP 503 Service Unavailable percent: 10, // 10% of requests return this error quiet: true }); const result = await loadTest({ url: 'http://localhost:8000', maxRequests: 1000, concurrency: 10, quiet: true }); console.log('Error distribution:', result.errorCodes); // { '200': ~900, '503': ~100 } console.log(`Total errors: ${result.totalErrors}`); await server.close(); ``` -------------------------------- ### Run Complete Integration Test with Loadtest Source: https://context7.com/alexfernandez/loadtest/llms.txt Use this snippet to run a full suite of performance tests, including throughput, latency, and keep-alive, within an automated test environment. It requires starting a local server and asserting the test results. ```javascript import { loadTest, startServer } from 'loadtest'; import assert from 'assert'; async function runPerformanceTests() { // Start test server const server = await startServer({ port: 8000, quiet: true }); try { // Test 1: Basic throughput console.log('Running throughput test...'); const throughputResult = await loadTest({ url: 'http://localhost:8000', maxRequests: 1000, concurrency: 10, quiet: true }); assert(throughputResult.effectiveRps > 100, `Throughput too low: ${throughputResult.effectiveRps} rps`); assert(throughputResult.totalErrors === 0, `Unexpected errors: ${throughputResult.totalErrors}`); console.log(` Throughput: ${throughputResult.effectiveRps} req/s ✓`); // Test 2: Latency under load console.log('Running latency test...'); const latencyResult = await loadTest({ url: 'http://localhost:8000', maxSeconds: 10, requestsPerSecond: 200, quiet: true }); assert(latencyResult.percentiles['99'] < 100, `99th percentile too high: ${latencyResult.percentiles['99']}ms`); console.log(` 99th percentile: ${latencyResult.percentiles['99']}ms ✓`); // Test 3: Keep-alive performance console.log('Running keep-alive test...'); const keepAliveResult = await loadTest({ url: 'http://localhost:8000', maxRequests: 1000, concurrency: 10, agentKeepAlive: true, quiet: true }); assert(keepAliveResult.effectiveRps > throughputResult.effectiveRps, 'Keep-alive should improve throughput'); console.log(` Keep-alive throughput: ${keepAliveResult.effectiveRps} req/s ✓`); console.log('\nAll performance tests passed!'); } finally { await server.close(); } } runPerformanceTests().catch(console.error); ``` -------------------------------- ### Wrk Version Check Source: https://github.com/alexfernandez/loadtest/blob/main/doc/tcp-sockets.md Checks the installed version of wrk. This tool is used for load testing. ```bash $ wrk -v wrk debian/4.1.0-3build1 [epoll] ``` -------------------------------- ### Set Secure Protocol Source: https://github.com/alexfernandez/loadtest/blob/main/README.md Specify the TLS/SSL method to use with the -s or --secureProtocol option. For example, use 'TLSv1_method'. ```bash $ loadtest -n 1000 -s TLSv1_method https://www.example.com ``` -------------------------------- ### Barebones TCP Loadtest Source: https://github.com/alexfernandez/loadtest/blob/main/doc/tcp-sockets.md Runs the loadtest tool using a naive barebones TCP socket implementation without parsing responses. Achieves high performance but is only suitable for GET requests without bodies. ```console $ node bin/loadtest.js http://localhost:7357 --cores 1 --tcp [...] Effective rps: 79997 ``` -------------------------------- ### Load test with lower fixed RPS Source: https://github.com/alexfernandez/loadtest/blob/main/README.md Test the server with a lower fixed requests per second rate to find a stable operating point. This example uses 500 rps. ```bash loadtest http://localhost:7357/ -t 20 -c 10 --rps 500 ... Requests: 0, requests per second: 0, mean latency: 0 ms Requests: 2258, requests per second: 452, mean latency: 0 ms Requests: 4757, requests per second: 500, mean latency: 0 ms Requests: 7258, requests per second: 500, mean latency: 0 ms Requests: 9757, requests per second: 500, mean latency: 0 ms ... Requests per second: 500 Completed requests: 9758 Total errors: 0 Total time: 20.002735398000002 s Requests per second: 488 Total time: 20.002735398000002 s Percentage of requests served within a certain time 50% 1 ms 90% 1 ms 95% 1 ms 99% 14 ms 100% 148 ms (longest request) ``` -------------------------------- ### HTTP Request with Keep-Alive Header Source: https://github.com/alexfernandez/loadtest/blob/main/doc/tcp-sockets.md Example of an HTTP request including headers like 'host', 'accept', 'user-agent', and 'Connection: keep-alive'. Performance is maintained around 80 krps. ```http GET / HTTP/1.1 host: localhost:7357 accept: */* user-agent: loadtest/7.1.0 Connection: keep-alive ``` -------------------------------- ### Apache ab Version Check Source: https://github.com/alexfernandez/loadtest/blob/main/doc/tcp-sockets.md Checks the installed version of ApacheBench (ab). This tool is used for load testing but does not support keep-alive. ```bash $ ab -V Version 2.3 <$Revision: 1879490 $>$ ``` -------------------------------- ### Example `result` Object Format Source: https://github.com/alexfernandez/loadtest/blob/main/doc/status-callback.md Illustrates the structure of the `result` object passed to the `statusCallback` function. This object contains details about a single completed request. ```javascript { host: 'localhost', path: '/', method: 'GET', statusCode: 200, body: 'hi', headers: [...], requestElapsed: 248, requestIndex: 8748, instanceIndex: 5, } ``` -------------------------------- ### Enable Multi-Process Mode Source: https://github.com/alexfernandez/loadtest/blob/main/README.md Start loadtest in multi-process mode using the --cores option to utilize multiple CPU cores simultaneously. The total requests and RPS are shared across processes. The default value has changed in version 7+. ```bash --cores 4 ``` -------------------------------- ### Install loadtest as a Dev Dependency Source: https://github.com/alexfernandez/loadtest/blob/main/README.md Install the loadtest package as a development dependency in your project using npm. This is useful for integrating load testing into your project's test suite. ```bash npm install --save-dev loadtest ``` -------------------------------- ### Autocannon Version Check Source: https://github.com/alexfernandez/loadtest/blob/main/doc/tcp-sockets.md Checks the installed version of Autocannon and Node.js. Autocannon uses keep-alive by default. ```bash $ autocannon --version autocannon v7.12.0 node v18.17.1 ``` -------------------------------- ### Basic Command-Line Load Test Source: https://github.com/alexfernandez/loadtest/blob/main/README.md Run a basic load test on a given URL. Specify the maximum number of requests with -n and the concurrency level with -c. Use -k for keep-alive connections. ```bash $ loadtest [-n requests] [-c concurrency] [-k] URL ``` -------------------------------- ### Run Load Test with Client Pooling Source: https://github.com/alexfernandez/loadtest/blob/main/doc/tcp-sockets.md Execute a load test with 1 core and TCP connections after refactoring to implement a pool of clients. This demonstrates the performance impact of the new client management strategy. ```bash $ node bin/loadtest.js http://localhost:7357/ --tcp --cores 1 [...] Effective rps: 60331 ``` -------------------------------- ### Run basic load test Source: https://github.com/alexfernandez/loadtest/blob/main/README.md Perform a load test against a given URL for a specified duration and concurrency. Results include requests per second and mean latency. ```bash loadtest http://localhost:7357/ -t 20 -c 10 ... Requests: 9589, requests per second: 1915, mean latency: 10 ms Requests: 16375, requests per second: 1359, mean latency: 10 ms Requests: 16375, requests per second: 0, mean latency: 0 ms ... Completed requests: 16376 Requests per second: 368 Total time: 44.503181166000005 s Percentage of requests served within a certain time 50% 4 ms 90% 5 ms 95% 6 ms 99% 14 ms 100% 35997 ms (longest request) ``` -------------------------------- ### Display Ubuntu Version Source: https://github.com/alexfernandez/loadtest/blob/main/doc/cloud-performance.md Use this command to display the Ubuntu version. Ensure you are running Ubuntu 22.04 LTS. ```shell $ lsb_release -a No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 22.04.3 LTS Release: 22.04 Codename: jammy ``` -------------------------------- ### Run Apache ab Test Source: https://github.com/alexfernandez/loadtest/blob/main/doc/tcp-sockets.md Executes a load test using Apache ab with 10 concurrent connections and a 10-second duration. Keep-alive is not supported. ```bash $ ab -t 10 -c 10 http://localhost:7357/ ``` -------------------------------- ### Programmatic load test invocation Source: https://github.com/alexfernandez/loadtest/blob/main/README.md Use the loadTest API to run load tests programmatically within your application. This example shows basic configuration with URL and maxRequests. ```javascript import {loadTest} from 'loadtest' const options = { url: 'http://localhost:8000', maxRequests: 1000, } const result = await loadTest(options) result.show() console.log('Tests run successfully') ``` -------------------------------- ### Invoke Load Test with Async/Await Source: https://github.com/alexfernandez/loadtest/blob/main/doc/api.md Demonstrates how to invoke a load test using async/await syntax with the `loadTest` function. ```APIDOC ## Invoke Load Test with Async/Await ### Description This example shows how to run a load test using the `loadTest` function with promises (async/await). ### Method `loadTest(options)` ### Parameters #### Request Body - **options** (object) - Required - Configuration options for the load test. - **url** (string) - Required - The URL to invoke. - **maxSeconds** (number) - Optional - Maximum number of seconds to run the tests. Defaults to 10 if `maxRequests` is not specified. - **maxRequests** (number) - Optional - Maximum number of requests to perform. If not specified, the test runs until `maxSeconds` is reached. - **concurrency** (number) - Optional - Number of parallel clients. Defaults to 10. Does not apply if `requestsPerSecond` is specified. - **timeout** (number) - Optional - Timeout for each request in milliseconds. 0 disables timeout (default). - **cookies** (array) - Optional - An array of cookies to send (e.g., `["name=value"]`). - **headers** (object) - Optional - An object containing request headers (e.g., `{"Content-Type": "application/json"}`). - **method** (string) - Optional - HTTP method to use (e.g., 'POST', 'PUT'). Defaults to 'GET'. - **body** (string|object) - Optional - The request body for POST or PUT requests. - **contentType** (string) - Optional - The MIME type for the request body. Defaults to 'text/plain'. - **requestsPerSecond** (number) - Optional - Number of requests to send per second globally. - **requestGenerator** (function) - Optional - A custom function to generate requests. - **agentKeepAlive** (boolean) - Optional - Use an agent with 'Connection: Keep-alive'. - **quiet** (boolean) - Optional - Suppress console messages. ### Request Example ```javascript import { loadTest } from 'loadtest'; const options = { url: 'http://localhost:8000', maxRequests: 1000, }; const result = await loadTest(options); result.show(); console.log('Tests run successfully'); ``` ### Response #### Success Response (200) - **result** (object) - An object containing the load test results. Call `result.show()` to display details. #### Response Example ```javascript // Assuming result.show() has been called and logs to console. console.log('Tests run successfully'); ``` ``` -------------------------------- ### Specify Client Key Source: https://github.com/alexfernandez/loadtest/blob/main/README.md Set the client key for the HTTP client using the --key option. This must be used in conjunction with the --cert option. ```bash --key path/to/key.pem ``` -------------------------------- ### Test Server and Loadtest Script Source: https://github.com/alexfernandez/loadtest/blob/main/README.md Run the test server and the loadtest script simultaneously on different consoles to measure the practical limits of the loadtest tool. ```bash $ node bin/testserver.js $ node bin/loadtest.js -n 1000000 -c 100 http://localhost:7357/ ``` -------------------------------- ### Baseline HTTP Loadtest (With Keep-Alive) Source: https://github.com/alexfernandez/loadtest/blob/main/doc/tcp-sockets.md Runs the loadtest tool with the default HTTP implementation with keep-alive enabled. Demonstrates significant performance improvement over the non-keep-alive version. ```console $ node bin/loadtest.js http://localhost:7357 --cores 1 -k [...] Effective rps: 20490 ``` -------------------------------- ### Run Load Test with Multiple Cores Source: https://github.com/alexfernandez/loadtest/blob/main/doc/tcp-sockets.md Execute a load test against a local HTTP server using 3 cores and TCP connections. This configuration aims to maximize throughput. ```bash $ node bin/loadtest.js http://localhost:7357 --cores 3 --tcp [...] Effective rps: 115379 ``` -------------------------------- ### Use Custom Request Generator Source: https://github.com/alexfernandez/loadtest/blob/main/README.md Employ a custom request generator function from an external file using the -R option. Refer to the documentation for examples on creating request generator modules. ```bash -R requestGeneratorModule.js ``` -------------------------------- ### Loadtest with Basic Response Parsing Source: https://github.com/alexfernandez/loadtest/blob/main/doc/tcp-sockets.md Runs loadtest with a simple response parsing implementation that reads the first line to extract the status code. Performance drops to around 68 krps, assuming responses fit in one packet. ```console $ node bin/loadtest.js http://localhost:7357 --cores 1 [...] Effective rps: 68000 ``` -------------------------------- ### Add data to request body with loadtest Source: https://github.com/alexfernandez/loadtest/blob/main/README.md Use the `--data` flag to add data to the request body. Requires `-m` for the method and `-T` for the content type. Does not support GET method. ```bash --data '{"username": "test", "password": "test"}' -T 'application/x-www-form-urlencoded' -m POST ``` -------------------------------- ### Specify Client Certificate Source: https://github.com/alexfernandez/loadtest/blob/main/README.md Set the client certificate for the HTTP client using the --cert option. This must be used in conjunction with the --key option. ```bash --cert path/to/cert.pem ``` -------------------------------- ### Run Test Server with Error Percentage Source: https://github.com/alexfernandez/loadtest/blob/main/README.md Simulate errors on a specified percentage of requests using the --percent option. The default error is 500. ```bash testserver-loadtest --percent 20 ``` -------------------------------- ### Run Test Server with Fixed Error Source: https://github.com/alexfernandez/loadtest/blob/main/README.md Configure the test server to return a specific error code for every request using the --error option. ```bash testserver-loadtest --error 503 ``` -------------------------------- ### Run Load Test with HTTP Keep-Alive Source: https://github.com/alexfernandez/loadtest/blob/main/doc/tcp-sockets.md Run a load test using standard HTTP connections with keep-alive enabled and 3 cores. This demonstrates performance without TCP optimization. ```bash $ node bin/loadtest.js http://localhost:7357/ -k --cores 3 [...] Effective rps: 54432 ``` -------------------------------- ### Bare Iron Benchmark Results (Apple M1 Pro - Second Instance) Source: https://github.com/alexfernandez/loadtest/blob/main/doc/cloud-performance.md Benchmark results for a Mac with an Apple M1 Pro CPU. The results are an average of three runs, rounded to the nearest krps. ```text Effective rps: 84219 ``` -------------------------------- ### Run Wrk Load Test Source: https://github.com/alexfernandez/loadtest/blob/main/doc/tcp-sockets.md Execute a load test using the wrk tool with 3 threads. This is used for performance comparison against other tools. ```bash $ wrk http://localhost:7357/ -t 3 [...] Requests/sec: 118164.03 ``` -------------------------------- ### Invoke Load Test with Callback Source: https://github.com/alexfernandez/loadtest/blob/main/doc/api.md Demonstrates how to invoke a load test using a callback function for older JavaScript environments or specific control flow. ```APIDOC ## Invoke Load Test with Callback ### Description This example shows how to run a load test using a callback function as the second argument to `loadTest`. This approach is used for legacy reasons and bypasses the async/await behavior. ### Method `loadTest(options, callback)` ### Parameters #### Request Body - **options** (object) - Required - Configuration options for the load test (see `Invoke Load Test with Async/Await` for details). - **callback** (function) - Optional - A function that will be invoked when the test completes or an error occurs. It receives `(error, result)` as arguments. ### Request Example ```javascript import { loadTest } from 'loadtest'; const options = { url: 'http://localhost:8000', maxRequests: 1000, }; loadTest(options, function(error, result) { if (error) { return console.error('Got an error: %s', error); } result.show(); console.log('Tests run successfully'); }); ``` ### Response #### Success Response (200) - **result** (object) - An object containing the load test results. Call `result.show()` to display details. #### Response Example ```javascript // Inside the callback function: if (error) { console.error('Got an error: %s', error); } else { result.show(); console.log('Tests run successfully'); } ``` ``` -------------------------------- ### Bare Iron Benchmark Results (Intel Core i5 - 2015) Source: https://github.com/alexfernandez/loadtest/blob/main/doc/cloud-performance.md Benchmark results for a MacBookPro12,1 2015 with an Intel Core i5 (2 cores) CPU. The results are an average of three runs, rounded to the nearest krps. ```text Effective rps: 9754 Effective rps: 10002 Effective rps: 10792 ``` -------------------------------- ### Basic Load Test CLI Source: https://context7.com/alexfernandez/loadtest/llms.txt Perform a basic load test against a URL with specified number of requests and concurrency, or duration and keep-alive connections, or a fixed requests-per-second rate. ```bash # Run 1000 requests with concurrency of 10 loadtest -n 1000 -c 10 http://localhost:8000/ ``` ```bash # Run for 20 seconds with keep-alive connections loadtest -t 20 -c 10 -k http://localhost:8000/ ``` ```bash # Fixed rate of 200 requests per second loadtest -c 10 --rps 200 http://localhost:8000/ ``` -------------------------------- ### Run HTTP Load Test with Bun Source: https://github.com/alexfernandez/loadtest/blob/main/doc/cloud-performance.md Performs an HTTP load test using Bun, specifying 1 core and enabling keepalive. Use this for testing HTTP performance with Bun. ```bash bun bin/loadtest.js http://localhost:80/ --cores 1 -k ``` -------------------------------- ### Bare Iron Benchmark Results (Intel Core i5-12400T) Source: https://github.com/alexfernandez/loadtest/blob/main/doc/cloud-performance.md Benchmark results for a bare iron server with an Intel Core i5-12400T CPU. The results are an average of three runs, rounded to the nearest krps. ```text Effective rps: 68391 Effective rps: 69082 Effective rps: 68044 ``` -------------------------------- ### Run HTTP Load Test with Node.js Source: https://github.com/alexfernandez/loadtest/blob/main/doc/cloud-performance.md Performs an HTTP load test using Node.js, specifying 1 core and enabling keepalive. Use this for comparing HTTP performance with Node.js. ```bash node bin/loadtest.js http://localhost:80/ --cores 1 -k ``` -------------------------------- ### Bare Iron Benchmark Results (Intel Core i5-1340P) Source: https://github.com/alexfernandez/loadtest/blob/main/doc/cloud-performance.md Benchmark results for a laptop with an Intel Core i5-1340P CPU. The results are an average of three runs, rounded to the nearest krps. ```text Effective rps: 172586 Effective rps: 171574 Effective rps: 173009 ``` -------------------------------- ### Run Autocannon Test (Keep-Alive Enabled) Source: https://github.com/alexfernandez/loadtest/blob/main/doc/tcp-sockets.md Runs a load test using Autocannon. By default, it uses 10 concurrent connections and keep-alive is enabled. ```bash $ autocannon http://localhost:7357/ ``` -------------------------------- ### Send POST data with loadtest Source: https://github.com/alexfernandez/loadtest/blob/main/README.md Use the `-P` or `--postBody` flag to send a string as the POST body. Use `-T` to set the content type. ```bash -P '{"key": "a9acf03f"}' ``` -------------------------------- ### Bare Iron Benchmark Results (Intel Core i5-10210U) Source: https://github.com/alexfernandez/loadtest/blob/main/doc/cloud-performance.md Benchmark results for a laptop with an Intel Core i5-10210U CPU. The results are an average of three runs, rounded to the nearest krps. ```text Effective rps: 41561 Effective rps: 41797 Effective rps: 42207 ``` -------------------------------- ### .loadtestrc Configuration File Source: https://context7.com/alexfernandez/loadtest/llms.txt Configures default load test options via a JSON file in the project root. Command-line options override these settings. ```json { "maxRequests": 1000, "concurrency": 10, "timeout": 5000, "method": "GET", "contentType": "application/json", "headers": { "Authorization": "Bearer default-token", "Accept": "application/json" }, "cookies": { "session": "default-session-id" }, "agentKeepAlive": true, "insecure": false, "requestsPerSecond": 100, "recover": true } ``` -------------------------------- ### Loadtest with Content-Length Parsing Source: https://github.com/alexfernandez/loadtest/blob/main/doc/tcp-sockets.md Implements parsing of the 'content-length' header and checks against body length for complete responses. Performance is further reduced to approximately 63 krps. ```console $ node bin/loadtest.js http://localhost:7357 --cores 1 [...] Effective rps: 63000 ``` -------------------------------- ### Run Autocannon Load Test Source: https://github.com/alexfernandez/loadtest/blob/main/doc/tcp-sockets.md Execute a load test using the autocannon tool with 3 workers and 30 concurrent connections. This serves as a benchmark for comparison. ```bash $ autocannon http://localhost:7357/ -w 3 -c 30 [...] ┌───────────┬───────┬───────┬─────────┬─────────┬──────────┬─────────┬───────┐ │ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ ├───────────┼───────┼───────┼─────────┼─────────┼──────────┼─────────┼───────┤ │ Req/Sec │ 88511 │ 88511 │ 107071 │ 110079 │ 105132.8 │ 6148.39 │ 88460 │ ├───────────┼───────┼───────┼─────────┼─────────┼──────────┼─────────┼───────┤ │ Bytes/Sec │ 11 MB │ 11 MB │ 13.3 MB │ 13.6 MB │ 13 MB │ 764 kB │ 11 MB │ └───────────┴───────┴───────┴─────────┴─────────┴──────────┴─────────┴───────┘ ``` -------------------------------- ### Multi-Core Load Testing CLI Source: https://context7.com/alexfernandez/loadtest/llms.txt Utilize multiple CPU cores for increased throughput during load tests, or run in single-core mode for simpler testing scenarios. ```bash # Use 4 CPU cores (default is half available CPUs) loadtest -n 100000 --cores 4 --rps 5000 http://localhost:8000/ ``` ```bash # Single-core mode for simpler testing loadtest -n 1000 --cores 1 http://localhost:8000/ ``` -------------------------------- ### Barebones TCP Loadtest (No Keep-Alive) Source: https://github.com/alexfernandez/loadtest/blob/main/doc/tcp-sockets.md Runs the loadtest tool with a barebones TCP socket implementation without keep-alive, creating a new socket for each request. Performance is significantly lower due to socket creation overhead. ```console $ node bin/loadtest.js http://localhost:7357 --cores 1 --tcp [...] Effective rps: 10000 ``` -------------------------------- ### Baseline HTTP Loadtest (No Keep-Alive) Source: https://github.com/alexfernandez/loadtest/blob/main/doc/tcp-sockets.md Runs the loadtest tool with the default HTTP implementation without keep-alive enabled. Useful for establishing a baseline performance metric. ```console $ node bin/loadtest.js http://localhost:7357 --cores 1 [...] Effective rps: 6342 ``` -------------------------------- ### Loadtest with TCP and 3 Cores against Nginx Source: https://github.com/alexfernandez/loadtest/blob/main/doc/tcp-sockets.md Run loadtest against a local Nginx server using TCP sockets with three cores. This test measures the effective requests per second (krps) achieved with multi-core utilization. ```bash $ node bin/loadtest.js http://localhost:80/ --tcp --cores 3 [...] Effective rps: 110858 ``` -------------------------------- ### Loadtest without TCP and 3 Cores against Nginx Source: https://github.com/alexfernandez/loadtest/blob/main/doc/tcp-sockets.md Run loadtest against a local Nginx server without using TCP sockets, utilizing three cores. This demonstrates the performance difference compared to using TCP with multiple cores. ```bash $ node bin/loadtest.js http://localhost:80/ --cores 3 [...] (Implied result of 49 krps) ``` -------------------------------- ### Bare Iron Benchmark Results (Apple M1 Max) Source: https://github.com/alexfernandez/loadtest/blob/main/doc/cloud-performance.md Benchmark results for a Mac with an Apple M1 Max CPU. The results are an average of three runs, rounded to the nearest krps. ```text Effective rps: 77497 ``` -------------------------------- ### loadTest with TCP Sockets (Experimental) Source: https://context7.com/alexfernandez/loadtest/llms.txt Enable TCP sockets for significantly faster performance in local testing scenarios. The `tcp` option bypasses the standard HTTP library for raw TCP connections, potentially increasing performance by up to 10x. ```javascript import { loadTest } from 'loadtest'; const options = { url: 'http://localhost:8000/api/fast', maxRequests: 100000, method: 'GET', tcp: true, // Experimental: use raw TCP sockets quiet: true }; // Note: tcp mode is not compatible with: // - indexParam // - statusCallback // - requestGenerator const result = await loadTest(options); console.log(`High-performance test: ${result.effectiveRps} req/s`); result.show(); ``` -------------------------------- ### Bare Iron Benchmark Results (Intel Core i7-9750H) Source: https://github.com/alexfernandez/loadtest/blob/main/doc/cloud-performance.md Benchmark results for a laptop with an Intel Core i7-9750H CPU. The results are an average of three runs, rounded to the nearest krps. ```text Effective rps: 31878 [...] Effective rps: 42439 ``` -------------------------------- ### Run Wrk Test (Single Thread) Source: https://github.com/alexfernandez/loadtest/blob/main/doc/tcp-sockets.md Executes a load test using wrk with a single thread for fair comparison. This test uses keep-alive. ```bash $ wrk http://localhost:7357/ -t 1 ``` -------------------------------- ### Run TCP Load Test with Bun Source: https://github.com/alexfernandez/loadtest/blob/main/doc/cloud-performance.md Executes a TCP load test using Bun, specifying 1 core and enabling keepalive with the --tcp flag. This tests raw TCP socket performance. ```bash bun bin/loadtest.js http://localhost:80/ --cores 1 -k --tcp ``` -------------------------------- ### Use Low-Level TCP Sockets Source: https://github.com/alexfernandez/loadtest/blob/main/README.md Enable the experimental --tcp option to utilize low-level TCP sockets for potentially faster HTTP requests. Note that not all options are supported with this experimental feature. ```bash --tcp ``` -------------------------------- ### Bare Iron Benchmark Results (8-Core Intel Core i9) Source: https://github.com/alexfernandez/loadtest/blob/main/doc/cloud-performance.md Benchmark results for a MacBookPro15,1 with an 8-Core Intel Core i9 CPU. The results are an average of three runs, rounded to the nearest krps. ```text Effective rps: 38118 ``` -------------------------------- ### Loadtest with TCP and 1 Core against Nginx Source: https://github.com/alexfernandez/loadtest/blob/main/doc/tcp-sockets.md Run loadtest against a local Nginx server using TCP sockets with a single core. This test measures the effective requests per second (krps) achieved. ```bash $ node bin/loadtest.js http://localhost:80/ --tcp --cores 1 [...] Effective rps: 61059 ``` -------------------------------- ### Invoke Load Test with Async/Await Source: https://github.com/alexfernandez/loadtest/blob/main/doc/api.md Use this snippet to run a load test asynchronously using async/await. Ensure the loadTest function is imported and options are configured. ```javascript import {loadTest} from 'loadtest' const options = { url: 'http://localhost:8000', maxRequests: 1000, } const result = await loadTest(options) result.show() console.log('Tests run successfully') ``` -------------------------------- ### Bare Iron Benchmark Results (Intel Core i9-12900HK) Source: https://github.com/alexfernandez/loadtest/blob/main/doc/cloud-performance.md Benchmark results for a Dell laptop with an Intel Core i9-12900HK CPU. The results are an average of three runs, rounded to the nearest krps. ```text Effective rps: 162517 ``` -------------------------------- ### Bare Iron Benchmark Results (AMD Ryzen 7) Source: https://github.com/alexfernandez/loadtest/blob/main/doc/cloud-performance.md Benchmark results for a laptop with an AMD Ryzen 7 CPU. The results are an average of three runs, rounded to the nearest krps. ```text Effective rps: 45940 ``` -------------------------------- ### Run TCP Load Test with Node.js Source: https://github.com/alexfernandez/loadtest/blob/main/doc/cloud-performance.md Executes a TCP load test using Node.js, specifying 1 core and enabling keepalive with the --tcp flag. This tests raw TCP socket performance. ```bash node bin/loadtest.js http://localhost:80/ --cores 1 -k --tcp ``` -------------------------------- ### WebSocket Load Test CLI Source: https://context7.com/alexfernandez/loadtest/llms.txt Conduct load tests against WebSocket endpoints, specifying the number of requests and concurrent connections. ```bash # WebSocket load test loadtest -n 1000 -c 50 ws://localhost:8000/socket ``` -------------------------------- ### JavaScript API: Basic Load Test Source: https://context7.com/alexfernandez/loadtest/llms.txt Programmatically run a load test using the `loadTest` function with configurable options. It returns a Promise that resolves to a detailed result object. ```javascript import { loadTest } from 'loadtest'; const options = { url: 'http://localhost:8000/api/users', maxRequests: 1000, concurrency: 10, method: 'GET', headers: { 'Authorization': 'Bearer your-token-here', 'Accept': 'application/json' }, timeout: 5000, quiet: true }; try { const result = await loadTest(options); console.log('Load Test Results:'); console.log('Total Requests:', result.totalRequests); console.log('Total Errors:', result.totalErrors); console.log('Requests/sec:', result.effectiveRps); console.log('Mean Latency:', result.meanLatencyMs, 'ms'); console.log('Max Latency:', result.maxLatencyMs, 'ms'); console.log('Percentiles:', result.percentiles); // { '50': 7, '90': 10, '95': 11, '99': 15 } console.log('Error Codes:', result.errorCodes); // { '200': 997, '500': 3 } // Or display formatted results result.show(); } catch (error) { console.error('Load test failed:', error); } ```