-1

I am using AWS Lambda Function with Java and I use container images for deployment.

  • The first call to this function with cold start results in around 6 seconds:
Init Duration (ms) Duration (ms) Billed Duration (ms)
2300 4300 6600
  • Whereas after the first call when the function is warm, it is usually only around 120ms:
Init Duration (ms) Duration (ms) Billed Duration (ms)
N/A 120 120

In order to avoid the cold start, I set up an EventBridge scheduled event that pings the Lambda function every 5 minutes. The handler looks like this:

public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input,
            Context context) {
    if (input.getHeaders().get("foo") == "Pinging") {
        return new APIGatewayProxyResponseEvent().withStatusCode(200);
    }
    //...
    //continue the business logics
    //...

Here is the test result:

Description Time Init Duration (ms) Duration (ms) Billed Duration (ms)
Deployment 9:12am N/A N/A N/A
1st ping 9:15am 2300 20 2320
2nd ping 9:20am N/A 3 3
Real function call 1 9:21am N/A 4300 4300
Real function call 2 9:21am N/A 147 147
Real function call 3 9:22am N/A 280 280
3rd ping 9:25am N/A 3 3

It seems the scheduled ping can only reduce the init duration of 2300ms. How can I effectively reduce the duration of 4300ms of the first function call (i.e. Real function call 1)?

  • Have you ensured the cloudwatch service has permissions to invoke your function? – John Aug 21 '23 at 04:28
  • There is nothing wrong with permission as I can use EventBridge to ping the Lambda successfully. I collected the duration data from Lambda logs in CloudWatch. – Zhuang Paulus Aug 21 '23 at 05:30
  • Java performs on-demand classloading, which is what usually takes the time. Your ping function should perform all initialization, so that none happens during the client call. You can also increase memory allotment, which increases CPU allotment. But you're always going to have an "N+1" problem, where the Lambda that you've lept alive via pings is busy processing a request, and a new request comes in. See https://stackoverflow.com/a/65160907/42126 for more information. – kdgregory Aug 21 '23 at 12:46

0 Answers0