Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Write a minimal AWS Lambda handler in Java that receives an API Gateway event and returns a JSON response. Explain where you would create SDK clients and database connections, and what affects cold start time for Java functions.

A minimal handler implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> from aws-lambda-java-core and aws-lambda-java-events, and returns a response object with a status code, a JSON content type and a body. SDK clients and other expensive objects belong in static fields or the constructor, so they are created once per execution environment and reused by every invocation it serves. Cold start time comes from starting the JVM, loading classes and running that initialization, so it grows with framework size and dependencies, and shrinks with more memory, a smaller package and less startup scanning.

Why this question is asked

Java on AWS Lambda works well, but it punishes code written as if every request started fresh, and it punishes heavy startup. Interviewers ask for a minimal handler to check that we know the programming model: which interface we implement, what the event looks like, and where state lives between invocations. The follow-up about clients and cold starts separates people who have run Java functions in production from people who have only read about them. In this answer, we will recap how Lambda runs a Java function, write the handler step by step, see where to create clients and database connections, and then look at what makes cold starts slow and how to shorten them.

1A Quick Recap of How Lambda Runs Java

Lambda runs our code inside an execution environment, a small isolated micro VM with the Java runtime, our jar and a fixed amount of memory. When a request arrives and no environment is free, Lambda creates one. That creation is the cold start: it starts the JVM, loads our handler class, runs static initializers and the constructor, and only then calls our handler method. This is called the init phase.

After the invocation finishes, Lambda keeps the environment around for a while and sends it later requests. Those are warm invocations: the JVM is already running, our class is loaded and our static fields still hold their values. One environment handles one request at a time; if ten requests arrive at once, Lambda runs ten environments.

Step throughCold start, then a warm invocation
API GatewayLambda serviceEnvironment
request 1
start JVM, load classes
static init: create clients
invoke handleRequest
response 1
200 OK
request 2
invoke handleRequest (warm)
response 2

9 messages in order. Play them, or step through them one at a time.

Only the first request pays for JVM start and static initialization.

2Writing the Handler

We need two small libraries: aws-lambda-java-core, which defines the RequestHandler interface and the Context object, and aws-lambda-java-events, which has typed classes for events such as the API Gateway proxy event. The handler takes the event and returns the response that API Gateway turns into an HTTP reply.

Java
public class GreetingHandler
implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
// created once per execution environment, reused by every warm invocation
private static final ObjectMapper JSON = new ObjectMapper();
private static final DynamoDbClient DYNAMO = DynamoDbClient.builder()
.httpClient(UrlConnectionHttpClient.create()) // light HTTP client, faster to start
.build();
@Override
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent event, Context ctx) {
Map<String, String> query = event.getQueryStringParameters(); // null when there is no query string
String name = query != null ? query.getOrDefault("name", "world") : "world";
try {
String body = JSON.writeValueAsString(Map.of("message", "Hello, " + name));
return new APIGatewayProxyResponseEvent()
.withStatusCode(200)
.withHeaders(Map.of("Content-Type", "application/json"))
.withBody(body); // {"message":"Hello, Ana"}
} catch (JsonProcessingException e) {
ctx.getLogger().log("serialization failed: " + e.getMessage());
return new APIGatewayProxyResponseEvent().withStatusCode(500).withBody("{\"error\":\"internal\"}");
}
}
}

Notice three details. The query string map is null, not empty, when the request has no query string, which is a classic NullPointerException in Lambda handlers. The body is a string, because API Gateway expects the JSON already serialized. And the content type header tells the client what the body is; without it, some clients treat it as plain text. In the function configuration, the handler is set to the class name, for example com.acme.GreetingHandler::handleRequest.

3Where to Create SDK Clients and Database Connections

An SDK client is expensive to create: it loads many classes, builds an HTTP connection pool and resolves credentials. If we built it inside handleRequest, every invocation would pay that cost, often 100 to 300 ms on a small function. Putting it in a static field or the constructor means it is built once during the init phase and reused, and its connection pool keeps TCP and TLS connections open between calls.

Database connections follow the same idea with one catch. A connection opened during init may sit idle while the environment is frozen between invocations, and the database or a NAT gateway may drop it. So we create the pool or connection lazily on first use, keep it tiny, one connection per environment, because each environment serves one request at a time, and validate it before use. And we only open connections the function actually needs: a function that writes to the database on one path out of ten should not connect during init for all of them.

