Skip to content

Instantly share code, notes, and snippets.

@shuhei
Last active November 17, 2016 22:58
Show Gist options
  • Save shuhei/9b6b802f4f3a7ceaaaedd412698afecf to your computer and use it in GitHub Desktop.
Save shuhei/9b6b802f4f3a7ceaaaedd412698afecf to your computer and use it in GitHub Desktop.
experiment on http.globalAgent.maxSockets of Node.js

It was fastest without maxSockets until the client gets Error: connect ECONNRESET 127.0.0.1:8080. maxSockets avoided the error but didn't work for performance.

const http = require('http');
const REQ_COUNT = 10000;
http.globalAgent.maxSockets = 10000;
// http.globalAgent.maxSockets = Number.POSITIVE_INFINITY;
const request = () => new Promise((resolve, reject) => {
http.get('http://localhost:8080', (res) => {
let buffer = '';
res.setEncoding('utf-8');
res.on('readable', (chunk) => {
buffer += res.read();
});
res.on('end', () => {
resolve(buffer);
});
res.on('error', (e) => {
reject(e);
});
});
});
const timeout = (ms) => new Promise((resolve) => {
setTimeout(resolve, ms);
});
const start = process.hrtime();
const promises = Array(REQ_COUNT).fill(0)
.map(() => timeout(100 * Math.random()).then(request));
Promise.all(promises)
.then(() => {
const [s, ns] = process.hrtime(start);
console.log('done', REQ_COUNT, s * 1000.0 + ns / 1000000.0, 'ms');
})
.catch((e) => {
console.error('error', e);
});
const http = require('http');
const server = http.createServer((req, res) => {
const timeout = 30 + Math.floor(Math.random() * 100);
setTimeout(() => {
res.writeHead(200, {
'Content-Type': 'application/json',
});
res.end(JSON.stringify({ hello: 'world', timeout }));
}, timeout);
});
server.listen(8080, () => {
const { address, port } = server.address();
console.log(`Listening on ${address}:${port}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment