Node.js is faster than Go

CJ Hewett
3 min readApr 1, 2024

…when you write bad code. A lesson in connection pooling, and not simply copying and pasting code you find on the internet.

I was performance testing APIs I’d made in different frameworks against a Timescale Postgres DB in a Docker container locally. These were simple APIs that searched for a record with over 100 millions records.

I found Go was getting around 2000 requests per second. I thought this was good until I saw NestJS and Bun were getting 3000rps. This couldn’t be right since Go is meant to be far superior 💪.

I found the issue was connection pooling, and not setting limits on max and idle connections. This is something that not many tutorials mention about the Go SQL package. However, this article describes it well:

After setting limits, I started to get 2–3x more RPS for Go.

When searching for how to connect to a database, I found a lot of examples of something similar to the following:

func NewPostgresStore() (*PostgresStore, error) {
godotenv.Load()
connStr := fmt.Sprintf("host=%s port=%s user=%s dbname=%s password=%s sslmode=%s",
os.Getenv("HOST"), os.Getenv("PORT"), os.Getenv("DBUSER"), os.Getenv("DBNAME"), os.Getenv("DBPASS"), os.Getenv("SSLMODE"))

db, err := sql.Open("postgres", connStr)
if err != nil {
return nil, err
}

db.SetMaxOpenConns(20)
db.SetMaxIdleConns(20)

// defer db.Close()

if err := db.Ping(); err != nil {
return nil, err
}

return &PostgresStore {
db: db,
}, nil
}

But it was rare to find examples of defining connection pooling, this is as easy as setting the following right after opening the connection:

// Open the db connection
db, err := sql.Open("postgres", connStr)
if err != nil {
return nil, err
}

// Set connection limits for connection pooling
db.SetMaxOpenConns(20)
db.SetMaxIdleConns(20)

Play around these values to find what works for you and your database, performance wise.

Cheers

Performance testing…

Go without connection pooling

Go with connection pooling

Nodejs with Nestjs

Bun

--

--

CJ Hewett

🛹 Skateboarder. 🏂 Snowboarder. 🏄 Websurfer. I write monthly* about Cloud/DevOps/IoT. AWS Certified DevOps Engineer and Terraform Associate