简体   繁体   中英

Database connection hanging on AWS Lambda

I am trying to do basic db connection in AWS Lambda with Go, and for some reason, it got stuck at db.prepare() and no log is presented in cloudwatch.

func Handler(request Request) (Response, error) {

    db, err := sql.Open("mysql", dbUsername+":"+dbPassword+"@tcp("+dbURL+":"+dbPort+")/"+dbName)
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()
    stmt, err := db.Prepare("SELECT id, password FROM package_passwords WHERE password = ?")
    return Response{
        Message: "rows",
        Ok:      false,
    }, nil
}

weird thing is that the code above stuck at least more than 5 second in AWS Lambda while it works fine in plain go run/ go build.

It's probably the AWS security groups

The lambda tries to connect but the security groups time it out as they block it forever

Attach the AWSLambdaVPCAccessExecutionRole policy to your lambda and ensure the Lambda is in a VPC. Check the database security groups allow access from the VPC

There are some more pointers in this question Allow AWS Lambda to access RDS Database

If it is a RDS operation, I think it is getting timeout. The default timeout of a lambda function is 6 seconds and therefore it is getting timeout before the operation finishes with RDS. To avoid this you do not have to increase the timeout. Instead of that you can make "callBackWaitsForEmptyEventLoop" false as your first line of code in lambda function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM