AWS generally terminates Lambda functions after 30-60 mins of inactivity and sometimes shorter. The long wake-up time could create service reliability issues during times when usages are low. And if the Lambda function is deployed using Docker images, the warm up time will literally be in minutes even for simple machine learning models.

We can resolve this issue by creating a cron job, AWS Step Function, or another Lambda function to ping our services every N minutes to keep them awake. Or pay ~$10 per month for 1GB Lambda using the provisioned concurrency feature. But with AWS Serverless Application Model (SAM), there exists another way.

Keeping Lambda Function Warm with SAM

How to Keep Your Lambda Functions Warm suggests that we can creating an Schedule Expressions for Rules on Cloudwatch that pings the Lambda function on a schedule using Cloudwatch Events.

Inspired by that, we can combine the Events idea with AWS SAM and schedule an expression every 5 mins to keep a Lambda function alive. We can create the following resources in the resource section of our SAM template.yaml to keep our Lambda function MyAwsLambdaFunction alive:

Resources:

    MyAwsLambdaFunctionKeepAliveEvent:
    Type: 'AWS::Events::Rule'
    Properties:
        Description: "Keeping MyAWSLambdaFunction alive"
        ScheduleExpression: rate(5 minutes)
        State: ENABLED
        Targets:
          - 
            Arn:
              Fn::GetAtt:
                - "MyAwsLambdaFunction"
                - "Arn"
            Id: '1'

    MyAwsLambdaFunctionKeepAliveEventPermission:
    Type: 'AWS::Lambda::Permission'
    Properties:
        FunctionName: !Ref "MyAwsLambdaFunction"
        Action: 'lambda:InvokeFunction'
        Principal: events.amazonaws.com
        SourceArn:
          Fn::GetAtt:
            - MyAwsLambdaFunctionKeepAliveEvent
            - Arn

References:

New – Provisioned Concurrency for Lambda Functions

How to Keep Your Lambda Functions Warm

Schedule Expressions for Rules

AWS::Events::Rule