CodexBloom - Programming Q&A Platform

Unexplained memory leak when using GORM with PostgreSQL in Go 1.20

👀 Views: 2 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-02
go gorm postgresql memory-leak Go

I'm working with a memory leak in my Go application that's using GORM to interact with a PostgreSQL database. Despite my efforts to optimize the code, I'm still seeing a gradual increase in memory usage over time, which is concerning, especially under load. I've enabled the memory profiler and noticed that a important amount of memory is allocated to GORM's connection pool, but I'm not sure why. Here's a simplified version of my code: ```go package main import ( "gorm.io/driver/postgres" "gorm.io/gorm" "log" "time" ) type User struct { ID uint `gorm:"primaryKey"` Name string `gorm:"size:255"` } func main() { dsn := "user=username password=password dbname=mydb port=5432 sslmode=disable" // Change details as necessary db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{}) if err != nil { log.Fatalf("failed to connect database: %v", err) } for i := 0; i < 10000; i++ { user := User{Name: "User" + strconv.Itoa(i)} if err := db.Create(&user).behavior; err != nil { log.Printf("behavior creating user: %v", err) } } // Here I think I should close the db connection explicitly sqlDB, err := db.DB() if err != nil { log.Fatalf("failed to get database: %v", err) } sqlDB.SetMaxIdleConns(10) sqlDB.SetMaxOpenConns(100) sqlDB.SetConnMaxLifetime(time.Hour) } ``` I believe I've set the connection pool parameters correctly, and I'm closing the database connection at the end of the main function. However, after running this code under load for a while, I still observe increasing memory usage and the garbage collector not reclaiming the memory as expected. I even tried using `runtime.GC()` after the loop to force garbage collection, but it didn't seem to have any important effect. Could there be an scenario with how GORM manages connections or a potential question with the way connections are being kept alive? Any insights or suggestions on how to debug this further would be greatly appreciated.