AWS Lambda Snapstart: Fast cold starts for your Java functions
- Tomasz Łakomy
What is AWS Lambda SnapStart
If you've been using AWS Lambda for a while, you've probably noticed that cold starts can be a bit slow. This is especially true for Java-based functions, since JVM is not exactly the fastest piece of software out there.
Luckily, during re:Invent 2022 AWS announced a new feature called SnapStart, which makes cold starts up to 10x faster for Java-based functions. This is achieved by launching your function, executing the entire
Init phase and storing a snapshot of memory & disk state. When your function is invoked, the snapshot is loaded and the
Init phase is skipped, which makes the cold start much faster.
To quote AWS Blog:
After you enable Lambda SnapStart for a particular Lambda function, publishing a new version of the function will trigger an optimization process. The process launches your function and runs it through the entire
Initphase. Then it takes an immutable, encrypted snapshot of the memory and disk state, and caches it for reuse.
When the function is subsequently invoked, the state is retrieved from the cache in chunks on an as-needed basis and used to populate the execution environment. This optimization makes invocation time faster and more predictable, since creating a fresh execution environment no longer requires a dedicated
How to enable SnapStart for your Java function
SnapStart can be enabled via the Console (Cloudash team does not encourage ClickOps), AWS CLI or IaC solutions like SAM or CDK.
Update: At the time of writing, CDK support is not shipped yet, here's a PR to add it: https://github.com/aws/aws-cdk/pull/23196
Regardless of the way you choose to enable SnapStart, it's a single setting you need to enable for your function. There are no additional charges for using SnapStart, it's completely free. (And they warn you about lock-in!).
Can SnapStart be used with all Java functions?
Yes, and no.
For instance, any unique content that is generated during the
Init phase will not be unique for each invocation. For example, if you generate a random number during the
Init phase, it will be the same for each invocation. This is because the
Init phase is skipped and the snapshot is loaded instead.
If your applications depend on uniqueness of state, you must evaluate your function code and verify that it is resilient to snapshot operations.
Read handling uniqueness with Lambda SnapStart to learn more.
There's also a matter of network connections - if your function opens a connection to a database or other service during the
Init phase, it will be reused for each invocation. Make sure that your
Invoke phase code can reestablish the connection if necessary. The AWS SDKs have already been updated to do this.
Learn more by watching AWS re:Invent 2022 - AWS Lambda SnapStart: Fast cold starts for your Java functions (SVS320) on YouTube.