SkilVaultSign inStart free

Catalogue / java-lambda-caller

java-lambda-caller

Older skill: source not recordedSignedGuides the agent through calling and administering AWS Lambda functions from Java with AWS SDK for Java 2.x. Covers LambdaClient and LambdaAsyncClient construction, synchronous and event-style invocations with JSON payloads, typed mapping with Jackson, function create, list, update and delete flows,…
---
name: java-lambda-caller
description: >
  Guides the agent through calling and administering AWS Lambda functions from Java with AWS SDK for Java 2.x. Covers LambdaClient and LambdaAsyncClient construction, synchronous and event-style invocations with JSON payloads, typed mapping with Jackson, function create, list, update and delete flows, environment, memory and timeout settings, Spring Boot wiring, and Mockito tests. Use when the user wants Java code that invokes a Lambda function, hides Lambda calls behind a Spring service, changes function settings through the SDK, or diagnoses invocation failures in a Java project. Not for writing the handler code that runs inside a Lambda, for other AWS services, or for AWS SDKs in other languages.
allowed-tools: Read, Write, Edit, Bash, Glob, Grep
---

The Java caller's side of AWS Lambda

You are writing Java that treats a Lambda function as a remote procedure and, when asked, administers that function through the same SDK. Move through five layers in order:

  1. Add the SDK and JSON libraries to the build.
  2. Construct clients that live for the lifetime of the application.
  3. Invoke functions — blocking, queued, or typed.
  4. Administer functions — inspect freely, mutate only with the user's blessing.
  5. Wrap everything in application services with tests that never touch AWS.

Bring in the libraries

Pin all SDK modules with the BOM, then pull in the Lambda module without a version:

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>software.amazon.awssdk</groupId>
      <artifactId>bom</artifactId>
      <version>2.31.5</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependency>
  <groupId>software.amazon.awssdk</groupId>
  <artifactId>lambda</artifactId>
</dependency>

Gradle equivalents, including the Jackson dependency that payload mapping needs:

implementation platform('software.amazon.awssdk:bom:2.31.5')
implementation 'software.amazon.awssdk:lambda'
implementation 'com.fasterxml.jackson.core:jackson-databind'

Construct the clients once

Build a single client per application and inject it everywhere. SDK clients own connection pools and are safe to share across threads; manufacturing one per call produces connection churn and wasted sockets.

LambdaClient lambda = LambdaClient.builder()
    .region(Region.AP_SOUTHEAST_2)
    .build();

LambdaAsyncClient asyncLambda = LambdaAsyncClient.builder()
    .region(Region.AP_SOUTHEAST_2)
    .build();

Use the async variant at call sites that prefer a CompletableFuture over a blocked thread.

Never place access keys, session tokens, or any secret into source files, configuration you author, or log output. The client locates credentials by itself through the default provider chain — environment, system properties, then a local profile — and that behavior should stay untouched. Do not read credential files or secret environment variables on the user's behalf, and do not echo them anywhere.

Run functions

Blocking call that needs the answer

This is the default invocation shape: the SDK waits for the function to finish and hands back its output. A function that crashes still yields HTTP 200, so checking only the status code hides failures — always inspect functionError() first:

public String simulatePrice(LambdaClient lambda, String quoteJson) {
    InvokeResponse res = lambda.invoke(InvokeRequest.builder()
        .functionName("pricing-simulator")
        .payload(SdkBytes.fromUtf8String(quoteJson))
        .build());

    if (res.functionError() != null) {
        throw new IllegalStateException(
            "pricing-simulator reported " + res.functionError()
                + " with body " + res.payload().asUtf8String());
    }
    return res.payload().asUtf8String();
}

Queued event when nobody waits

Choose the EVENT invocation type when the caller does not want the result. Lambda buffers the event and retries it if processing fails. The response body is empty in this mode, so never try to decode it — the status code is the only useful field:

InvokeRequest req = InvokeRequest.builder()
    .functionName("lead-scorer")
    .invocationType(InvocationType.EVENT)
    .payload(SdkBytes.fromUtf8String(eventJson))
    .build();
InvokeResponse res = lambda.invoke(req);
// res.payload() is empty here; only res.statusCode() means anything

Objects in, objects out

Most call sites should not juggle strings. Serialize the query with Jackson, send it, check for a function error, then deserialize the reply:

public <Q, R> R roundTrip(LambdaClient lambda, String fn, Q query, Class<R> resultType) {
    String body;
    try {
        body = mapper.writeValueAsString(query);
    } catch (JsonProcessingException e) {
        throw new FunctionCallException(fn, "request serialization failed", e);
    }
    InvokeResponse res = lambda.invoke(InvokeRequest.builder()
        .functionName(fn)
        .payload(SdkBytes.fromUtf8String(body))
        .build());
    if (res.functionError() != null) {
        throw new FunctionCallException(fn, res.payload().asUtf8String());
    }
    try {
        return mapper.readValue(res.payload().asUtf8String(), resultType);
    } catch (JsonProcessingException e) {
        throw new FunctionCallException(fn, "response deserialization failed", e);
    }
}

Keep two failure families straight when you reason about retries:

| Signal | Meaning | Reaction | | --- | --- | --- | | functionError() set to Handled or Unhandled | The function ran and failed, deliberately or by exception | Surface the payload to the caller; retrying usually repeats the failure | | LambdaException thrown, e.g. ResourceNotFoundException | The service rejected the request before execution | Do not retry; the function name is wrong | | LambdaException thrown, e.g. TooManyRequestsException | Throttling or a concurrency cap | Retry with exponential backoff and jitter |

