Skip to content

Commit

Permalink
lib: add flag to drop connection when running in cluster mode
Browse files Browse the repository at this point in the history
PR-URL: #54927
Refs: #54882
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
  • Loading branch information
theanarkh authored and aduh95 committed Oct 19, 2024
1 parent 9b7b4a6 commit db18aca
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 3 deletions.
17 changes: 15 additions & 2 deletions doc/api/net.md
Original file line number Diff line number Diff line change
Expand Up @@ -603,12 +603,25 @@ changes:

* {integer}

Set this property to reject connections when the server's connection count gets
high.
When the number of connections reaches the `server.maxConnections` threshold:

1. If the process is not running in cluster mode, Node.js will close the connection.

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`.

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

### `server.dropMaxConnection`

<!-- YAML
added: REPLACEME
-->

* {boolean}

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.

### `server.ref()`

<!-- YAML
Expand Down
4 changes: 3 additions & 1 deletion lib/internal/cluster/child.js
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,9 @@ function onconnection(message, handle) {

if (accepted && server[owner_symbol]) {
const self = server[owner_symbol];
if (self.maxConnections != null && self._connections >= self.maxConnections) {
if (self.maxConnections != null &&
self._connections >= self.maxConnections &&
!self.dropMaxConnection) {
accepted = false;
}
}
Expand Down
21 changes: 21 additions & 0 deletions test/parallel/test-net-server-drop-connections-in-cluster.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
'use strict';
const common = require('../common');
const cluster = require('cluster');
const http = require('http');

if (cluster.isPrimary) {
cluster.fork();
} else {
const server = http.createServer();
server.maxConnections = 0;
server.dropMaxConnection = true;
// When dropMaxConnection is false, the main process will continue to
// distribute the request to the child process, if true, the child will
// close the connection directly and emit drop event.
server.on('drop', common.mustCall((a) => {
process.exit();
}));
server.listen(common.mustCall(() => {
http.get(`http://localhost:${server.address().port}`).on('error', console.error);
}));
}

0 comments on commit db18aca

Please sign in to comment.