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?