Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS Lambda - Java static initialization

Inside AWS lambda function (written in Java) I want to use AsyncHttpClient (https://github.com/AsyncHttpClient/async-http-client). Unfortunately it takes around 500 ms to create an instance of this object.. (but I still like it, please don't advice me to change the http client).

I was considering creating AsyncHttpClient in static initialization block. So maybe it will be executed once by AWS and than the snapshot would be cloned for the every AWS Lambda execution. Am I correct ?

When static block are executed in AWS Lambda ?

  • Once and than the snapshot is cloned to every AWS Lambda invocation
  • or static block is executed for every Lambda execution separately (and it will not help to put creation of Http Client there)

Thank you for help

like image 771
Hollow.Quincy Avatar asked Feb 13 '26 03:02

Hollow.Quincy


2 Answers

There is no "snapshot" taken of your Lambda execution environment, ever. There is however a concept of container reuse. A static initialization block will be called when the function runs for the first time in a new container, and each subsequent Lambda execution that is sent to that container will be able to skip the initialization step. Each time Lambda spins up a new container for your Lambda function that initialization work will need to happen again.

I suggest reading this post on the AWS blog about Lambda container reuse.

like image 199
Mark B Avatar answered Feb 15 '26 17:02

Mark B


As Mark B explained, there is no such thing as a 'snapshot'.

AWS starts an execution context the first time your Lambda is called and then reuses it for the next requests. However, this is not guaranteed. AWS may shut down this context at any time, or create others to scale your Lambda in case your of heavy load.

An execution context consists of the container, the JVM, and a Singleton instance of the Java class where your handler function is defined.

Therefore, I would not recommend doing any "one-time" initialization in a static block, but instead in the constructor of your class. This will greatly improve the testability of your code.

like image 29
Raphaël Brugier Avatar answered Feb 15 '26 15:02

Raphaël Brugier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!