Search code examples
node.jsamazon-s3aws-sdk-js

Reuse same instance of AWS.S3 in multiple requests to my node.js app


Is it safe to use the same instance of AWS.S3 in every request? Does it handle stuff like reconnecting? Or do I need to instantiate the s3 client inside my controller action?

In other words, can I safely instantiate the client outside the scope of the controller action:

const s3 = new AWS.S3(myAwsConfiguration);

async myControllerAction(ctx, next) {
  let s3Object = null;
  try {
    s3Object = await s3.getObject({
      'Bucket': bucket,
      'Key': key,
    }).promise();
  } catch(e) {
    ctx.throw(500, 'cannot fetch from s3');
  }
}

or do I have to do it inside:

async myControllerAction(ctx, next) {
  const s3 = new AWS.S3(myAwsConfiguration);

  let s3Object = null;
  try {
    s3Object = await s3.getObject({
      'Bucket': bucket,
      'Key': key,
    }).promise();
  } catch(e) {
    ctx.throw(500, 'cannot fetch from s3');
  }
}

Solution

  • As I have learned in the meantime:

    Yes, it is perfectly safe to reuse the same instance. The s3 protocol is stateless and there is no such thing as a maintained connection that could get lost.