We will summarize the configuration to run the API server using Hono in the Bun runtime on AWS Lambda.
The purpose is to run it with the Bun runtime, not Node.js or LLRT.
Source code
How to achieve it
- Compile as Single File Executable (executable binary)
- Run using AWS Lambda Web Adapter (LWA)
I think it can be run without using LWA, but this time I prioritized checking the operation using LWA.
Technology used
- Bun -Hono
- AWS SAM
- AWS Lambda Web Adapter
Directory structure
.├── Makefile├── README.md├── app│ └── index.ts├── bun.lockb├── lambda.ts├── localhost.ts├── package.json├── samconfig.toml├── template.yaml└── tsconfig.jsonSAM template (infrastructure configuration)
Define AWS Lambda, Lambda Function URL, and IAM role.
AWSTemplateFormatVersion: "2010-09-09"Transform: AWS::Serverless-2016-10-31Description: > bun compiled sfe binary on Lambda demo
Globals: Function: Timeout: 10
Resources: BunAppFunction: DeletionPolicy: Delete Type: AWS::Serverless::Function Properties: CodeUri: . MemorySize: 256 Handler: bootstrap Runtime: provided.al2023 Architectures: - x86_64 Environment: Variables: PORT: "8000" Layers: - !Sub arn:aws:lambda:${AWS::Region}:753240598075:layer:LambdaAdapterLayerX86:22 FunctionUrlConfig: AuthType: NONE Metadata: BuildMethod: makefile
Outputs: FunctionUrl: Value: !GetAtt BunAppFunctionUrl.FunctionUrlBuild settings
When developing locally, start with bun --hot localhost.ts.
At sam build, the Makefile’s Build task is executed. This is the key here.
bun build --compile --minify --sourcemap --target=bun-linux-x64 ./lambda.ts --outfile bootstrap
cp ./bootstrap $(ARTIFACTS_DIR)/.Generate an executable binary using Bun’s --compile option and output it as bootstrap.
Entry point
I didn’t do anything particularly difficult. Just receive the PORT number from the environment variable.
API implementation (Hono implementation) is consolidated under the app directory.
import { app } from "./app";
export default { port: process.env.PORT, fetch: app.fetch,};Deploy
Set samconfig.toml.
version = 0.1
[default.deploy.parameters]stack_name = "<your_stack_name>"resolve_s3 = trues3_prefix = "<your_stack_name>"region = "<region>"confirm_changeset = truecapabilities = "CAPABILITY_IAM"Deploy command:
sam deployIf successful, a URL like the one below will be issued.
https://<random-string>.lambda-url.<region>.on.awsWhen used with CloudFront
Basically, combination use is recommended.
- Change the AuthType of Lambda Function URL to
IAM_AUTH - Create OAC for Lambda Function URL in CloudFront
- Update Lambda resource-based policy statements
summary
By compiling it as Bun’s Single File Executable and using Lambda Web Adapter, you can run the Hono API server on Lambda with the Bun runtime.
The difference between local development and deployment is small, and the configuration allows the high speed of Bun to be utilized in the Lambda environment.
hsb.horse