0

I have an AWS Object Lambda in Node 20.x that uses SharpJS to watermark and reduce an image size upon GET requests. Code looks like this:

export const handler = async (event) => {
  const start = performance.now();

  const object_get_context = event['getObjectContext']
  const request_route = object_get_context['outputRoute']
  const request_token = object_get_context['outputToken']
  const s3_url = object_get_context['inputS3Url']
  const width = 1024
  const image = sharp().clone();
  
  try {
    const watermark = sharp('./watermark.png').resize(width - 300); 
    const watermarkBuffer = await watermark.toBuffer();
    // Download the image and watermark
    await axios.get(s3_url, { responseType: 'stream' })
    .then(res => 
      res.data.pipe(image.resize(width).composite([{input: watermarkBuffer}]))
    )
    .then(stream => {
      const input = {
        RequestRoute: request_route, 
        RequestToken: request_token, 
        Body: stream
      };
      const command = new WriteGetObjectResponseCommand(input);
      return s3Client.send(command)
    });
    
   return {
    status: 200
   };
  } catch (error) {
    console.error('Error processing image:', error);
  }
}

My problem is that executing the lambda is taking anywhere from 2-7 seconds per request. Images vary from 10-20MB. The lambda is executed from AWS CloudFront so once it's requested once, it is cached. The images are used to display in a gallery UI, so requesting 100 images the first time through CloudFront would take extremely long. Are there any performance enhancements to speed up watermark/resizing speeds?

2
  • You're doing this over and over again. Why not do a lazy creation to S3? If the image exists in S3 then send that. Otherwise, do the work needed and save it to S3 so that the next time you don't have to do it? Or, better yet, pre-generate the files in S3 and have the Lambda only send a pre-signed URL.
    – stdunbar
    Commented Jul 8 at 20:09
  • Wouldn't that be the same as having CloudFront cache the image? Not having S3 store the resized images saves me storage costs (in my use case, one image has at least 3 variants of sizes that can be requested) Commented Jul 9 at 14:26

0