Why is Postgres complaining 'FATAL #53300 sorry, too many clients already' when I am using only one client?

1.2k views Asked by At

I have a global instance to Postgres database which is being used throughout the code.

There are 500 goroutines inserting some data into the database using the same instance.

So when there is just one instance (client) why does it fail with panic: FATAL #53300 sorry, too many clients already?

My understanding is that, there is just one instance of the database which is being created by ConnectToDB() method when it is called for the first time & on the subsequent calls, it merely returns this instance instead of creating a new one.

Finally when main ends, that one single instance is closed.

I am not able to understand how could it possibly create too many instances as indicated by the error message.

package main

import (
    "github.com/go-pg/pg/v10"
    "github.com/go-pg/pg/v10/orm"
    "sync"
)

var db *pg.DB
var once sync.Once


type DummyTable struct {
    IdOne int
    IdTwo int
}

func main() {
    var wg sync.WaitGroup

    db := ConnectToDB()
    defer db.Close()

    for i := 0; i < 500; i++ {
        wg.Add(1)
        go insertIntoDB(&wg)
    }
    wg.Wait()
}

func insertIntoDB(wg *sync.WaitGroup) {
    defer wg.Done()
    localDb := ConnectToDB()

    _, err := localDb.Model(&DummyTable{
        IdOne: 2,
        IdTwo: 3,
    }).Insert()
    if err != nil {
        panic(err)
    }
}

func createSchema(db *pg.DB) error {
    models := []interface{}{
        (*DummyTable)(nil),
    }

    for _, model := range models {
        err := db.Model(model).CreateTable(&orm.CreateTableOptions{
            Temp: false,
        })
        if err != nil {
            return err
        }
    }
    return nil
}

func ConnectToDB() *pg.DB {
    once.Do(func() {
        db = pg.Connect(&pg.Options{
            User:     "username",
            Database: "dbName",
        })
        err := createSchema(db)
        if err != nil {
            panic(err)
        }
    })
    return db
}

0

There are 0 answers