Skip to content

Commit db18aca

Browse files
theanarkhaduh95
authored andcommitted
lib: add flag to drop connection when running in cluster mode
PR-URL: #54927 Refs: #54882 Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent 9b7b4a6 commit db18aca

File tree

3 files changed

+39
-3
lines changed

3 files changed

+39
-3
lines changed

doc/api/net.md

+15-2
Original file line numberDiff line numberDiff line change
@@ -603,12 +603,25 @@ changes:
603603

604604
* {integer}
605605

606-
Set this property to reject connections when the server's connection count gets
607-
high.
606+
When the number of connections reaches the `server.maxConnections` threshold:
607+
608+
1. If the process is not running in cluster mode, Node.js will close the connection.
609+
610+
2. If the process is running in cluster mode, Node.js will, by default, route the connection to another worker process. To close the connection instead, set \[`server.dropMaxConnection`]\[] to `true`.
608611

609612
It is not recommended to use this option once a socket has been sent to a child
610613
with [`child_process.fork()`][].
611614

615+
### `server.dropMaxConnection`
616+
617+
<!-- YAML
618+
added: REPLACEME
619+
-->
620+
621+
* {boolean}
622+
623+
Set this property to `true` to begin closing connections once the number of connections reaches the \[`server.maxConnections`]\[] threshold. This setting is only effective in cluster mode.
624+
612625
### `server.ref()`
613626

614627
<!-- YAML

lib/internal/cluster/child.js

+3-1
Original file line numberDiff line numberDiff line change
@@ -231,7 +231,9 @@ function onconnection(message, handle) {
231231

232232
if (accepted && server[owner_symbol]) {
233233
const self = server[owner_symbol];
234-
if (self.maxConnections != null && self._connections >= self.maxConnections) {
234+
if (self.maxConnections != null &&
235+
self._connections >= self.maxConnections &&
236+
!self.dropMaxConnection) {
235237
accepted = false;
236238
}
237239
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
'use strict';
2+
const common = require('../common');
3+
const cluster = require('cluster');
4+
const http = require('http');
5+
6+
if (cluster.isPrimary) {
7+
cluster.fork();
8+
} else {
9+
const server = http.createServer();
10+
server.maxConnections = 0;
11+
server.dropMaxConnection = true;
12+
// When dropMaxConnection is false, the main process will continue to
13+
// distribute the request to the child process, if true, the child will
14+
// close the connection directly and emit drop event.
15+
server.on('drop', common.mustCall((a) => {
16+
process.exit();
17+
}));
18+
server.listen(common.mustCall(() => {
19+
http.get(`http://localhost:${server.address().port}`).on('error', console.error);
20+
}));
21+
}

0 commit comments

Comments
 (0)