session/mysql for beego/v2 inappropriately creates a new *sql.DB for every session
Author: friedrichsenmCreated Jul 22, 2026Updated Jul 22, 2026
Here's an example from sess_mysql.go
// SessionRead get mysql session by sid
func (mp *Provider) SessionRead(ctx context.Context, sid string) (session.Store, error) {
c := mp.connectInit()
row := c.QueryRow("select session_data from "+TableName+" where session_key=?", sid)
var sessiondata []byte
err := row.Scan(&sessiondata)
if err == sql.ErrNoRows {
c.Exec("insert into "+TableName+"(`session_key`,`session_data`,`session_expiry`) values(?,?,?)",
sid, "", time.Now().Unix())
} else if err != nil {
return nil, err
}
var kv map[interface{}]interface{}
if len(sessiondata) == 0 {
kv = make(map[interface{}]interface{})
} else {
kv, err = session.DecodeGob(sessiondata)
if err != nil {
return nil, err
}
}
rs := &SessionStore{c: c, sid: sid, values: kv}
return rs, nil
}Inside mp.connectInit() a new *sql.DB is being created. *sql.DB is supposed to be thread safe, so instead of creating one per session you are querying from the provider. You should create a single *sql.DB in the provider and use connections from it. In my beego app I'm noticing random crashes and logging is showing the mysql is running out of connections. I think this is the culprit.
It looks likely that the postgres session implementation is also doing this.
Source: beego/beego