Run Grails on AWS Lambda with the CDK

Serverless deployment can make a Grails application easier to scale, but moving a servlet-style web app into functions requires more than packaging a WAR. Running Grails in Amazon Lambda works well when HTTP handling remains stateless, database and file storage live in managed services, and infrastructure is defined with the AWS Cloud Development Kit (CDK).

This guide uses a Lambda container image with an embedded servlet container and the Lambda Web Adapter, alongside API Gateway, Amazon ECR and AWS CloudFormation. CDK turns those resources into a repeatable stack, so Australian development teams can review changes, provision matching environments and roll back releases without clicking through the AWS console.

Choose the AWS Sydney or Melbourne Region to place most application traffic close to users in Australia’s largest cities. Australians commonly use mobile devices while commuting, while regional and rural users may have less consistent coverage, so responses should stay small and timeouts should account for variable networks. The local market includes cloud-native SaaS, fintech, online retail and community platforms, where demand can fluctuate around releases, sporting events and promotional campaigns.

The design must also respect Australian privacy and communications rules. The Privacy Act 1988 and Australian Privacy Principles govern many personal records, while the Spam Act 2003 affects commercial email. Treat logs, traces and database replicas as potential copies of customer data rather than disposable infrastructure artefacts.

Architecture for a stateless Grails service

Begin with a clear boundary around request handling. An API Gateway HTTP API accepts public requests and invokes a Lambda function containing the Grails application. The function talks to Amazon Aurora PostgreSQL Serverless v2 or RDS through a VPC, stores uploaded files in S3, and reads secrets from Secrets Manager. Use DynamoDB only where the data model suits it; Grails applications using JDBC and Hibernate usually benefit more from PostgreSQL.

Grails session state must not live in the function’s container. Store sessions in Redis or use signed, short-lived tokens, and keep uploaded files out of /tmp, which is ephemeral and limited. Quartz jobs, caches and scheduled tasks also need an external trigger or shared backing service. For long-running work, return a job identifier and process the task through SQS rather than holding a Lambda invocation open.

Keep synchronous requests short. Set the Lambda timeout to the same limit or below the API Gateway timeout, normally 20 to 30 seconds, and publish health routes separately from expensive diagnostic routes. A useful flow is Route 53 or CloudFront, HTTP API, Lambda, then RDS and S3. The CDK stack can also add WAF, a JWT authorizer for Amazon Cognito, alarms and log retention, but those controls should follow an explicit threat model.

Prepare the Grails application

Use a JDK version supported by both your Grails release and the Lambda runtime, then verify the application locally with grails run and the full test suite. Pin Java, Grails and dependency versions in the build. A local Docker build is also useful because it reveals missing native libraries, write permissions and assumptions about a persistent file system before AWS is involved.

Produce a deployable WAR with grails war. Copy that artefact into the servlet container rather than starting a development server in production. Externalise environment-specific values such as database URLs, upload locations and feature-flag endpoints; do not bake AWS account identifiers or credentials into application.yml. Run database migrations as a controlled release step, not whenever a new function instance starts.

Release controls remain important after the serverless boundary. For staged releases, the site’s feature toggle tutorial shows how to separate code deployment from feature exposure. Keep a toggle’s state in a shared service, and give every role enough permission to read it without granting control over unrelated infrastructure.

Define infrastructure with AWS CDK

Treat the CDK stack as the source of truth for the runtime boundary. A minimal HTTP path needs a DockerImageFunction, an HttpApi and an output containing the API URL. The VPC, subnets, security groups, database proxy, ECR repository and alarms can live in the same stack or in a separate stack with explicit dependencies.

The core Java looks like this:

DockerImageFunction grails = new DockerImageFunction(this, "GrailsFunction",
    DockerImageFunctionProps.builder()
        .code(DockerImageAsset.fromPath("lambda"))
        .memorySize(1024)
        .timeout(Duration.ofSeconds(30))
        .environment(Map.of("GRAILS_ENV", "prod"))
        .build());

HttpApi api = new HttpApi(this, "GrailsHttpApi");
api.addDefaultRoute(new HttpLambdaIntegration("Grails", grails));

new CfnOutput(this, "ApiUrl", CfnOutputProps.builder()
    .value(api.getUrl())
    .build());

