AWS Lambda Explained with a Simple Java Example

AWS Lambda is a fully serverless compute service that lets you run code without provisioning or managing servers. You are billed only for the time your function actually runs—unlike EC2, where you pay even when the server is idle. Lambda automatically scales, executes only when triggered, and shuts down after execution.


What AWS Lambda Does

  • Runs small pieces of code called functions written in Java, Python, Node.js, Ruby, and more.
  • No server, OS, CPU, RAM, or patching management—AWS handles everything.
  • Billed only per invocation and execution time.
  • Ideal for event-driven, bursty, or low-traffic workloads.

How AWS Lambda is Triggered

A Lambda function does nothing until a trigger fires. Common triggers include:

  • S3 — Run code when files are uploaded or deleted (e.g., image resizing).
  • SQS / SNS — Process messages as they arrive.
  • API Gateway — Build serverless REST APIs where each HTTP call invokes Lambda.
  • EventBridge / CloudWatch — Cron jobs like hourly cleanup or daily reports.

The Lambda console also provides built-in test events, allowing you to run your function instantly without configuring real triggers.


Creating and Testing a Lambda from the Console

In the AWS console, you can create a simple Lambda function using Node.js or any runtime. For example:


// index.js - Example Node.js Lambda function
exports.handler = async (event) => {
    console.log("Lambda triggered");
    return { message: "Function executed successfully" };
};

The console allows you to edit code inline, deploy instantly, and run test events. Each invocation’s logs appear inside CloudWatch Logs, confirming successful execution.


Triggering Lambda from S3

A simple demonstration is connecting Lambda to an S3 bucket:

  • Create an S3 bucket in the same AWS region.
  • Configure the bucket as a Lambda trigger.
  • Choose events such as ObjectCreated.

Whenever a file is uploaded, S3 automatically executes the Lambda function. The logs in CloudWatch confirm the trigger with messages like “Lambda triggered by S3 upload”.


Running a Java Function on AWS Lambda

Lambda supports Java 11 and Java 17 runtimes. To deploy Java code, you create a simple Maven project containing a handler class.

Java Handler Example


package org.example;

public class Hello {

    public String handleRequest(String input) {
        System.out.println("Java Lambda executed");
        return "Hello from Java Lambda! Input: " + input;
    }
}

Project Structure:


src
 └── main
     └── java
         └── org
             └── example
                 └── Hello.java

Maven pom.xml (minimal for Lambda)


<project xmlns="http://maven.apache.org/POM/4.0.0">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.example</groupId>
    <artifactId>lambda-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-lambda-java-core</artifactId>
            <version>1.2.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.3.0</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals><goal>shade</goal></goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

Build the JAR:


mvn clean package

Upload the generated JAR to AWS Lambda and set the handler as:


org.example.Hello::handleRequest

Now run a test event in the Lambda console—the logs will show:
Java Lambda executed


Common AWS Lambda Use Cases

  • Image/video processing (resize, compress, watermark).
  • Real-time data stream processing (Kinesis, DynamoDB Streams).
  • Serverless REST APIs using API Gateway + Lambda.
  • Automated event-driven workflows (S3, DynamoDB, CloudWatch).
  • Scheduled tasks (cron jobs via EventBridge).

Limitations You Should Know

  • Cold starts: Idle functions take longer on the first request.
  • Max execution time: 15 minutes per invocation.
  • Resource limits: Memory and temporary storage have predefined limits.
  • Debugging: Harder compared to traditional server apps.

Conclusion

AWS Lambda is a powerful and cost-efficient way for Java developers to build event-driven, scalable applications without managing servers. Combined with S3, API Gateway, EventBridge, and SQS, Lambda enables fully serverless architectures that scale automatically and cost nothing when idle.

Comments

Popular posts from this blog

Spring Boot on AWS EC2: Upload to S3 Securely Using IAM Role

Java Streams Intermediate Operations Explained with Examples

ConcurrentHashMap vs Synchronized HashMap in Java