diff --git a/lambda-durable-execution-java-cdk/.gitignore b/lambda-durable-execution-java-cdk/.gitignore new file mode 100644 index 000000000..7be64f01b --- /dev/null +++ b/lambda-durable-execution-java-cdk/.gitignore @@ -0,0 +1,6 @@ +node_modules +cdk.out +*.js +*.d.ts +package-lock.json +src/target diff --git a/lambda-durable-execution-java-cdk/README.md b/lambda-durable-execution-java-cdk/README.md new file mode 100644 index 000000000..b332648e5 --- /dev/null +++ b/lambda-durable-execution-java-cdk/README.md @@ -0,0 +1,125 @@ +# Lambda Durable Execution with Java SDK + +This pattern deploys a Lambda durable function written in Java that orchestrates a multi-step order processing workflow with automatic checkpointing and failure recovery. + +Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/lambda-durable-execution-java-cdk + +Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example. + +## Requirements + +- [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources. +- [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured +- [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) +- [Node and NPM](https://nodejs.org/en/download/) installed +- [AWS CDK](https://docs.aws.amazon.com/cdk/latest/guide/cli.html) installed +- [Java 17+](https://docs.aws.amazon.com/corretto/latest/corretto-17-ug/downloads-list.html) installed +- [Apache Maven](https://maven.apache.org/install.html) installed + +## Deployment Instructions + +1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository: + ```bash + git clone https://github.com/aws-samples/serverless-patterns + ``` +2. Change directory to the pattern directory: + ```bash + cd serverless-patterns/lambda-durable-execution-java-cdk + ``` +3. Build the Java Lambda function: + ```bash + cd src + mvn clean package -q + cd .. + ``` +4. Install CDK dependencies: + ```bash + npm install + ``` +5. Deploy the stack: + ```bash + cdk deploy + ``` + +## How it works + +This pattern uses the [AWS Lambda Durable Execution SDK for Java](https://github.com/aws/aws-durable-execution-sdk-java/) (GA April 2026) to build a resilient order processing workflow. + +The Java function extends `DurableHandler` and uses `DurableContext` to: + +1. **Validate order** — `ctx.step()` checkpoints the validation result +2. **Reserve inventory** — `ctx.step()` checkpoints the reservation ID +3. **Process payment** — `ctx.step()` checkpoints the payment confirmation +4. **Wait for warehouse** — `ctx.wait()` suspends execution for 5 seconds with zero compute charges +5. **Confirm shipment** — `ctx.step()` checkpoints the tracking number + +If the function is interrupted at any point, it replays from the beginning but skips completed steps using stored checkpoint results. + +### Architecture + +``` +┌─────────────────────────────────────────────────────────┐ +│ Lambda Durable Function │ +│ │ +│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌────────┐ │ +│ │ Validate │→ │ Reserve │→ │ Process │→ │ Wait │ │ +│ │ Order │ │Inventory │ │ Payment │ │ (free) │ │ +│ └──────────┘ └──────────┘ └──────────┘ └────────┘ │ +│ ↓ checkpoint ↓ checkpoint ↓ checkpoint │ │ +│ ↓ │ +│ ┌──────────┐ │ +│ │ Confirm │ │ +│ │ Shipment │ │ +│ └──────────┘ │ +└─────────────────────────────────────────────────────────┘ +``` + +### Key Java SDK concepts + +- **`DurableHandler`** — Base class for durable functions. Extend this and implement `handleRequest(I input, DurableContext ctx)`. +- **`ctx.step(name, type, fn)`** — Execute code with automatic checkpointing and retry support. +- **`ctx.wait(name, duration)`** — Suspend execution without compute charges. +- **`ctx.invoke()`** — Invoke another Lambda function and wait for the result. +- **`ctx.map()`** — Apply a function across a collection concurrently. +- **`ctx.parallel()`** — Run multiple operations concurrently. + +## Testing + +1. After deployment, note the `FunctionAliasArn` output. + +2. Invoke the durable function using the alias ARN: + ```bash + aws lambda invoke \ + --function-name \ + --payload '{"orderId": "ORD-001", "amount": 149.99}' \ + --cli-binary-format raw-in-base64-out \ + output.json + + cat output.json + ``` + +3. Expected output: + ```json + { + "orderId": "ORD-001", + "status": "COMPLETED", + "validation": "VALIDATED", + "reservationId": "RES-a1b2c3d4", + "paymentId": "PAY-e5f6g7h8", + "trackingNumber": "TRACK-i9j0k1l2" + } + ``` + +4. Monitor the durable execution in the Lambda console under the **Durable executions** tab. + +## Cleanup + +```bash +cdk destroy +``` + +--- + +Copyright 2026 Amazon.com, Inc. or its affiliates. All Rights Reserved. + +SPDX-License-Identifier: MIT-0 diff --git a/lambda-durable-execution-java-cdk/bin/app.ts b/lambda-durable-execution-java-cdk/bin/app.ts new file mode 100644 index 000000000..b16bee3f5 --- /dev/null +++ b/lambda-durable-execution-java-cdk/bin/app.ts @@ -0,0 +1,7 @@ +#!/usr/bin/env node +import "source-map-support/register"; +import * as cdk from "aws-cdk-lib"; +import { LambdaDurableExecutionJavaStack } from "../lib/lambda-durable-execution-java-stack"; + +const app = new cdk.App(); +new LambdaDurableExecutionJavaStack(app, "LambdaDurableExecutionJavaStack"); diff --git a/lambda-durable-execution-java-cdk/cdk.json b/lambda-durable-execution-java-cdk/cdk.json new file mode 100644 index 000000000..822400f59 --- /dev/null +++ b/lambda-durable-execution-java-cdk/cdk.json @@ -0,0 +1,11 @@ +{ + "app": "npx ts-node --prefer-ts-exts bin/app.ts", + "watch": { + "include": ["**"], + "exclude": ["README.md", "cdk*.json", "**/*.d.ts", "**/*.js", "node_modules", "src"] + }, + "context": { + "@aws-cdk/aws-lambda:recognizeLayerVersion": true, + "@aws-cdk/core:checkSecretUsage": true + } +} diff --git a/lambda-durable-execution-java-cdk/example-pattern.json b/lambda-durable-execution-java-cdk/example-pattern.json new file mode 100644 index 000000000..5d3b18be4 --- /dev/null +++ b/lambda-durable-execution-java-cdk/example-pattern.json @@ -0,0 +1,62 @@ +{ + "title": "Lambda Durable Execution with Java SDK", + "description": "Build a resilient, multi-step order processing workflow using the AWS Lambda Durable Execution SDK for Java with automatic checkpointing and failure recovery.", + "language": "Java", + "level": "300", + "framework": "AWS CDK", + "introBox": { + "headline": "How it works", + "text": [ + "This pattern deploys a Lambda durable function written in Java that orchestrates a multi-step order processing workflow. The function uses the Durable Execution SDK for Java (v1.0.1) to automatically checkpoint progress at each step.", + "The workflow: (1) validates the order, (2) reserves inventory, (3) processes payment, (4) waits for warehouse processing (no compute charges), (5) confirms shipment. Each step is checkpointed, so if the function is interrupted, it resumes from the last completed step.", + "This is the first Java-based durable execution pattern. The Java SDK provides an idiomatic experience with DurableHandler and DurableContext, supporting steps, waits, callbacks, invoke, map, and parallel operations." + ] + }, + "gitHub": { + "template": { + "repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/lambda-durable-execution-java-cdk", + "templateURL": "serverless-patterns/lambda-durable-execution-java-cdk", + "projectFolder": "lambda-durable-execution-java-cdk", + "templateFile": "lib/lambda-durable-execution-java-stack.ts" + } + }, + "resources": { + "bullets": [ + { + "text": "Lambda Durable Execution SDK for Java on GitHub", + "link": "https://github.com/aws/aws-durable-execution-sdk-java/" + }, + { + "text": "Lambda Durable Functions Documentation", + "link": "https://docs.aws.amazon.com/lambda/latest/dg/durable-functions.html" + }, + { + "text": "Deploy Lambda durable functions with Infrastructure as Code", + "link": "https://docs.aws.amazon.com/lambda/latest/dg/durable-getting-started-iac.html" + } + ] + }, + "deploy": { + "text": [ + "cd src && mvn clean package -q", + "cd .. && cdk deploy" + ] + }, + "testing": { + "text": [ + "See the GitHub repo for detailed testing instructions." + ] + }, + "cleanup": { + "text": [ + "Delete the stack: cdk destroy." + ] + }, + "authors": [ + { + "name": "Nithin Chandran R", + "bio": "Technical Account Manager at AWS", + "linkedin": "nithin-chandran-r" + } + ] +} diff --git a/lambda-durable-execution-java-cdk/lib/lambda-durable-execution-java-stack.ts b/lambda-durable-execution-java-cdk/lib/lambda-durable-execution-java-stack.ts new file mode 100644 index 000000000..0a824684a --- /dev/null +++ b/lambda-durable-execution-java-cdk/lib/lambda-durable-execution-java-stack.ts @@ -0,0 +1,52 @@ +import * as cdk from "aws-cdk-lib"; +import * as lambda from "aws-cdk-lib/aws-lambda"; +import * as iam from "aws-cdk-lib/aws-iam"; +import { Construct } from "constructs"; + +export class LambdaDurableExecutionJavaStack extends cdk.Stack { + constructor(scope: Construct, id: string, props?: cdk.StackProps) { + super(scope, id, props); + + // Lambda function + const fn = new lambda.Function(this, "DurableOrderProcessorFn", { + runtime: lambda.Runtime.JAVA_17, + handler: "com.example.OrderProcessor::handleRequest", + code: lambda.Code.fromAsset("src/target/lambda-durable-execution-java-1.0.0.jar"), + timeout: cdk.Duration.minutes(15), + memorySize: 512, + description: "Durable order processing workflow using Java SDK", + }); + + // Enable durable execution via escape hatch + const cfnFn = fn.node.defaultChild as lambda.CfnFunction; + cfnFn.addOverride("Properties.DurableConfig", { + ExecutionTimeout: 3600, + RetentionPeriodInDays: 7, + }); + + // Durable execution permissions via AWS managed policy + fn.role!.addManagedPolicy( + iam.ManagedPolicy.fromAwsManagedPolicyName( + "service-role/AWSLambdaBasicDurableExecutionRolePolicy" + ) + ); + + // Version and alias via L1 to avoid CDK version property validation + const version = new lambda.CfnVersion(this, "FnVersion", { + functionName: fn.functionName, + description: "Durable execution version", + }); + + const alias = new lambda.CfnAlias(this, "ProdAlias", { + functionName: fn.functionName, + functionVersion: version.attrVersion, + name: "prod", + }); + + new cdk.CfnOutput(this, "FunctionName", { value: fn.functionName }); + new cdk.CfnOutput(this, "FunctionAliasArn", { + value: alias.ref, + description: "Use this ARN to invoke the durable function", + }); + } +} diff --git a/lambda-durable-execution-java-cdk/package.json b/lambda-durable-execution-java-cdk/package.json new file mode 100644 index 000000000..6d7b9a917 --- /dev/null +++ b/lambda-durable-execution-java-cdk/package.json @@ -0,0 +1,20 @@ +{ + "name": "lambda-durable-execution-java-cdk", + "version": "1.0.0", + "bin": { + "app": "bin/app.ts" + }, + "scripts": { + "build": "tsc", + "cdk": "cdk" + }, + "dependencies": { + "aws-cdk-lib": "2.180.0", + "constructs": "10.4.2" + }, + "devDependencies": { + "@types/node": "^22.0.0", + "ts-node": "^10.9.0", + "typescript": "~5.7.0" + } +} diff --git a/lambda-durable-execution-java-cdk/src/Dockerfile b/lambda-durable-execution-java-cdk/src/Dockerfile new file mode 100644 index 000000000..f1d792c40 --- /dev/null +++ b/lambda-durable-execution-java-cdk/src/Dockerfile @@ -0,0 +1,5 @@ +FROM maven:3.9-amazoncorretto-17 AS build +WORKDIR /app +COPY pom.xml . +COPY main/ src/main/ +RUN mvn clean package -DskipTests diff --git a/lambda-durable-execution-java-cdk/src/main/java/com/example/OrderProcessor.java b/lambda-durable-execution-java-cdk/src/main/java/com/example/OrderProcessor.java new file mode 100644 index 000000000..61fc0e1ec --- /dev/null +++ b/lambda-durable-execution-java-cdk/src/main/java/com/example/OrderProcessor.java @@ -0,0 +1,63 @@ +package com.example; + +import software.amazon.lambda.durable.DurableContext; +import software.amazon.lambda.durable.DurableHandler; + +import java.time.Duration; +import java.util.Map; +import java.util.UUID; + +/** + * Durable order processing workflow that demonstrates automatic checkpointing, + * wait operations, and multi-step orchestration using the Java Durable Execution SDK. + * + * Each step is checkpointed — if the function is interrupted, it resumes from + * the last completed step without re-executing previous work. + */ +public class OrderProcessor extends DurableHandler, Map> { + + @Override + public Map handleRequest(Map input, DurableContext ctx) { + String orderId = (String) input.getOrDefault("orderId", UUID.randomUUID().toString()); + double amount = ((Number) input.getOrDefault("amount", 99.99)).doubleValue(); + + // Step 1: Validate order + String validation = ctx.step("validate-order", String.class, stepCtx -> { + System.out.println("Validating order " + orderId); + if (amount <= 0) { + throw new IllegalArgumentException("Invalid order amount: " + amount); + } + return "VALIDATED"; + }); + + // Step 2: Reserve inventory + String reservationId = ctx.step("reserve-inventory", String.class, stepCtx -> { + System.out.println("Reserving inventory for order " + orderId); + return "RES-" + UUID.randomUUID().toString().substring(0, 8); + }); + + // Step 3: Process payment + String paymentId = ctx.step("process-payment", String.class, stepCtx -> { + System.out.println("Processing payment of $" + amount + " for order " + orderId); + return "PAY-" + UUID.randomUUID().toString().substring(0, 8); + }); + + // Wait for warehouse processing (no compute charges during wait) + ctx.wait("warehouse-processing", Duration.ofSeconds(5)); + + // Step 4: Confirm shipment + String trackingNumber = ctx.step("confirm-shipment", String.class, stepCtx -> { + System.out.println("Confirming shipment for order " + orderId); + return "TRACK-" + UUID.randomUUID().toString().substring(0, 8); + }); + + return Map.of( + "orderId", orderId, + "status", "COMPLETED", + "validation", validation, + "reservationId", reservationId, + "paymentId", paymentId, + "trackingNumber", trackingNumber + ); + } +} diff --git a/lambda-durable-execution-java-cdk/src/pom.xml b/lambda-durable-execution-java-cdk/src/pom.xml new file mode 100644 index 000000000..2e2955378 --- /dev/null +++ b/lambda-durable-execution-java-cdk/src/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + + com.example + lambda-durable-execution-java + 1.0.0 + jar + + + 17 + 17 + UTF-8 + + + + + software.amazon.lambda.durable + aws-durable-execution-sdk-java + 1.0.1 + + + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.6.0 + + + package + + shade + + + + + + + diff --git a/lambda-durable-execution-java-cdk/tsconfig.json b/lambda-durable-execution-java-cdk/tsconfig.json new file mode 100644 index 000000000..15e54de36 --- /dev/null +++ b/lambda-durable-execution-java-cdk/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "target": "ES2020", + "module": "commonjs", + "lib": ["es2020"], + "declaration": true, + "strict": true, + "noImplicitAny": true, + "strictNullChecks": true, + "noImplicitThis": true, + "alwaysStrict": true, + "outDir": "build", + "rootDir": ".", + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "resolveJsonModule": true, + "esModuleInterop": true + }, + "exclude": ["node_modules", "build", "src"] +}