SkilVaultSign inStart free

Catalogue / java-lambda-handler-playbook

java-lambda-handler-playbook

Older skill: source not recordedSignedBuilds and ships Java AWS Lambda functions with either raw Java or Micronaut: event adapters for API Gateway, ALB and S3, service composition, packaging with Gradle or Maven, cold-start measurement, handler and repository tests, and reviewable SAM or Serverless release definitions. Use when the user…
---
name: java-lambda-handler-playbook
description: >-
  Builds and ships Java AWS Lambda functions with either raw Java or Micronaut: event
  adapters for API Gateway, ALB and S3, service composition, packaging with Gradle or
  Maven, cold-start measurement, handler and repository tests, and reviewable SAM or
  Serverless release definitions. Use when the user says "deploy a Java Lambda",
  "Java Lambda cold start is slow", "Micronaut Lambda handler", "API Gateway Java
  handler", "package Java Lambda with Shadow", or "canary deploy a Java function".
  Not for Lambda in other languages, and not for running deployments, traffic shifts,
  or cloud changes without explicit approval.
---

Establish the runtime, event, and release boundary

Inspect these before writing code:

  • Existing Java, build-tool and dependency versions
  • The actual Lambda runtime and CPU architecture in the target account
  • Event source (API Gateway, ALB, S3, direct) and its authentication contract
  • Deployment tooling already in the project

The user supplies verified installed dependencies, build tools, CLI programs, and local container images. Do not download or execute packages, installers, remote scripts, or container images.

Choose an approach by need:

  • Raw Java — small handler, explicit composition, minimal dependencies.
  • Micronaut — compile-time dependency injection, configuration, introspection, and a

broader application model justify the extra dependencies.

Ahead-of-time processing removes some runtime work but not every reflection path, and neither approach guarantees a particular cold start. Treat any latency figure as a hypothesis to measure.

Confirming "write this handler" or "run this test suite" covers exactly that scope. Ask before any additional write, packaging beyond it, container use, API calls, secret access, configuration updates, IAM or network changes, uploads, deployment, version publication, alias traffic changes, scheduled scaling, tuning experiments, or resource removal. Before any cloud action, state the account, region, stage, resources, payloads, and cost implications.

Keep the project layout simple: build manifest, src/main/java, resource configuration/logging, src/test/java, an optional integration-test source set, event fixtures, and one reviewed Serverless or SAM definition. Separate business logic and persistence from Lambda transport so both are testable without AWS.

Normalize event formats before business logic

Each event shape differs in fields and response contract:

| Event | Watch out for | |---|---| | API Gateway REST (v1) proxy | Its specific request/response fields; base64 and binary media handling; CORS at the gateway | | HTTP API (v2) | Different field layout — never feed it to a REST v1 adapter | | ALB | Status description and encoding fields are required; verify multi-value headers/query support | | S3 | URL-encoded keys, every record in the event, duplicate delivery | | Direct invocation | No HTTP envelope at all |

Match the installed event classes explicitly rather than assuming shapes.

Use RequestHandler<Input,Output> for typed event DTOs, or RequestStreamHandler when parsing streams or handling an explicit binary envelope. A stream handler still receives the invocation event; binary HTTP payloads may arrive base64 encoded inside JSON rather than as raw bytes. Validate size and media type before decoding.

The adapter below performs real interface delegation for all CRUD verbs. Supply a durable repository implementation and authentication/ownership enforcement from the application. Notes:

  • The Lambda runtime constructs the handler, so ship a concrete composition subclass or

delegating handler only once a verified durable Catalog exists — an in-memory map is not a production datastore.

  • Give parsing/validation, not-found, conditional-write conflicts, and infrastructure

failures distinct response contracts instead of mapping everything to a bad request.

  • Authorize every mutation at the application boundary; approval to deploy code is not

end-user API authorization.

  • Avoid wildcard CORS as a default for authenticated APIs.
  • Do not log full paths, bodies, user identifiers, or exception messages unless their

disclosure has been reviewed.

package atelier.lambda;