Administer functions

Inspecting is free: call getFunction(...).configuration() to read runtime, timeout, memory, and environment before proposing changes, and listFunctions() to see what exists.

Everything that changes state — creating a function, publishing new code, editing configuration, deleting — rewrites live infrastructure in the user's account. It can break production traffic and generate charges. Before you execute any of these against a real account, whether by running generated code, running a snippet yourself, or issuing a shell command, stop and get the user's explicit confirmation naming the exact function and account. Offer to rehearse against a disposable name carrying a stage suffix such as -dev first. Writing or editing the code, without running it, needs no gate. The same caution applies the first time you execute an invocation yourself: a live call runs real code that may send mail, write databases, and bill the account.

Create

CreateFunctionResponse created = lambda.createFunction(CreateFunctionRequest.builder()
    .functionName("receipt-vault-dev")
    .runtime(Runtime.JAVA21)
    .role(roleArn) // must already exist and trust the Lambda service
    .handler("com.northwind.vault.Handler::store")
    .code(FunctionCode.builder()
        .zipFile(SdkBytes.fromByteArray(zipBytes))
        .build())
    .timeout(45)
    .memorySize(768)
    .environment(Environment.builder()
        .variables(Map.of("VAULT_STAGE", "dev"))
        .build())
    .build());

The role must be created beforehand and grant the Lambda service permission to assume it; provisioning roles is outside this skill.

Publish code, then change settings — never simultaneously

A function sits in a transitional state right after a code publish, and a configuration change sent into that window is rejected. Send the code, let the SDK waiter bridge the gap, then send the settings:

lambda.updateFunctionCode(UpdateFunctionCodeRequest.builder()
    .functionName("receipt-vault-dev")
    .zipFile(SdkBytes.fromByteArray(zipBytes))
    .publish(true) // cut a numbered version
    .build());

lambda.waiter().waitUntilFunctionUpdated(
    GetFunctionRequest.builder().functionName("receipt-vault-dev").build());
lambda.updateFunctionConfiguration(UpdateFunctionConfigurationRequest.builder()
    .functionName("receipt-vault-dev")
    .timeout(75)
    .memorySize(1536)
    .environment(Environment.builder()
        .variables(Map.of("VAULT_STAGE", "dev", "RETENTION_DAYS", "90"))
        .build())
    .build());

Delete

Deleting cannot be undone. Never carry out a removal against an account without the confirmation described above, and when the user does approve, scope the removal to a single published version through a qualifier rather than erasing the whole function in one stroke.

Plug into Spring

Hand the client to the container so it manages construction and shutdown:

@Configuration
public class RemoteFunctionConfig {
    @Bean
    public LambdaClient lambdaClient() {
        return LambdaClient.builder().region(Region.AP_SOUTHEAST_2).build();
    }
}

Put the SDK calls inside one generic bridge, then give each downstream function a narrow, typed facade with its name injected from configuration instead of hardcoded:

@Service
public class FunctionBridge {
    private final LambdaClient lambda;
    private final ObjectMapper mapper;

    public FunctionBridge(LambdaClient lambda, ObjectMapper mapper) {
        this.lambda = lambda;
        this.mapper = mapper;
    }

    public <R> R call(String fn, Object query, Class<R> resultType) { /* roundTrip above */ }
    public void emit(String fn, Object event) { /* EVENT invocation above */ }
}
public interface RenewalEstimator {
    RenewalQuote estimate(RenewalQuery query);
}

@Service
public class LambdaRenewalEstimator implements RenewalEstimator {
    private final FunctionBridge bridge;

    @Value("${remote-functions.renewal-estimator}")
    private String functionName;

    public LambdaRenewalEstimator(FunctionBridge bridge) {
        this.bridge = bridge;
    }

    public RenewalQuote estimate(RenewalQuery query) {
        return bridge.call(functionName, query, RenewalQuote.class);
    }
}

This layering keeps AWS types out of business logic and leaves a single mockable seam per function.

Hard limits to respect while writing code

| Constraint | Bound | Consequence for your code | | --- | --- | --- | | Payload, blocking invoke | 6 MB | Oversized requests are refused; park bulky data in object storage and pass a key | | Payload, EVENT invoke | 256 KB | Far tighter; keep queued events lean | | Function timeout | 15 minutes | The client's read timeout must be longer than the function's, or the client abandons the call first | | Memory | 128 MB to 10 GB | The allocation also fixes CPU and network share | | Deployment package | 250 MB unzipped, layers included | Large dependencies push toward container images |

Verify with tests

Unit tests must not reach a real account. Mock LambdaClient and stub invoke with a constructed InvokeResponse, and add a companion case proving the failure path is loud rather than silent:

@ExtendWith(MockitoExtension.class)
class FunctionBridgeTest {
    @Mock LambdaClient lambda;

    @Test
    void decodes_result_payload() {
        when(lambda.invoke(any(InvokeRequest.class))).thenReturn(InvokeResponse.builder()
            .statusCode(200)
            .payload(SdkBytes.fromUtf8String(
                "{\"quoteId\":\"QT-8814\",\"annualPremium\":43250}"))
            .build());

        RenewalQuote q = new FunctionBridge(lambda, new ObjectMapper())
            .call("renewal-estimator", new RenewalQuery("POL-2049"), RenewalQuote.class);

        assertThat(q.quoteId()).isEqualTo("QT-8814");
    }

    @Test

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