Java
private static HikariDataSource dataSource; // shared by warm invocations
private static synchronized DataSource db() {
if (dataSource == null) {
HikariConfig cfg = new HikariConfig();
cfg.setJdbcUrl(System.getenv("DB_URL"));
cfg.setMaximumPoolSize(1); // one request at a time per environment
cfg.setMaxLifetime(300_000); // 5 minutes: replace connections before idle drops
dataSource = new HikariDataSource(cfg); // created on the first call that needs it
}
return dataSource;
}

With many concurrent environments, even one connection each can add up to hundreds of connections, so for relational databases a connection proxy such as RDS Proxy in front of the database is the usual next step.

4What Makes a Java Cold Start Slow

The cold start of a Java function is the sum of three parts. Starting the JVM itself takes a fraction of a second. Loading classes takes longer the more classes we touch: a plain handler with the SDK loads a few thousand, a full Spring Boot application loads many more. Then our initialization runs, and frameworks that scan the classpath for annotations and wire beans through reflection add the most time. So a bare handler may start in well under a second, while the same logic inside a large framework can take several seconds.

Memory matters in a surprising way. In Lambda, the CPU share grows with the memory setting; at about 1,769 MB a function gets the equivalent of one full vCPU. Class loading and JIT compilation are CPU-bound, so moving from 512 MB to 1,769 MB often shortens the init phase noticeably, and because we pay per millisecond, it can cost about the same overall.

Levers on Java cold start
LeverWhy it helps
Smaller deployment packagefewer classes to find and load
Light HTTP client (URL connection)less to initialize than Netty or Apache
No reflection-heavy scanningavoids classpath walks at startup
More memorymore CPU for class loading and JIT
Lazy connectionsdo not pay for what this call does not use
SnapStartrestores an initialized snapshot instead of starting again
Measure the Init Duration in the REPORT log line before and after each change.

5Follow-up questions

What does execution environment reuse mean for static state?

Everything in static fields, and files in /tmp, survives from one invocation to the next in the same environment, but not across environments. That is good for clients, caches and connection pools, which is why we put them there. It is dangerous for per-request data: if we store the current user or a request id in a static field, the next request in that environment may see it. And we cannot rely on reuse either, because Lambda can create a new environment or discard an old one at any time, so a cache must be just a cache and never the only copy of data.

Why use the URL connection HTTP client instead of the default?

The default synchronous client in SDK 2.x is the Apache-based one, which is solid but loads more classes. The URL connection client uses the JDK's built-in HTTP support and starts faster, which suits functions that make a few calls per invocation. For high-throughput functions, the Apache or CRT clients may perform better, so we measure both.

Should the handler catch all exceptions?

For API Gateway proxy integrations, yes at the top level, so we can return a meaningful status code such as 400 or 500 with a JSON body instead of letting API Gateway reply with a generic 502. We log the error with the request id from the Context so we can find it in CloudWatch.

6Conclusion

In this answer, we wrote a minimal API Gateway handler with RequestHandler and the typed event classes, returning a status code, a JSON content type and a serialized body. We saw that clients belong in static fields or the constructor so warm invocations reuse them, while database connections should be lazy, tiny and validated. And we saw that a Java cold start is JVM start plus class loading plus our initialization, which more memory, a smaller package and less scanning all shorten.

What to say in the interviewAbout 90 seconds aloud

Open with

I would implement RequestHandler with APIGatewayProxyRequestEvent as input and APIGatewayProxyResponseEvent as output, from aws-lambda-java-core and aws-lambda-java-events. In handleRequest I read the query parameters, remembering that the map is null when there are none, build the result, serialize it to a JSON string with Jackson, and return a response with status code 200, a Content-Type of application/json and the string as body.

Then, if they want more

Errors are caught at the top and returned as a 500 with a small JSON body and a log line with the request id.

For SDK clients I use static final fields or the constructor, because Lambda reuses the execution environment between invocations, so the client, its connection pool and its credentials are created once during the init phase and not on every request.

Database connections I create lazily on first use, with a pool of one, since an environment handles one request at a time, and with RDS Proxy in front if concurrency is high. Cold start is starting the JVM, loading classes and running initialization. Big frameworks, reflection-based scanning and many dependencies make it slower.

To shorten it I keep the package small, use a light HTTP client, avoid opening connections I might not need, and give the function more memory, because Lambda gives more CPU with more memory and class loading is CPU-bound. I measure the Init Duration from the REPORT log line before and after each change.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
AWS documentation
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write a minimal AWS Lambda handler in Java that receives an API Gateway event and...": https://scrivio-interview-library.netlify.app/spring-boot/aws/985e01eed7/