Reduce DynamoDB latency from Java Lambda
According to this post from an AWS employee on the AWS forums, construction of the AmazonDynamoDB
object is expensive. Moving construction (back) into the static initializer combined with a little extra memory (=CPU) allocation basically sorts the problem.
Data from the logs still shows that each of the 2 slow steps identified above takes about half the time. Therefore, presumably both construction and first use of the AmazonDynamoDB
objects are slow.
Obviously this doesn't help with the first request which still takes the same time as in the question. However, once the lambda is warmed, subsequent requests take ~15ms (well below the minimum billing threshold of 100ms). Addressing the first request problem is well understood - e.g. by using CloudWatch Events to schedule a regular call to the lambda to keep it warm.
Edit in 2020: You can also use Provisioned Currency to deal with the cold start problem.
(isn't a answer, but i hope it helps someone else) I have made the updates posted here and i besides them, i had to made a "dummy" query operation on dynamoDb (to open a connection with it), just in case of if help someone else, my code is as follows:
class MyFunctionHandler : RequestHandler<Map<String, Any>, ApiGatewayResponse> {
//var dbClient: AmazonDynamoDB = AmazonDynamoDBClientBuilder.defaultClient()
var dbClient: AmazonDynamoDB = AmazonDynamoDBClientBuilder
.standard().withRegion("sa-east-1").build()
override fun handleRequest(input: Map<String, Any>, context: Context): ApiGatewayResponse {
LOG.info("received input: $input")
input["wakeup"]?.let {
if (it == true) {
with(EmpresaRepository(dbClient)) {
LOG.info("### Connection was not stablished at this point")
someDynamoQueryHere("dummyParameter")
LOG.info("### The Connection was opened and will keep alived for 1 minute")
}
return buildResponseForWakeUpReq(input)
}
}
val param = input["queryStringParameters"]?.toString()
...
The subsequent operations that will open the dynamoDb connection will occurs in terms of milliseconds!