Skip to content

Commit 446f9ff

Browse files
committed
lib: add flag to drop connection when running in cluster mode
1 parent ce531af commit 446f9ff

File tree

3 files changed

+39
-3
lines changed

3 files changed

+39
-3
lines changed

doc/api/net.md

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -599,12 +599,25 @@ changes:
599599

600600
* {integer}
601601

602-
Set this property to reject connections when the server's connection count gets
603-
high.
602+
When the number of connections reaches the `server.maxConnections` threshold:
603+
604+
1. If the process is not running in cluster mode, Node.js will close the connection.
605+
606+
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`.
604607

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

611+
### `server.dropMaxConnection`
612+
613+
<!-- YAML
614+
added: REPLACEME
615+
-->
616+
617+
* {boolean}
618+
619+
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.
620+
608621
### `server.ref()`
609622

610623
<!-- YAML

lib/internal/cluster/child.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,9 @@ function onconnection(message, handle) {
233233

234234
if (accepted && server[owner_symbol]) {
235235
const self = server[owner_symbol];
236-
if (self.maxConnections != null && self._connections >= self.maxConnections) {
236+
if (self.maxConnections != null &&
237+
self._connections >= self.maxConnections &&
238+
!self.dropMaxConnection) {
237239
accepted = false;
238240
}
239241
}
Lines changed: 21 additions & 0 deletions
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)