The goal is to showcase that the Java programming language can compete as well in the serverless space.
We will be building a native executable with the help of GraalVM's Native Image technology, and deploy it on AWS Lambda.
Custom Lambda runtimes
Lambdas support managed runtimes for most prominent programming languages, including Java.
We won´t be using the AWS runtime for Java in this tutorial because the whole point is to not run on the JVM!
AWS Lambda allow you to run your own custom runtime directly on the Amazon Linux 2 (AL2).
This will allow us to run a native binary, provided it is for AL2 and x86_64/arm64 architecture:
All we need to provide is a zip archive containing a bootstrap file and the function being invoked:
.
├── bootstrap
├── function.sh
Example Bootstrap
bootstrap
#!/bin/sh
set -euo pipefail
# Initialization - load function handler
source $LAMBDA_TASK_ROOT/"$(echo $_HANDLER | cut -d. -f1).sh"
# Processing
while true
do
HEADERS="$(mktemp)"
# Get an event. The HTTP request will block until one is received
EVENT_DATA=$(curl -sS -LD "$HEADERS" "http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/next")
# Extract request ID by scraping response headers received above
REQUEST_ID=$(grep -Fi Lambda-Runtime-Aws-Request-Id "$HEADERS" | tr -d '[:space:]' | cut -d: -f2)
# Run the handler function from the script
RESPONSE=$($(echo "$_HANDLER" | cut -d. -f2) "$EVENT_DATA")
# Send the response
curl "http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/$REQUEST_ID/response" -d "$RESPONSE"
done