Search code examples
node.jsamazon-web-servicesamazon-s3aws-sdk-jsaws-sdk-nodejs

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?

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);
});
...

Solution

  • 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.