{"id":14779615,"url":"https://github.com/trueangle/kotlin-native-aws-lambda-runtime","last_synced_at":"2025-09-14T22:31:00.922Z","repository":{"id":257166718,"uuid":"823213218","full_name":"trueangle/kotlin-native-aws-lambda-runtime","owner":"trueangle","description":"A runtime for executing AWS Lambda functions written in Kotlin/Native, designed to reduce cold start issues common with the JVM platform.","archived":false,"fork":false,"pushed_at":"2024-12-01T13:55:12.000Z","size":1915,"stargazers_count":7,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2024-12-01T14:34:02.377Z","etag":null,"topics":["aws-lambda","aws-lambda-runtime","kotlin","kotlin-multiplatform","kotlin-native","serverless"],"latest_commit_sha":null,"homepage":"","language":"Kotlin","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/trueangle.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-07-02T15:41:47.000Z","updated_at":"2024-12-01T14:25:51.000Z","dependencies_parsed_at":"2024-11-06T12:19:08.480Z","dependency_job_id":"30a0d9e2-7198-4b41-a827-b5d784227452","html_url":"https://github.com/trueangle/kotlin-native-aws-lambda-runtime","commit_stats":null,"previous_names":["trueangle/kotlin-native-aws-lambda-runtime"],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/trueangle%2Fkotlin-native-aws-lambda-runtime","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/trueangle%2Fkotlin-native-aws-lambda-runtime/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/trueangle%2Fkotlin-native-aws-lambda-runtime/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/trueangle%2Fkotlin-native-aws-lambda-runtime/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/trueangle","download_url":"https://codeload.github.com/trueangle/kotlin-native-aws-lambda-runtime/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":233035229,"owners_count":18614970,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["aws-lambda","aws-lambda-runtime","kotlin","kotlin-multiplatform","kotlin-native","serverless"],"created_at":"2024-09-17T01:00:54.444Z","updated_at":"2025-09-14T22:31:00.912Z","avatar_url":"https://github.com/trueangle.png","language":"Kotlin","readme":"# Kotlin Native Runtime for AWS Lambda\n[![Maven Central](https://maven-badges.herokuapp.com/maven-central/io.github.trueangle/lambda-runtime/badge.svg)](https://maven-badges.herokuapp.com/maven-central/io.github.trueangle/lambda-runtime/badge.svg)\n\nA runtime for executing AWS Lambda Functions written in Kotlin/Native, designed to reduce cold start issues common with the JVM platform.\n\n## Project Structure\n\n- `lambda-runtime`: Library providing the Lambda runtime.\n- `lambda-events`: Library with strongly-typed Lambda event models like `APIGatewayRequest`, `DynamoDBEvent`, `S3Event`, `KafkaEvent`, `SQSEvent`, etc.\n- `sample`: Sample project demonstrating examples of lambda functions.\n\n## Supported [OS-only runtime machines](https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html)\n\n- Amazon Linux 2023 (provided.al2023) with x86_64 or arm64 architecture\n- Amazon Linux 2 (provided.al2) with x86_64 or arm64 architecture\n\n## Performance\n\nBenchmarks of Kotlin Native's \"Hello World\" Lambda function on Amazon Linux 2023 (x86_64) configured with different amounts of provisioned memory. For more detailed benchmarks, [read the article](https://medium.com/@s.ivanovichev/leveraging-kotlin-native-for-efficient-serverless-applications-on-aws-lambda-66d992c074cc).\n- **Lambda 128mb provisioned memory**. Kotlin/Native outperforms JVM-based runtimes like GraalVM and Java 17 and Java 21 SnapStart.\n![Kotlin Native AWS Lambda Runtime 128mb benchmark](docs/performance_hello_world_128mb.png)\n- **Lambda 256mb provisioned memory**. Competitive with Python in execution time and memory usage, while surpassing JVM-based runtimes.\n![Kotlin Native AWS Lambda Runtime 256mb benchmark](docs/performance_hello_world_256mb.png)\n- **Lambda 512mb provisioned memory**. Kotlin/Native ranks among the top 5 fastest runtimes, ahead of Python, C#, and JVM, only trailing behind C++, Rust, LLRT, and Go.\n![Kotlin Native AWS Lambda Runtime 512mb benchmark](docs/performance_hello_world_512mb.png)\n- **Lambda 1024mb provisioned memory**\n![Kotlin Native AWS Lambda Runtime 1024mb benchmark](docs/performance_hello_world_1024mb.png)\n\n## Getting started\n\n### 1. Create a Kotlin Multiplatform Project\nSee [Get started with Kotlin/Native](https://kotlinlang.org/docs/native-get-started.html) for more details.\n\n### 2. Add Dependencies\n\nAdd the following to your `build.gradle` file:\n```kotlin\nplugins {\n    id(\"io.github.trueangle.plugin.lambda\") version \"0.0.2\"\n}\n\nkotlin {\n    sourceSets {\n        nativeMain.dependencies {\n            implementation(\"io.github.trueangle:lambda-runtime:$lambda_runtime_version\")\n            implementation(\"io.github.trueangle:lambda-events:$lambda_runtime_version\")\n        }\n    }\n}\n\nbuildLambdaRelease {\n    architecture.set(Architecture.LINUX_X64) // or Architecture.LINUX_ARM64\n}\n```\n\n### 3. Specify Entry Point and Targets\n```kotlin\nkotlin {\n    listOf(\n        macosArm64(),\n        macosX64(),\n        linuxX64(),\n    ).forEach {\n        it.binaries {\n            executable {\n                entryPoint = \"com.github.trueangle.knative.lambda.runtime.sample.main\" // Link this to your main function entry point\n                freeCompilerArgs += listOf(\"-Xallocator=mimalloc\") // to understand how the choice of allocator impacts the performance, refer https://medium.com/aws-tip/leveraging-kotlin-native-for-efficient-serverless-applications-on-aws-lambda-66d992c074cc\n            }\n        }\n    }\n}\n```\n\n### 4. Choose Lambda Function Type\n\n#### Buffered \nBuffered Lambda functions collect all data before sending a response. This is a default behavior of Lambda function. Response payload max size: 6 MB.\n\n```kotlin\nclass HelloWorldLambdaHandler : LambdaBufferedHandler\u003cAPIGatewayV2Request, APIGatewayV2Response\u003e {\n    override suspend fun handleRequest(\n        input: APIGatewayV2Request,\n        context: Context\n    ): APIGatewayV2Response {\n        return APIGatewayV2Response(\n            statusCode = 200,\n            body = \"Hello world\",\n            cookies = null,\n            headers = null,\n            isBase64Encoded = false\n        )\n    }\n}\n```\n`LambdaBufferedHandler\u003cI, O\u003e` is designed to work with any Kotlin class that is supported by the Kotlin serialization library as both the input and output types. This allows you to define your own custom request and response models annotated with `@Serializable` or utilize existing ones provided by the `lambda-events` module.\n\n#### Streaming\nA streaming function sends data as soon as it's available, instead of waiting for all the data. It processes and returns the response in chunks, which is useful for large or ongoing tasks. This allows for faster responses and can handle data as it comes in. [More details here](https://docs.aws.amazon.com/lambda/latest/dg/configuration-response-streaming.html). For example, `SampleStreamingHandler` reads a large json file and streams it in chunks.\n\n```kotlin\nclass SampleStreamingHandler : LambdaStreamHandler\u003cByteArray, ByteWriteChannel\u003e {\n    override suspend fun handleRequest(\n        input: ByteArray,\n        output: ByteWriteChannel,\n        context: Context\n    ) {\n        ByteReadChannel(SystemFileSystem.source(Path(\"hello.json\")).buffered()).copyTo(output)\n    }\n}\n```\n`LambdaStreamHandler\u003cI, ByteWriteChannel\u003e` accepts any serializable input and outputs to `ByteWriteChannel` which is then streamed to the client.\n\nBoth `LambdaBufferedHandler` and `LambdaStreamHandler` are suspend functions, so you can use Kotlin coroutines to handle the request in non-blocking way.\n\nEach handler accepts [`Context`](https://github.com/trueangle/kotlin-native-aws-lambda-runtime/blob/68025bacc26ca075d8d0e9419c45b855a8b4003b/lambda-runtime/src/commonMain/kotlin/io/github/trueangle/knative/lambda/runtime/api/Context.kt#L1) object which can be used to get information about the function execution environment, such as the request ID, resource limits, and other details.\n\n### 5. Specify Main Function\nCreate application entry point using standard `main` function. Call `LambdaRuntime.run` to execute Lambda by passing handler to it.\n\n```kotlin\nfun main() = LambdaRuntime.run { HelloWorldLambdaHandler() }\n```\n\nOr for SampleStreamingHandler\n\n```kotlin\nfun main() = LambdaRuntime.run { SampleStreamingHandler() }\n\n```\n\nFor more examples refer to project's sample.\n\n## Testing Runtime locally\n\nUse the [AWS runtime emulator](https://github.com/aws/aws-lambda-runtime-interface-emulator) to run the runtime locally.\n\n1. `./gradlew build` to build the Lambda executable.\n2. Modify `runtime-emulator/Dockerfile` to set the path to the generated executable (.kexe) file in `build/bin/linuxX64/releaseExecutable`.\n3. Run `docker build -t sample:latest .`\n4. Start server `docker run -p 9000:8080 sample:latest`\n5. Execute the function\n   using `curl -XPOST \"http://localhost:9000/2015-03-31/functions/function/invocations\" -d '{}'`\n\n## Build and deploy to AWS\n\n1. Make sure you have applied the plugin `id(\"io.github.trueangle.plugin.lambda\") version \"0.0.1\"`\n2. Execute `./gradlew buildLambdaRelease`. The command will output the path to the archive containing lambda executable (YOUR_MODULE_NAME.kexe) located in (YOUR_MODULE_NAME/build/bin/lambda/release/YOUR_MODULE_NAME.zip)\n3. Deploy .zip archive to AWS. If you have never used AWS Lambda\n   before, [learn how to deploy Lambda function as zip archive manually](https://docs.aws.amazon.com/lambda/latest/dg/configuration-function-zip.html)\n   or\n   using [AWS CLI](https://docs.aws.amazon.com/codedeploy/latest/userguide/getting-started-codedeploy.html):\n\n```bash\n$ aws lambda create-function --function-name LAMBDA_FUNCTION_NAME \\\n  --handler YOUR_MODULE_NAME.kexe \\ # Important to specify the name of the Lambda executable. \n  --zip-file YOUR_MODULE_NAME.zip \\\n  --runtime provided.al2023 \\ # Change this to provided.al2 if you would like to use Amazon Linux 2\n  --architecture x86_64 \\ # or arm64\n  --role arn:aws:iam::XXXXXXXXXXXXX:role/YOUR_LAMBDA_EXECUTION_ROLE \\\n  --tracing-config Mode=Active\n```\n\nTest the function using the AWS CLI:\n\n```bash\n$ aws lambda invoke\n--cli-binary-format raw-in-base64-out \\\n--function-name LAMBDA_FUNCTION_NAME \\\n--payload '{\"command\": \"Say Hi!\"}' \\\noutput.json\n$ cat output.json \n```\n\n## Logging\n\nThe Runtime uses AWS logging conventions for enhanced log capture, supporting String and JSON log\noutput\nformat. It also allows to dynamically control log levels without altering your code, simplifying\nthe debugging process. Additionally, you can direct logs to specific Amazon CloudWatch log groups,\nmaking log management and aggregation more efficient at scale. More details on how to set log format\nand level refer to the article.\nhttps://aws.amazon.com/blogs/compute/introducing-advanced-logging-controls-for-aws-lambda-functions/\n\nUse the global Log object with extension functions. The log message accepts any object / primitive type.\n\n```kotlin\nLog.trace(message: T?) // The most fine-grained information used to trace the path of your code's execution\n\nLog.debug(message: T?) // Detailed information for system debugging\n\nLog.info(message: T?) // Messages that record the normal operation of your function\n\nLog.warn(message: T?) // Messages about potential errors that may lead to unexpected behavior if unaddressed\n\nLog.error(message: T?) // Messages about problems that prevent the code from performing as expected\n\nLog.fatal(message: T?) // Messages about serious errors that cause the application to stop functioning\n```\n\n## Troubleshooting\n\n- For Amazon Linux 2023, create a [Lambda layer](https://docs.aws.amazon.com/lambda/latest/dg/chapter-layers.html) with the libcrypt.so dependency. This library can be taken from your Linux machine or via the [Github Action workflow](https://github.com/trueangle/kotlin-native-aws-lambda-runtime/actions/workflows/libcrypt.yml).\n- Currently, it's not possible to build ARM type target on Linux machine (use macOS instead) as Kotlin repo misses necessary metadata. For more details, see:\n    1. The list of supported targets for Kotlin Native  https://repo.maven.apache.org/maven2/org/jetbrains/kotlin/kotlin-native-prebuilt/\n    2. https://youtrack.jetbrains.com/issue/KT-36871/Support-Aarch64-Linux-as-a-host-for-the-Kotlin-Native\n","funding_links":[],"categories":["Recently Updated","Libraries"],"sub_categories":["[Sep 16, 2024](/content/2024/09/16/README.md)"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftrueangle%2Fkotlin-native-aws-lambda-runtime","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftrueangle%2Fkotlin-native-aws-lambda-runtime","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftrueangle%2Fkotlin-native-aws-lambda-runtime/lists"}