DockerImageAsset builds the image and publishes it to ECR during synthesis. addDefaultRoute forwards unmatched paths, which is useful for Grails URL mappings. Add explicit routes only when they provide clearer metrics or authorisation policies. The sample deliberately leaves VPC settings and database grants out; production stacks need them, including permission for Lambda to manage VPC network interfaces.

Create the infrastructure project with cdk init app --language=java, then run cdk bootstrap once per target account and Region. Preview changes with cdk diff and deploy with cdk deploy from a trusted workstation or CI runner. AWS CDK v2 uses CloudFormation underneath, so drift can be detected and the same reviewed template can target test, staging and production accounts.

Package, publish and deploy

Build the image on a Lambda-compatible provided.al2023 base containing the Runtime Interface Client and Lambda Web Adapter. Install a Tomcat release compatible with your Grails generation, copy the WAR as ROOT.war, and use a startup script that runs catalina.sh run as the foreground process. Point the adapter at the Tomcat port and give it a lightweight readiness path. Avoid catalina.sh start, which can conceal a failed server startup.

The container needs writable locations for Tomcat work files and logs, but no durable application state. Mounting an EFS file system can ease shared access, although it adds latency and cost; for most Grails deployments, PostgreSQL plus S3 is simpler. Keep /tmp for temporary processing only, and configure S3 multipart uploads for larger documents.

Deploy through CI rather than a developer console. The pipeline should authenticate to AWS with short-lived credentials, run tests, synthesise the CDK app, review the diff and promote the same image digest through environments. Publish an immutable image digest rather than relying on latest, record it in deployment metadata and retain a tested rollback path. Schema changes should be backward-compatible with the previous application version during the rollback window.

Secure configuration and user data

Load non-secret settings from Lambda environment variables or Systems Manager Parameter Store, and retrieve passwords, tokens and signing keys from Secrets Manager at runtime. Grant the function read access only to the specific secret versions it needs. Rotate credentials without rebuilding the image, and ensure CloudFormation does not place secret values in templates, outputs or environment-variable descriptions visible to operators.

Protect the HTTP API with Cognito or another OIDC identity provider when the application has user accounts. CDK can create a JWT authorizer, configure allowed origins and add throttling; WAF can provide managed protections for common web attacks. Authentication does not replace authorisation, so enforce object ownership and tenant boundaries inside Grails services. Under the Australian Privacy Act, assess access controls, retention and notification workflows for eligible personal information.

If the product includes maps, the Leaflet map integration example shows the Grails plugin side of that feature. Bundle the JavaScript and CSS in the WAR, but let the browser request map tiles from the chosen provider instead of proxying every tile through Lambda. Check the provider’s Australian availability, caching terms and privacy policy, since tile requests can reveal user location even when the Grails record itself contains no coordinates.

Reliability and cost recommendations

Send structured logs to CloudWatch Logs with the request identifier, route, duration, status and deployment version. Enable X-Ray tracing when request tracing adds enough value to justify its cost, and create alarms for error rate, throttles and p95 latency. A health check should distinguish process liveness from dependency readiness; otherwise a brief database interruption can make every function appear unhealthy.

Lambda pricing can be dominated by requests, duration and memory rather than compute alone. Include API Gateway, ECR storage, logs, NAT gateways, RDS and backups in the estimate. A private function needs ECR and CloudWatch access through VPC endpoints where appropriate; an always-on NAT gateway can otherwise become the largest surprise bill. Measure load with realistic Grails sessions and uploads before choosing memory or provisioned concurrency.

Bursty Australian workload—an Australian esports network receiving traffic around match times is a useful comparison—benefits from planning for concurrency rather than average traffic. Use load tests, alarms and a queue for asynchronous work instead of scaling the function indiscriminately. Remember that support and operations teams can span Australian Eastern Standard Time and Australian Central Standard Time, so dashboards and incident rotations should display explicit time zones.

Deploy your first Grails Lambda stack

Your first stack can stay deliberately small: one HTTP API, one Lambda image, one PostgreSQL database and one S3 bucket. Add the Cognito authorizer, WAF rules, database proxy and alarms once the request flow is working. This keeps the first deployment debuggable while preserving clear places to add isolation, queues or separate stacks later.

Build the WAR, package the container, add the CDK stack and run cdk deploy against a test account. Open the HTTP API URL printed by the stack outputs, call the health route, then exercise representative Grails controllers with authentication and database access enabled. Promote the reviewed image digest through CI, watch the initial alarms and complete the production release only after the smoke and rollback checks pass.