
Answer-first summary for fast verification
Answer: Move the database connection out of the handler
Move the database connection out of the handler Here at every Lambda function execution, the database connection handler will be created, and then closed. These connections steps are expensive in terms of time, and thus should be moved out of the handler function so that they are kept in the function execution context, and re-used across function calls. This is what the function should look like in the end: mysql = mysqlclient.connect() def handler(event, context): data = event['data'] mysql.execute(f"INSERT INTO foo (bar) VALUES (${data});") return Incorrect options: Upgrade the MySQL instance type - The bottleneck here is the MySQL connection object, not the MySQL instance itself. Change the runtime to Node.js - Re-writing the function in another runtime won't improve the performance. Increase the Lambda function RAM - While this may help speed-up the Lambda function, as increasing the RAM also increases the CPU allocated to your function, it only makes sense if RAM or CPU is a critical factor in the Lambda function performance. Here, the connection object is at fault.
Author: LeetQuiz Editorial Team
Ultimate access to all questions.
A developer has deployed an AWS Lambda function written in Python, which inserts data into an RDS MySQL database. The function code is as follows:
def handler(event, context):
mysql = mysqlclient.connect()
data = event['data']
mysql.execute(f"INSERT INTO foo (bar) VALUES (${data});")
mysql.close()
return
def handler(event, context):
mysql = mysqlclient.connect()
data = event['data']
mysql.execute(f"INSERT INTO foo (bar) VALUES (${data});")
mysql.close()
return
Upon testing the function, it has been observed that the initial execution takes 2 seconds to complete, whereas the subsequent executions take 1.9 seconds.
What strategies or modifications can be employed to enhance the execution time of this Lambda function?
A
Increase the Lambda function RAM
B
Change the runtime to Node.js
C
Upgrade the MySQL instance type
D
Move the database connection out of the handler
No comments yet.