import java.util.Map;
import java.util.List;
import java.util.Optional;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public final class CatalogHandler implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
  public record Input(String label) {}
  public record Item(String id, String label) {}
  public interface Catalog {
    List<Item> list();
    Optional<Item> find(String id);
    Item create(Input input);
    Optional<Item> update(String id, Input input);
    boolean delete(String id);
  }
  private static final ObjectMapper JSON = new ObjectMapper();
  private final Catalog catalog;
  public CatalogHandler(Catalog catalog) { this.catalog = catalog; }
  // Lambda runtime construction belongs in a concrete composition subclass
  // or a separate handler delegating here with a verified durable Catalog.
  @Override public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent event, Context context) {
    try {
      if (event == null || event.getHttpMethod() == null)
        return response(400, Map.of("error", "invalid event"));
      Map<String,String> path = event.getPathParameters();
      String id = path == null ? null : path.get("itemId");
      return switch(event.getHttpMethod()) {
        case "GET" -> id == null ? response(200, catalog.list()) :
          catalog.find(id).map(item -> response(200,item))
            .orElseGet(() -> response(404,Map.of("error","item missing")));
        case "POST" -> id != null ? response(405,Map.of("error","unsupported operation")) :
          response(201,catalog.create(input(event)));
        case "PUT" -> id == null ? response(400,Map.of("error","item ID required")) :
          catalog.update(id,input(event)).map(item -> response(200,item))
            .orElseGet(() -> response(404,Map.of("error","item missing")));
        case "DELETE" -> id == null ? response(400,Map.of("error","item ID required")) :
          catalog.delete(id) ? response(204,null) : response(404,Map.of("error","item missing"));
        default -> response(405,Map.of("error","unsupported method"));
      };
    } catch (IllegalArgumentException | JsonProcessingException error) {
      return response(400,Map.of("error","invalid request body"));
    } catch (Exception error) {
      if(context != null) context.getLogger().log("catalog failure request=" + context.getAwsRequestId());
      return response(500,Map.of("error","internal failure"));
    }
  }
  private Input input(APIGatewayProxyRequestEvent event) throws JsonProcessingException {
    String body = event.getBody();
    if(body == null) throw new IllegalArgumentException("body required");
    if(Boolean.TRUE.equals(event.getIsBase64Encoded()))
      body = new String(Base64.getDecoder().decode(body), StandardCharsets.UTF_8);
    Input input = JSON.readValue(body,Input.class);
    if(input == null || input.label() == null || input.label().isBlank() || input.label().length() > 120)
      throw new IllegalArgumentException("label invalid");
    return new Input(input.label().strip());
  }
  private static APIGatewayProxyResponseEvent response(int status,Object value) {
    try {
      return new APIGatewayProxyResponseEvent().withStatusCode(status)
        .withHeaders(Map.of("Content-Type","application/json"))
        .withIsBase64Encoded(false).withBody(status == 204 ? "" : JSON.writeValueAsString(value));
    } catch(JsonProcessingException error) {
      return new APIGatewayProxyResponseEvent().withStatusCode(500)
        .withHeaders(Map.of("Content-Type","application/json"))
        .withBody("{\"error\":\"serialization failure\"}");
    }
  }
}

For S3 triggers:

  • Inspect every record and decode the object's URL-encoded key correctly.
  • Validate the permitted bucket and prefix; authorize the caller.
  • Handle duplicate delivery idempotently.
  • Reuse the S3 client and process the object through a bounded stream — do not merely

log its location and report success.

  • Preserve the failure/retry behavior of the real event source, and guard against the

function writing objects that trigger itself.

Compose services once, without accidental initialization calls

  • Cache safe, reusable AWS SDK v2 clients and immutable configuration for warm

invocations. Static initialization or a lazy holder can both be appropriate; do not turn "reuse clients" into "eagerly initialize every service".

  • The Lambda runtime constructs the handler during initialization, so a constructor is

not automatically first-use lazy. Defer genuinely optional resources behind a tested lazy provider.

  • Validate required resource names before client creation; keep clients injectable into

repository constructors for tests.

A DynamoDB repository should provide:

  1. GetItem with explicit attribute mapping
  2. Conditional PutItem using attribute_not_exists(id)
  3. An explicitly defined update expression
  4. DeleteItem semantics, with deliberate handling of missing attributes and conditional

conflicts

Query a defined key or index rather than defaulting to Scan. Scope tenant ownership in keys and conditions; a caller-supplied ID is never authorization by itself.

A thread-safe initialization holder can cache a composed service without double-checked-locking boilerplate. Remember that static state exists only per execution environment and can vanish at any time — it is never durable storage, and request-specific data must not leak into later calls. Do not call listTables or issue a health request merely to construct the application: it widens IAM, adds latency, and makes an unrelated network call.

For AWS clients:

  • Select only the SDK modules you need, not an aggregate.
  • Configure connection/read/API-attempt/overall timeouts below the remaining Lambda

budget; use a lightweight HTTP adapter such as the URLConnection client when its feature set suffices, and account for stale connections after idle periods and retries.

For databases, consider RDS Proxy and a small per-environment pool. Illustrative Hikari settings: maximum pool 2, minimum idle 0, idle timeout 10 s, connection timeout 5 s, maximum lifetime 5 min — verify driver and pool minima under real load. Total connections scale with the number of execution environments; such a pool does not by itself prevent database overload.

Add Micronaut only through its actual installed API

  • Use micronaut-function-aws-api-proxy or the matching function adapter for your event

boundary. Custom-runtime dependencies are for an actual custom runtime, not an automatic requirement of a managed Java runtime.

  • Pick one supported entry pattern: a MicronautRequestHandler overriding execute, a

@FunctionBean implementing Function, or a verified stream/custom-runtime adapter. Calling an assumed handleRequest on a runtime class is not proof of a supported stream integration.

  • Use constructor injection, jakarta.inject.Singleton, verified @Factory bean

declarations, configuration properties, and conditionally selected implementations. Do not assume a particular @Lazy annotation exists or use the wrong Singleton package; test bean creation timing explicitly. @PostConstruct runs when its bean is created, not inherently on first request.

Preview shortened. The full SKILL.md is in the pack.