1

How to manage MongoDB connection for more than 100000 goroutines in golang.

I have created one *mongo.Client instance then using this same client but it creates multiple connections.

icza
  • 389,944
  • 63
  • 907
  • 827
Vikram Biwal
  • 2,618
  • 1
  • 25
  • 36
  • 1
    `mongo.Client` manages an internal connection pool. You do not have to worry about that. `mongo.Client` is safe for concurrent use. What is your problem or question? – icza Jun 06 '21 at 18:21
  • @icza but it shows more than 10000 connection and getting too slow operations can you suggest any solution, Thanks :) – Vikram Biwal Jun 06 '21 at 18:30

1 Answers1

5

The mongo.Client manages an internal connection pool. You do not have to worry about that. mongo.Client is safe for concurrent use.

If you want to limit the internal pool, you may do so at connection using ClientOptions. For example:

clientOpts := options.Client().ApplyURI("<your-connection-string>").
    SetMaxPoolSize(100) // Allow no more than 100 connections

client, err := mongo.Connect(context.TODO(), clientOpts)
if err != nil {
    log.Fatal(err)
}

Quoting from ClientOptions.SetMaxPoolSize():

SetMaxPoolSize specifies that maximum number of connections allowed in the driver's connection pool to each server. Requests to a server will block if this maximum is reached. This can also be set through the "maxPoolSize" URI option (e.g. "maxPoolSize=100"). The default is 100. If this is 0, it will be set to math.MaxInt64.

ClientOptions also has methods for setting the MaxConnIdleTime and MinPoolSize properties.

But know that this won't speed things up. If you have a hundred thousand goroutines all interacting with MongoDB, likely MongoDB will be your bottleneck.

icza
  • 389,944
  • 63
  • 907
  • 827