How I handle time-based events in serverless architecture

Richard Fan
Level Up Coding
Published in
8 min readMar 18, 2020

--

Serverless is an event-driven world

Unlike years ago, when we all host long-running daemon as servers, we are entering a serverless era, which everything is triggered by events.

It is obvious if you think about normal website traffics. User hit the URL of your website/API endpoint, API Gateway triggers Lambda function, Lambda then triggers DynamoDB to update/retrieve data, everything starts from the user.

User hit the API, API Gateway triggers Lambda function, Lambda then triggers DynamoDB to update or retrieve data
A common serverless architecture. Everything starts from user actions

However, if your system is big enough, you will always face the case which requires scheduled actions. How can we adopt serverless architecture for those cases?

My past project: EV charger control system

One of my past projects is to build a cloud-based system to remotely control EV (Electronic Vehicle) chargers. The main feature is to time the duration of each charging session and stops the charger when the duration expires (User have to select the duration and pay for it before the session starts).

My design is simple. Users interact with the system through API Gateway. The Lambda function handles the logic and sends commands to on-site Raspberry Pi through SQS queue, the Raspberry Pi then control the chargers through on-site LAN.

The main problem is how should I trigger the event when a session expires? If I was hosting a classic server, I can run a CRON job every minute. Or extremely, I can run an infinite loop to check if there is any expiring session every second.

while True:
terminate_expired_sessions()
time.sleep(1)

How about in serverless architecture? What should we do?

Option 1: CRON

Back old days, we use CRON to do time-based jobs, why don’t we use the same method? In AWS, we can use CloudWatch Event Rule to trigger Lambda functions regularly. In Azure, we can set up a Function App with a timer trigger.

--

--