Skip to content

Commit 1984735

Browse files
committed
cold start optimization
1 parent cfeb035 commit 1984735

File tree

5 files changed

+252
-5
lines changed

5 files changed

+252
-5
lines changed

cloudformation/iam.yml

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,15 @@ Resources:
143143
- lambda.amazonaws.com
144144

145145
Policies:
146+
- PolicyName: lambda-self-invoke
147+
PolicyDocument:
148+
Version: "2012-10-17"
149+
Statement:
150+
- Action:
151+
- lambda:invokeFunction
152+
Effect: Allow
153+
Resource:
154+
- Fn::Sub: "arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${LambdaFunctionName}"
146155
- PolicyName: lambda-generic
147156
PolicyDocument:
148157
Version: "2012-10-17"

cloudformation/main.yml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,16 @@ Resources:
192192
RestApiId: !Ref AppApiGateway
193193
Path: /{proxy+}
194194
Method: ANY
195+
WarmingSchedule:
196+
Type: Schedule
197+
Properties:
198+
Schedule: !If [
199+
ShouldAttachVpc,
200+
'rate(15 minutes)',
201+
'rate(5 minutes)'
202+
]
203+
Input: '{ "warmer":true,"concurrency":3 }'
204+
195205

196206
AppSqsLambdaFunction:
197207
Type: AWS::Serverless::Function

src/api/lambda.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,23 @@
11
import "zod-openapi/extend";
22
import awsLambdaFastify from "@fastify/aws-lambda";
33
import init from "./index.js";
4+
import warmer from "lambda-warmer";
5+
import { type APIGatewayEvent, type Context } from "aws-lambda";
46

57
const app = await init();
6-
const handler = awsLambdaFastify(app, {
8+
const realHandler = awsLambdaFastify(app, {
79
decorateRequest: false,
810
serializeLambdaArguments: true,
911
callbackWaitsForEmptyEventLoop: false,
1012
});
13+
const handler = async (event: APIGatewayEvent, context: Context) => {
14+
// if a warming event
15+
if (await warmer(event, { correlationId: context.awsRequestId }, context)) {
16+
return "warmed";
17+
}
18+
// else proceed with handler logic
19+
return realHandler(event, context);
20+
};
21+
1122
await app.ready(); // needs to be placed after awsLambdaFastify call because of the decoration: https://github.com/fastify/aws-lambda-fastify/blob/master/index.js#L9
1223
export { handler };

src/api/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@
4949
"ioredis": "^5.6.1",
5050
"jsonwebtoken": "^9.0.2",
5151
"jwks-rsa": "^3.2.0",
52+
"lambda-warmer": "^2.3.0",
5253
"moment": "^2.30.1",
5354
"moment-timezone": "^0.5.48",
5455
"node-cache": "^5.1.2",

0 commit comments

Comments
 (0)