In this example we are going to use an AWS Lambda function to insert data into MySQL database. The main point here is to prove that you don't have to do anything special in order to re-use same connection (read here) but the critical point is, do not manually close connection in code.


Prerequisite


Create a database called lambda and a table request.


Lambda


My MySQL server is running in host OS as a docker container, hence using docker DSN below.


package main

import (
"context"
"database/sql"
"log"
"time"

"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-lambda-go/lambdacontext"

_ "github.com/go-sql-driver/mysql"
)

var db *sql.DB

func init() {
var err error
db, err = sql.Open("mysql", "root:root@tcp(host.docker.internal:3306)/lambda")
if err != nil {
log.Fatalln(err)
}

// Do not use this!
// defer db.Close()
}

func main() {
lambda.Start(handle)
}

func handle(ctx context.Context) error {
lc, _ := lambdacontext.FromContext(ctx)

qry := `INSERT INTO request (uuid, created_at) VALUES (?, ?)`

if _, err := db.ExecContext(ctx, qry, lc.AwsRequestID, time.Now().UTC()); err != nil {
return err
}

return nil
}

Setup


$ GOOS=linux CGO_ENABLED=0 go build -ldflags "-s -w" -o main main.go

zip lambda.zip main

aws --profile localstack --endpoint-url http://localhost:4566 lambda create-function \
--function-name test-lambda \
--handler main \
--runtime go1.x \
--role test-role \
--zip-file fileb://lambda.zip

Test


You can use queries below in MySQL server to watch changes. Results should be similar to what you see below.


mysql> SHOW PROCESSLIST;
+-----+------+------------------+----------+---------+------+----------+------------------+
| Id | User | Host | db | Command | Time | State | Info |
+-----+------+------------------+----------+---------+------+----------+------------------+
| 4 | root | 172.23.0.1:55642 | lambda | Sleep | 11 | | NULL |
| 5 | root | 172.23.0.1:55646 | NULL | Sleep | 21 | | NULL |
| 305 | root | localhost | lambda | Query | 0 | starting | SHOW PROCESSLIST |
+-----+------+------------------+----------+---------+------+----------+------------------+
4 rows in set (0.00 sec)

mysql> SHOW STATUS WHERE `variable_name` = 'Max_used_connections';
+----------------------+-------+
| Variable_name | Value |
+----------------------+-------+
| Max_used_connections | 8 |
+----------------------+-------+
1 row in set (0.01 sec)

mysql> SHOW STATUS WHERE `variable_name` = 'Threads_connected';
+-------------------+-------+
| Variable_name | Value |
+-------------------+-------+
| Threads_connected | 4 |
+-------------------+-------+
1 row in set (0.01 sec)

This will run Lambda function 1000 times. While running watch query results above.


$ for ((i=1;i<=1000;i++)); do aws --profile localstack --endpoint-url http://localhost:4566 lambda invoke --function-name test-lambda lambda.json; done