From 623db8f055c3c56177d7875c8f4190086886811c Mon Sep 17 00:00:00 2001 From: Magnus Holm Date: Mon, 31 Jul 2023 10:04:05 +0200 Subject: [PATCH] feat: limit the number of connections open in Node.js --- package-lock.json | 2 +- package.json | 2 +- src/http/nodeMiddleware.ts | 16 +++++++++++++++- 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index 4d2c4571..b8f7fbd7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,7 +10,7 @@ "license": "MIT", "dependencies": { "@sanity/eventsource": "^5.0.0", - "get-it": "^8.3.1", + "get-it": "^8.3.0", "rxjs": "^7.0.0" }, "devDependencies": { diff --git a/package.json b/package.json index f31e0938..f1f965d8 100644 --- a/package.json +++ b/package.json @@ -92,7 +92,7 @@ }, "dependencies": { "@sanity/eventsource": "^5.0.0", - "get-it": "^8.2.0", + "get-it": "^8.3.0", "rxjs": "^7.0.0" }, "devDependencies": { diff --git a/src/http/nodeMiddleware.ts b/src/http/nodeMiddleware.ts index 699d3389..2dff4f4f 100644 --- a/src/http/nodeMiddleware.ts +++ b/src/http/nodeMiddleware.ts @@ -1,10 +1,24 @@ -import {debug, headers} from 'get-it/middleware' +import {agent, debug, headers} from 'get-it/middleware' import {name, version} from '../../package.json' const middleware = [ debug({verbose: true, namespace: 'sanity:client'}), headers({'User-Agent': `${name} ${version}`}), + + // Enable keep-alive, and in addition limit the number of sockets that can be opened. + // This avoids opening too many connections to the server if someone tries to execute + // a bunch of requests in parallel. It's recommended to have a concurrency limit + // at a "higher limit" (i.e. you shouldn't actually execute hundreds of requests in parallel), + // and this is mainly to minimize the impact for the network and server. + // + // We're currently matching the same defaults as browsers: + // https://stackoverflow.com/questions/26003756/is-there-a-limit-practical-or-otherwise-to-the-number-of-web-sockets-a-page-op + agent({ + keepAlive: true, + maxSockets: 30, + maxTotalSockets: 256, + }), ] export default middleware