AWS Lambda caching in Python

Caching between lambda invocations may be useful for certain scenarios:

  • Authentication
  • Rate limits with external services
  • Speed

How to cache between lambda invocations

In Python, it’s as simple as modifying a global variable.

1
2
3
4
5
6
obj = None

def lambda_handler(event):
    global obj
    if not obj:
        obj = YourClass(event)

Upon initial run of a lambda function, obj will be set to the output of YourClass(event). On subsequent warm starts, the lambda function will reuse the global obj from the previous lambda run. More information regarding warm vs cold starts can be found here.