How to use SQS with NestJS + Serverless

Uğur Güngezerler
Plus Minus One
Published in
3 min readJun 23, 2021

Recently we deploy our new app with NestJS on Lambda. NestJS is amazing but does not support serverless architecture, at least in the documentation. So I learned a lot of things on the web about it so I think that it that may help others.

On the web, there are a few documents about how to run NestJS on Lambda. In this article, we are focusing on NestJS + Serverless + SQS.

Lambda is working as event-driven architecture. NestJS’s queue system is working great with a monolithic server.

If you have used NestJS Queue (bull) with Redis on lambda, you have probably observed that it’s not working as expected. Because on the event-driven system we need an event emitter. On lambda when we get a HTTPrequest API-Gateway fires an event to lambda so lambda wakes up then functions will work. In this case, when we add a job to the queue we must wake up lambda. Redis is not capable of this. At this point, SQS will help us.

So how can we use triggers?

In the code below we defined 2 lambda functions as main(NestJS) and queue(SQS). Also, 2 SQS channels as General and Notification are being created/defined and bound to the queue as an event, which will be used to trigger lambda.

In the code below, we define a lambda function and bootstrap the NestJS. Then we will process jobs on your SQS handler service async. When processing is complete lambda will sleep until the new job.

Almost complete! We know how to process jobs from SQS. But we need one more step for SQS job producer.

My solution is to create a base queue class instead of bull decorators. Maybe decorators might be better but at this point, we were racing against the time.

The base queue class contains two main methods. add() method will add jobs to the queue easily and send() method will send them to SQS.

PS: By using bull package, you can create long-time delayed jobs. But when you are using SQS, it lets you create maximum 15 mins delayed jobs.

To learn more about our development experiences you can look at our medium page. At Plus Minus One, we love to learn and share our experiences. We hope this article makes your life easier 🙏🏻

--

--