Load testing — simulate high traffic to test performance.
1const http = require("http");23class LoadTester {4 constructor(url, options = {}) {5 this.url = url;6 this.concurrency = options.concurrency || 10;7 this.totalRequests = options.totalRequests || 100;8 this.results = [];9 }1011 async run() {12 const startTime = Date.now();13 const queue = Array.from({ length: this.totalRequests }, (_, i) => i);14 const executing = new Set();1516 while (queue.length > 0 || executing.size > 0) {17 while (executing.size < this.concurrency && queue.length > 0) {18 const task = queue.shift();19 const promise = this.makeRequest(task)20 .then(result => {21 this.results.push(result);22 executing.delete(promise);23 });24 executing.add(promise);25 }26 await Promise.race(executing);27 }2829 return this.getReport(Date.now() - startTime);30 }3132 makeRequest(id) {33 return new Promise((resolve) => {34 const start = Date.now();35 http.get(this.url, (res) => {36 let data = "";37 res.on("data", chunk => data += chunk);38 res.on("end", () => {39 resolve({40 id,41 status: res.statusCode,42 duration: Date.now() - start,43 });44 });45 }).on("error", () => {46 resolve({ id, status: 0, duration: Date.now() - start });47 });48 });49 }5051 getReport(totalDuration) {52 const successful = this.results.filter(r => r.status === 200);53 const durations = this.results.map(r => r.duration);54 durations.sort((a, b) => a - b);5556 return {57 totalRequests: this.results.length,58 successful: successful.length,59 failed: this.results.length - successful.length,60 totalDuration,61 avgDuration: durations.reduce((a, b) => a + b, 0) / durations.length,62 p95Duration: durations[Math.floor(durations.length * 0.95)],63 p99Duration: durations[Math.floor(durations.length * 0.99)],64 rps: this.results.length / (totalDuration / 1000),65 };66 }67}6869const tester = new LoadTester("http://localhost:3000/api", {70 concurrency: 50,71 totalRequests: 1000,72});7374const report = await tester.run();75console.log(report);