Skip to content

Long execution time caused by callbackWaitsForEmptyEventLoop=true on AWS Stream #264

@garfieldnate

Description

@garfieldnate

Feature Request

We needed to set callbackWaitsForEmptyEventLoop to false for our use-case; without this, our lambda invocations were taking 30s instead of 8ms, so it's a huge deal for us.

It was a bit difficult to figure out how to access and modify the AWS context object, so I wanted to share our solution here for others to use in the future:

import {
  type BinarySettings,
  type ILogger,
  ServerlessAdapter,
} from "@h4ad/serverless-adapter";
import {
  type AWSStreamContext,
  AwsStreamHandler,
} from "@h4ad/serverless-adapter/lib/handlers/aws";

// Extend AwsStreamHandler to access the context object
class CustomAwsStreamHandler<TApp> extends AwsStreamHandler<TApp> {
  protected onReceiveRequest(
    log: ILogger,
    event: APIGatewayProxyEventV2,
    context: AWSStreamContext,
    binarySettings: BinarySettings,
    respondWithErrors: boolean,
  ): void {
    super.onReceiveRequest(
      log,
      event,
      context,
      binarySettings,
      respondWithErrors,
    );

    context.context.callbackWaitsForEmptyEventLoop = false;
  }
}

// set the stream handler on the adapter
export const handler = ServerlessAdapter.new(app)
  .setHandler(new CustomAwsStreamHandler())
  ...
  .build();

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingenhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions