Search code examples
amazon-web-servicesaws-lambda

how to decrease the exceution time of aws lambda function nodejs


i've written an api in aws sam lambda function node x20.
this api is responsible for login into the user and return me the response.
while at cold start it look 6 seconds, after that it took 3 seconds (average) to return the response.

what i want??i want that, the time to return the response should be less than 2 seconds. what can i do.

export const loginHandler = catchTryAsyncErrors(async (event) => {
  const headers = generateCorsHeaders();
  const DB = await DBConn();

  const requestBody = JSON.parse(event.body);
  await loginValidation.validate(requestBody, { abortEarly: false });
  const { password, email, platform = "CLIENT" } = requestBody;

  let response, error;
  const user = await DB.collection("users").findOne({
    email: email.toLowerCase(),
    isAccCreated: true,
    role: platform === "CLIENT" ? "Client" : "Admin",
  });

  if (!user) {
    error = new HTTPError("The email address was not found.", StatusCodes.NOT_FOUND);
    return {
      statusCode: StatusCodes.NOT_FOUND,
      headers,
      body: JSON.stringify(error),
    };
  }

  const passwordMatch = await bcryptjs.compare(password, user.password);
  if (!passwordMatch) {
    error = new HTTPError("The password entered is incorrect.", StatusCodes.CONFLICT);
    return {
      statusCode: StatusCodes.CONFLICT,
      headers,
      body: JSON.stringify(error),
    };
  }
  user.password = undefined;

  if (user["status"] === "Blocked") {
    error = new HTTPError("This user account has been blocked by the administrator.", StatusCodes.CONFLICT);
    return {
      statusCode: StatusCodes.CONFLICT,
      headers,
      body: JSON.stringify(error),
    };
  }

  if (user.role === "Admin") {
    const logData = {
      ip: event?.requestContext?.identity?.sourceIp,
      user: new ObjectId(user?._id),
      activity: "ADMIN_LOGIN",
      msg: `${user?.userName} login into Admin Site`,
      createdAt: new Date(),
      updatedAt: new Date(),
    };
    await DB.collection("logs").insertOne(logData);
  }

  const token = await getJWTToken({ _id: user["_id"], role: user["role"] });
  // const userWallet = await DB.collection("userwallets").findOne({
  //   _id: user?.userWallet,
  // });

  response = new HTTPResponse("Login successful.", {
    user: { ...user },
    token,
  });
  return {
    statusCode: StatusCodes.OK,
    headers,
    body: JSON.stringify(response),
  };
});

template.yaml

  LoginFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: login/
      Handler: app.loginHandler
      Runtime: nodejs20.x
      MemorySize: 3072
      Architectures:
        - x86_64
      Environment:
        Variables:
          MONGODB_URL: "mongodb://localhost:27017/10D"
          DB_NAME: "10D"
          JWT_SECRET: "awsSamLambdafunction2024node20jsX"
      Events:
        searchNodes:
          Type: Api
          Properties:
            Path: /api/user/login
            Method: post
    Metadata:
      SamResourceId: LoginFunction

i've increased the MemorySize of login function to 1024, still no performance upgradation.


Solution

  • Have you tried timing the different parts of your lambda ? I suspect that the DB connection and request might take a significant amount of time.

    You should at least move the DB connection initialization outside of your handler so that it is only executed once per cold-start, and not on every subsequent warm start.