EventBridge: The Cron Job Solution for Backends on AWS Lambda

A while ago, I found the need in the backend to run a cron job that automatically updates invoice and ticket statuses. At first, I used NestJS’s built-in cron job feature. However, it failed to work properly.

Why the Built-in Cron Job Failed on Lambda

AWS Lambda is event-driven and does not run continuously. The built-in NestJS cron job requires a process that stays active 24/7. As a result, when there’s no activity and Lambda stops, the cron job also stops, preventing the status updates from running.

Solution: AWS EventBridge

AWS EventBridge is a separate service that can trigger events on a schedule using a cron expression. With EventBridge, scheduled tasks continue to run even if the backend is deployed on Lambda.

Quick Implementation Steps

  1. Integrate EventBridge into your NestJS project using the AWS SDK.
  2. Set up a rule in EventBridge, for example, to trigger every hour.
  3. Create a module or handler in NestJS to receive and process events from EventBridge.

Result

The cron job now runs consistently according to schedule, even in a serverless, event-driven environment like Lambda.

Conclusion

For backends running on AWS Lambda, NestJS’s built-in cron job alone is not sufficient because it requires an always-on process. By leveraging AWS EventBridge, scheduling can continue without needing a constantly running server. Integration is relatively simple using the AWS SDK and an event-handling module in NestJS

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *