How to Create a Scheduled Serverless Service with AWS Lambda and EventBridge
Contents
In today's fast-paced world, automation is the key to increasing efficiency and reducing manual effort. Automating repetitive tasks like sending daily reminders, performing scheduled backups, or updating data at regular intervals can save both time and resources. This is where AWS Lambda and Amazon EventBridge (formerly known as CloudWatch Events) come into play—offering a scalable, cost-effective solution for automating tasks without the hassle of managing servers.
In this guide, we’ll show you how to create a scheduled serverless service using AWS Lambda and EventBridge. AWS Lambda allows you to run code in response to various events, and EventBridge makes it easy to schedule these events at specific times. By the end of this guide, you’ll be able to set up a Lambda function and schedule it to run at regular intervals using cron expressions or fixed-rate schedules with EventBridge.
Introduction to AWS Lambda and Amazon Event Bridge
What is AWS Lambda
AWS Lambda is a serverless computing service by AWS that lets you run your code in response to events without managing your own infrastructure. All you need to do is write a script in your preferred language or upload it as a .zip file or container image to AWS Lambda.
In your script, you’ll need to write a handler function —the entry point of your code that AWS Lambda will execute when the function is triggered. Here’s an example in Node.js:
export const handler = async (event) => {
// TODO implement
const response = {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!'),
};
return response;
};
Lambda functions are stateless, meaning each execution is independent of others. This makes them well-suited for tasks that don’t require persistent connections or shared state, such as running scheduled jobs or responding to API requests.
Here's a list of AWS Lambda's key features:
- Serverless - You don't need to manage the underlying infrastructure. Your application still runs on servers, but all the server management is done by AWS.
- Automatic scaling - AWS Lambda automatically scales up or down based on the number of incoming requests. There's no need to manually adjust server capacity.
- Pay-as-you-go pricing - You only pay for the number of requests and the compute time you use, billed by the millisecond. There are no charges for idle time.
- Wide language support - You can write your script in Java, Go, PowerShell, Node.js, C#, Python, and Ruby. If you need to use a different language, the Runtime API allows for that as well.
🐰 Hare Hint: With the free tier, you receive 14 million invocations per month at no cost!
What is Amazon Event Bridge
Amazon EventBridge (formerly CloudWatch Events) is a serverless event bus that connects your applications using events. It is useful for building loosely coupled microservices, automating workflows, or responding to system events in real-time.
The EventBridge Scheduler allows you to create, trigger, and manage scheduled events and tasks. It supports two types of schedule patterns:
- One-off schedule - This allows you to execute a Lambda function at a set time interval, such as every 5 minutes or every 24 hours. For example,
rate(1 hour)
runs the function every hour. - Recurring schedule - More complex schedules can be set using cron expressions. These allow you to specify an exact minute, hour, day, month, and day of the week for the Lambda function to execute. For example,
cron(0 0 * * 1-5)
runs the function at midnight every day from Monday to Friday.
After setting a schedule, you can then choose a target from the available AWS services, define the payload, set retry policies, and wait for it to be triggered.
Here’s an illustration of the process:
src: Amazon EventBridge Scheduler
Pre-requisites
Before getting started, make sure you have the following:
- AWS account - You’ll need an active AWS account to access AWS Lambda and EventBridge.
- Basic knowledge of AWS - Familiarity with AWS services, especially Lambda and EventBridge will be beneficial.
How to Create a Scheduled Serverless Service: Creating a Lambda Function
Step 1. Access the AWS Management Console
Sign in to the AWS Management Console and navigate to the Lambda service. This is where you will configure your serverless function:
Step 2. Create a New Lambda Function
Click on “Create function” to set up a new Lambda function:
You will be prompted to enter details such as the function name, runtime, and architecture. Once you’ve filled in the necessary information, click on “Create function” to finalize the configuration:
Step 3. Write or Upload Your Function Code
On your Lambda function's main page, you will find an editor for writing the code:
Edit it as needed. If you prefer to upload your code from a file, you can do so by selecting a zip file or specifying an Amazon S3 link:
🐰 Hare Hint: This code will be executed according to the schedule you will set later.
Step 4. Deploy the Function
After completing your code, click the “Deploy” button to publish your Lambda function:
How to Create a Scheduled Serverless Service: Creating an EventBridge Schedule
Step 1. Access Amazon EventBridge
Navigate to the EventBridge service within the AWS Management Console. This is where you will configure the schedule for your Lambda function:
Step 2. Create a New Schedule
On the EventBridge page, select “EventBridge Schedule” and then click “Create schedule” :
Provide a name and description for the schedule and define when it should occur:
You can configure a one-off schedule for a specific date and time:
Or set a recurring schedule using a cron expression or fixed rate:
For example, use the cron expression cron(0 0 * * 1-5)
to schedule the function to run at midnight from Monday to Friday, or the fixed rate expression rate(1 day)
for a daily run.
After defining the schedule, set “Flexible time window” to “Off” and click “Next” to continue.
🐰 Hare Hint: Use a cron expression generator if you need help defining the expression.
Step 3. Select the Target
On the next page, select “AWS Lambda - Invoke” from the list of targets:
Then, select your Lambda function from the dropdown menu:
Configure any additional settings or input data for the Lambda function if needed, then proceed by clicking “Skip to review and create schedule”.
Step 4. Review and Create the Schedule
Review the details of your schedule. If everything is correct, click “Create schedule” to finalize:
Step 5. Monitor the Function
To ensure your Lambda function operates as expected, you can check the CloudWatch logs from the “Monitor” tab on your Lambda function’s page:
Review the logs regularly to verify that your function is executing on schedule and that there are no errors:
Tips for Managing Your Scheduled AWS Lambda Function
AWS Lambda and EventBridge offer robust solutions for creating serverless, scheduled tasks. To make sure your scheduled function is reliable, efficient, and cost-effective, consider following these tips:
- Implement error handling and retries - Including error handling logic can manage exceptions and failures gracefully. This might include retries, fallback mechanisms, or notifications.
🐰 Hare Hint: EventBridge allows you to set retry policies for failed invocations. Configure these policies to ensure your tasks are retried automatically if a failure occurs, reducing the need for manual intervention.
- Set up notifications - Set up Amazon SNS or CloudWatch Alarms to notify you if the Lambda function fails or if there are other issues so that you can resolve them immediately.
- Enable detailed logging - Use CloudWatch Logs to capture detailed logs from your Lambda function to debug issues and understand the function’s behavior during execution. Make sure to log relevant information, such as input parameters and error messages.
- Manage resources wisely - Allocate appropriate memory and timeout settings based on your function's needs. Over-allocating memory can lead to unnecessary costs, while under-allocating may result in timeouts or performance issues.
- Ensure security - Apply the principle of least privilege to the IAM role associated with your Lambda function. Ensure it only has the permissions necessary for its tasks. For example, if your function needs to access S3, grant it only S3 read/write permissions.
Final Thoughts
Using AWS Lambda and EventBridge together allows you to automate tasks with minimal overhead. Lambda handles code execution without needing server management, while EventBridge provides powerful scheduling capabilities. This combination helps streamline repetitive tasks and boost operational efficiency.
However, the setup and configuration can be complex if you’re unfamiliar with AWS services. This includes managing permissions, setting up triggers, and configuring event rules. If you’re looking for a simpler alternative, consider Roborabbit. It offers a user-friendly platform for automating repetitive tasks and scheduling actions without the hassle of complex configurations. Scheduling options range from once an hour to twice a day:
Roborabbit offers an intuitive interface and simple automation setup, making it an excellent choice if you want something easier to set up than AWS Lambda and EventBridge. If this sounds like what you're looking for, check out Roborabbit’s demos and see how it works!