Skip to content

Commit f962735

Browse files
committed
Reuse S3 connections: cache S3Clients, adjust timeouts & keep-alive
This cuts down on the creation of new connections, which can overwhelm the S3 server during high load. The adjusted timeouts and keep-alive values also deal with this high load.
1 parent 3281caa commit f962735

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

app/src/services/storage.js

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@ const utils = require('../components/utils');
2727

2828
const DELIMITER = '/';
2929

30+
// Cache AWS S3Clients in order to reuse S3 connections
31+
const s3ClientCache = new Map();
32+
3033
// Get app configuration
3134
const defaultTempExpiresIn = parseInt(config.get('server.defaultTempExpiresIn'), 10);
3235

@@ -51,16 +54,37 @@ const objectStorageService = {
5154
log.error('Unable to generate S3Client due to missing arguments', { function: '_getS3Client' });
5255
}
5356

54-
return new S3Client({
57+
// S3Client already exists for the given credentials
58+
const cacheKey = JSON.stringify([accessKeyId, endpoint, region]);
59+
if (s3ClientCache.has(cacheKey)) {
60+
return s3ClientCache.get(cacheKey);
61+
}
62+
63+
// If new, cache the S3Client before returning
64+
const newClient = new S3Client({
5565
credentials: {
5666
accessKeyId: accessKeyId,
5767
secretAccessKey: secretAccessKey
5868
},
5969
endpoint: endpoint,
6070
forcePathStyle: true,
6171
logger: ['silly', 'debug'].includes(config.get('server.logLevel')) ? log : undefined,
72+
retryMode: 'standard',
73+
requestHandler: {
74+
connectionTimeout: 5000,
75+
requestTimeout: 60000,
76+
httpsAgent: {
77+
keepAlive: true,
78+
keepAliveMsecs: 5000,
79+
maxSockets: 15,
80+
maxFreeSockets: 10,
81+
timeout: 30000
82+
}
83+
},
6284
region: region
6385
});
86+
s3ClientCache.set(cacheKey, newClient);
87+
return newClient;
6488
},
6589

6690
/**

0 commit comments

Comments
 (0)