Lambdas can stay in RAM for 15mins. After that the request
will be served from cold start stage. To avoid this latency, we need to keep
lambdas alive. This concept is called as “Prewarming”. Certain containers will
always ready to serve the request.
I have implemented Prewarming through cloud watch events. To
do so, follow the steps as below.
Step 1: Create a rule in cloud watch. Set Schedule which will trigger lambda
every 15mins.
Step 2: Add target to lambda function. Give the name of your lambda
function “Pwa-prewarmmer-stage”. This lambda function takes two input
parameters: number of containers to be created and whether to prewarm stage or
production’s lambda.
This prewarming of lambda will invoke all other lambda’s and
create containers for the same. This can be cross checked in cloud watch logs
as below.
Code of Prewarm Lambda
[LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] public async Task<string> FunctionHandlerAsync(JObject input, ILambdaContext lambdaContext) { int num=Convert.ToInt16( input["NumberofContainer"]); bool isProd=Convert.ToBoolean( input["isProd"]); try { Console.WriteLine("Prewarmer Start"); for (int i = 1; i <= num; i++) { using (AmazonLambdaClient client = new AmazonLambdaClient()) { JObject ob = new JObject { { "Resource", "WarmingLambda" }, { "Body", i.ToString() } }; var request = new InvokeRequest { FunctionName = isProd? "Pwa-lead" : "Pwa-lead-stage", InvocationType = InvocationType.Event, Payload = ob.ToString() }; var response = await client.InvokeAsync(request); } } return "Lead prewarmer done"; } catch (Exception ex) { return ex.Message + ex.StackTrace; } } }
No comments:
Post a Comment