How To Make Your Database Connection Deadlocked in Golang

Table of Contents

Originally published on IDN Media Engineering on July 30, 2024.

Photo by TopSphere Media on Unsplash

Photo by TopSphere Media on Unsplash

Prologue

What if every request for your API will open a new database connection and closed the connection after request was finished? In small application maybe it’s okay to do that, but when your API scale up and handle so many request, open and close the connection on every request will be expensive. One of the solution to handle this, is using database connection pool. Database connection pool is like a “cache” of all database connection, so for every request it doesn’t need to create new connection, just use the available connection. The connection can be reused in the future database operation. For example, on first request in API it will using database connection number 1, second until fourth request will using database connection number 2–4, then on fifth request it will used database connection number 1, no need to create new connection for every request. Golang has already provide built-in database connection pool which can be used to keep connection open for a while and not open/close database connection on every request.

How Database Connection Pool Work In Golang?

For every request it will go through the connection pool to check if there are available connection. There are 4 option for connection pool if a request need a database connection.

  1. If connection pool is empty, connection pool will create a new database connection.
  2. If there are available connection, the request can directly using the connection.
  3. If all of the connection pool already used by another request and maximum open connection limit is not fulfilled, connection pool will create a new database connection.
  4. If all of the connection pool already used and maximum open connection limit is fulfilled, then a request must wait until connection is available on the pool.
database connection pool

database connection pool

Problem Found With Concurrent Request

While working on an API where I used Golang database connection pool and MySQL Database, I found a problem when it has concurrent request. In my code, my handler function call GetListFollows function to get list following users by query from database. After that, there is another query inside rows.Next() by calling function GetUserDetail. Why it’s different function to get user detail? Because query to get user detail also used by another endpoint, so i make it a different function to reduced duplicate code.

func Handler(w http.ResponseWriter, r *http.Request) {
	userID, _ := strconv.Atoi(r.Header.Get("x-user-id"))

	users, err := GetListFollows(r.Context(), userID)
	if err != nil {
		resp := &Response{
			Status:  http.StatusInternalServerError,
			Message: "ERROR",
		}
		bytes, _ := json.Marshal(resp)
		w.WriteHeader(http.StatusInternalServerError)
		w.Write(bytes)
		return
	}

	resp := &Response{
		Status:  http.StatusOK,
		Message: "SUCCESS",
		Data:    users,
	}
	bytes, _ := json.Marshal(resp)
	w.WriteHeader(http.StatusOK)
	w.Write(bytes)
}

func GetListFollows(ctx context.Context, id int) ([]*User, error) {
	users := []*User{}
	query := "SELECT source_id, target_id FROM follows where source_id = ?"
	rows, err := sqlDB.QueryContext(ctx, query, id)
	if err != nil {
		if err == sql.ErrNoRows {
			return nil, nil
		}
		return nil, err
	}
	defer rows.Close()

	for rows.Next() {
		follow := &Follow{}
		if err := rows.Scan(&follow.SourceID, &follow.TargetID); err != nil {
			return nil, err
		}

		user, err := GetUserDetail(ctx, follow.TargetID)
		if err != nil {
			return nil, err
		}

		users = append(users, user)
	}

	return users, nil
}

func GetUserDetail(ctx context.Context, id int) (*User, error) {
	user := &User{}
	query := "SELECT id, name, username, bio FROM users WHERE id = ?"
	row := sqlDB.QueryRowContext(ctx, query, id)
	err := row.Scan(&user.ID, &user.Name, &user.UserName, &user.Bio)
	if err != nil {
		if err == sql.ErrNoRows {
			return nil, nil
		}
		return nil, err
	}

	return user, nil
}

I try to make one request to my app and not found anything strange. But, when i try load test using hey with number of request is 50 and number of workers is 25, something strange is happen. All of my request was timeout.

old code hey load test, with n=50, c=25

old code hey load test, with n=50, c=25

Then i try to make another load test with lower configuration than before (number of request is 5 and number of workers is 5), and all of request was successful.

old code hey load test, with n=5, c=5

old code hey load test, with n=5, c=5

Why All My Request Are Timeout?

Because database connection is deadlocked

I’m curious why my request is always timeout on my old code, whereas the number of query is same in old and new code. After googling and looking into Golang source code i found that the problem because the database connection is deadlocked. In API, I use database connection pool with configuration Maximum Open Connection is 10.

