Establishing a connection is slow?

I am noticing that the first command executed after connecting is very slow. Subsequent commands after the first command perform fine. If I disconnect, and then reconnect, again the first command is slow.

Here is a repository that uses the Go SDK to connect to: cosmos db, atlas and a local mongo instance. In the example I am using Ping, but I am seeing this with any command.

Connected to Cosmos DB

$ go run main.go
Ping 1.549611747s
Ping 65.599248ms

Connected to Atlas

$ go run main.go
Ping 624.839234ms
Ping 33.384318ms

Connected to local Mongo

go run main.go
Ping 8.688944ms
Ping 820.645µs

I believe that the Connect function in the Go SDK does not actually perform I/O. The first time I call Ping is when a connection is established.

Am I missing an optimization or using the SDK incorrectly? Any suggestions for how to improve performance on the first call would be greatly appreciated. I’m writing a command line tool that accesses mongodb and having every command take an extra second is a problem.

If anyone can share if this is expected performance, that would be really helpful to know. I’m not sure if I should keep digging, or just give up. :sweat_smile:

Hey @Carolyn_Van_Slyck, thanks for the question and detailed repro example! You are correct that mongo.Connect() is currently a misnomer and doesn’t actually do any I/O or create any connections. The first operation run with a Client actually creates the connections needed as well as runs the operation. There are a few ways to improve the performance of the first operation:

  • Set the minimum connection pool size, either with the SetMinPoolSize(N) Client option or with the minPoolSize=N connection string option.
  • Run an operation to establish a connection before running the operation that you want to run quickly (e.g. a Ping operation).

Keep in mind that a new Client has to create a connection to run any operation, so the above suggestions may not make the total time between making a new Client and completing the first operation any shorter.

Does your command line tool run one operation per CLI call? Do you have an example of how you’re using the command line tool?

1 Like