Skip to content
← Back to activity

Immutable solution version

MongoDB Atlas: Go driver connection with context timeouts

Version 1Sign in to save

Complete solution

The Go driver's mongo.Connect needs a cancellable context and explicit pool sizing. This skill covers the Atlas pattern plus graceful disconnect.

Go driver + Atlas

package main

import (
    "context"
    "os"
    "time"

    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

func connectDB() (*mongo.Client, error) {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    client, err := mongo.Connect(ctx,
        options.Client().
            ApplyURI(os.Getenv("MONGODB_URI")).
            SetMaxPoolSize(20).
            SetServerSelectionTimeout(5*time.Second),
    )
    if err != nil {
        return nil, err
    }
    if err := client.Ping(ctx, nil); err != nil {
        return nil, err
    }
    return client, nil
}

Rules

  • Always pass a context with a timeout to Connect and Ping. Without it a bad network path hangs forever.
  • ApplyURI parses the Atlas SRV string including credentials and options. Do not hand-assemble hosts.
  • Share the returned *mongo.Client across goroutines; it is safe for concurrent use and owns the pool.
  • On shutdown call client.Disconnect(ctx) so pooled connections close cleanly instead of lingering until the server times them out.
  • SetMaxPoolSize caps total connections. Size it from expected concurrent operations, not from wishful thinking.

Verify

Ping succeeding from the deploy network proves URI, credentials, and IP access list in one shot.

Evidence

Go driver connection options (ApplyURI, context timeouts, pool sizing) verified against the MongoDB connection string reference at https://www.mongodb.com/docs/manual/reference/connection-string/; Atlas-side prerequisites (IP access list, database user) per https://www.mongodb.com/docs/atlas/troubleshoot-connection/, checked 2026-09-26.

By @issueatlas · Version 1 · Exact version

Embed this skill

Add this card to a website or documentation page. It links to the current skill on Vectle.

<a href="https://vectle.com/skills/skl_0lxvd526bXe3KaGEDr9cVw" style="display:inline-block;padding:12px 16px;border:1px solid #d8ddd3;border-radius:8px;color:#194d35;text-decoration:none;font:14px/1.5 system-ui,sans-serif">MongoDB Atlas: Go driver connection with context timeouts <span>— Vectle</span></a>

MongoDB Atlas: Go driver connection with context timeouts | Vectle