Home > Net >  Is it necessary to create a new S3 client object for each request in Node.js?
Is it necessary to create a new S3 client object for each request in Node.js?

Time:07-08

Is it necessary to create a new S3 client object for each request in Node.js?

const aws = require('aws-sdk');
const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  const s3 = new aws.S3();
  const params = {
    Bucket: "examplebucket", 
    Key: "HappyFace.jpg"
  };
  s3.getObject(params, (err, data) => {
   if (err) console.log(err, err.stack); // an error occurred
   else res.send(data);
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

This is just an example code, but the position of const s3 = new aws.S3(); is crucial for me. Let's imagine that the service processes thousands of requests in parallel, then it generates thousands of S3 objects. As it stands, the service can handle it without any problems. My question is, does it even have to? If I only created one S3 object above the route definition, would parallel requests affect each other or not when the code will be changed to

...
const s3 = new aws.S3();

app.get('/', (req, res) => {
  const params = {
    Bucket: "examplebucket", 
    Key: "HappyFace.jpg"
  };
  s3.getObject(params, (err, data) => {
   if (err) console.log(err, err.stack); // an error occurred
   else res.send(data);
});
...

CodePudding user response:

When you do:

const s3 = new aws.S3();

you're only instantiating the S3 class provided by the AWS SDK, thus the only thing that could be a problem is if you need a different initial configuration of the instance, e.g region, version...

That said, from the code you've provided, it's okay to instantiate the S3 class outside the endpoint, and it's probably good practice too.

CodePudding user response:

definitly not. The s3 object here is an instance of a manger for the subset of apis you will use from AWS sdk and not an s3 object representation.

Unless you are doing something very specific (which was not precised in the question so i assume that this is not the case) you are good to set it above the app.get part.

You would only go the 1st way you mention if the configuration of the sdk for s3 apis must be different for each request (ex: if you need to use a different aws credential for each request or store the object in a different region for each request)

  • Related