sqlDB.SetMaxOpenConns(10)

Then i make a concurrent request more than 10 to my API, and then all of my request are timeout because the database connection are deadlocked. Here is why the database connection are deadlocked :

  1. First 10 request will take one connection for each to running first query to get list following user, then each request need another connection because inside rows.Next() there are second query to get user detail.
  2. To running the second query (get user detail), it will take a look inside connection pool and all of the connection is not available because all of connection already used, so it will wait until a connection is available.
  3. All request will wait for each other to finished, but it’s deadlocked because neither of the connection will be released back to the pool until rows.Next() is finished or error.

notes : request number 11 until end also timeout, because it cannot run the first query because all of the database connection is not available in the pool

deadlock condition

deadlock condition

How to fix this

After some hours try to debugging my code, i found two solution that will solve my problem

First Solution
In this solution, i just adjust sql.DB Max Open Connections

sqlDB.SetMaxOpenConns(100)

It will works if the number of concurrent request less than Max Open Connections, if more than Max Open Connection the error is still exists.

Second Solution
I try to remove the query inside rows.Next() and move calling GetUserDetail function into the handler. Then, i’m running load test again with configuration number of requests is 100 and number of workers is 50, then all of my request are success. This approach will work because 1 connection only used to run 1 query, and after query is finished the connection will be back to the pool.

func HandlerFix(w http.ResponseWriter, r *http.Request) {
	userID, _ := strconv.Atoi(r.Header.Get("x-user-id"))

	follows, err := GetListFollowsFix(r.Context(), userID)
	if err != nil {
		resp := &Response{
			Status:  http.StatusInternalServerError,
			Message: "ERROR",
		}
		bytes, _ := json.Marshal(resp)
		w.WriteHeader(http.StatusInternalServerError)
		w.Write(bytes)
		return
	}

	users := []*User{}

	for _, follow := range follows {
		user, err := GetUserDetail(r.Context(), follow.TargetID)
		if err != nil {
			resp := &Response{
				Status:  http.StatusInternalServerError,
				Message: "ERROR",
			}
			bytes, _ := json.Marshal(resp)
			w.WriteHeader(http.StatusInternalServerError)
			w.Write(bytes)
			return
		}

		users = append(users, user)
	}

	resp := &Response{
		Status:  http.StatusOK,
		Message: "SUCCESS",
		Data:    users,
	}
	bytes, _ := json.Marshal(resp)
	w.WriteHeader(http.StatusOK)
	w.Write(bytes)
}

func GetListFollowsFix(ctx context.Context, id int) ([]*Follow, error) {
	follows := []*Follow{}
	query := "SELECT source_id, target_id FROM follows where source_id = ?"
	rows, err := sqlDB.QueryContext(ctx, query, id)
	if err != nil {
		if err == sql.ErrNoRows {
			return nil, nil
		}
		return nil, err
	}
	defer rows.Close()

	for rows.Next() {
		follow := &Follow{}
		if err := rows.Scan(&follow.SourceID, &follow.TargetID); err != nil {
			return nil, err
		}

		follows = append(follows, follow)
	}

	return follows, nil
}

fix code

fix code hey load test, with n=100, c=50

fix code hey load test, with n=100, c=50

Epilogue

It’s a a new experience for me to know that database connection can be deadlocked sometimes. I also found in golang documentation, database connection pool deadlock can be found sometimes

https://go.dev/doc/database/manage-connections

https://go.dev/doc/database/manage-connections

In my use case, the deadlocked connection exists because rows.Next() hold a connection until looping is finished (return false), and inside rows.Next() there are another query but there are no available connection until rows.Next() is finished.

How to prevent it?

So there is some solution to prevent deadlocked database connection in connection pool:

  1. Increase maximum open connection configuration in Golang (notes: database has also has maximum connection, if you set too high maybe another client cannot connect to the database)
  2. Remove calling query inside rows.Next(), because rows.Next() hold a connection until it returns false (looping is finished).

Full Code

For full code can be found in here: https://github.com/idnandre/connection-pool-deadlock-example

Closing

That’s it for my story about database connection deadlocked. Maybe there is another use case about deadlocked database connection, but so far i just only found this use case on my working experience. If you have another experience about deadlocked database connection or there are something i’m missing from my story, let me know in the comment :)

Thank you.

Reference