#4392·gofr

mongo: if MongoDB is down at startup, every operation and HealthCheck panics with a nil pointer and the client never recovers

Author: NitinKumar004Created Sep 27, 2026Updated Sep 27, 2026

Summary

If MongoDB is unreachable when the app starts, mongo.Client.Connect() returns early after the failed ping. That skips both the app_mongo_stats histogram registration and the c.Database assignment, and nothing retries later. Every subsequent operation dereferences a nil *mongo.Database and panics, and so does HealthCheck. The datasource stays dead for the whole life of the process, even after MongoDB comes back.

Separately, the uri and database fields that feed the hostname/database metric labels and the health details are never assigned anywhere, so they are always empty, even on a successful connect.

Reproduction

go
c := mongo.New(mongo.Config{URI: "mongodb://127.0.0.1:1/test", Database: "test", ConnectionTimeout: 300 * time.Millisecond})
c.UseLogger(logger)
c.UseMetrics(metrics)
c.Connect()
// ERROR: could not connect to MongoDB at 127.0.0.1 due to err: server selection error: ... connection refused
// c.Database == nil, c.uri == "", c.database == ""

c.InsertOne(ctx, "users", doc)
// RecordHistogram("app_mongo_stats") on a histogram that was never registered, then
// panic: runtime error: invalid memory address or nil pointer dereference

c.HealthCheck(ctx)
// panic: runtime error: invalid memory address or nil pointer dereference

Root cause

pkg/gofr/datasource/mongo/mongo.go:

  • Connect returns early on a connect error (~line 109) or a failed Ping (line 116).
  • NewHistogram("app_mongo_stats", ...) (line 125) and c.Database = m.Database(...) (line 127) only run after a successful ping.
  • There is no reconnect or retry.
  • Every operation (InsertOne, Find, UpdateOne, and so on) and HealthCheck use c.Database without a nil check.
  • c.uri and c.database are read for metric labels and health details but never set.

Impact

  • If MongoDB is down or not ready when a pod starts (startup ordering, a brief outage), every request that touches Mongo panics. The recovery middleware turns that into a 500 with a stack trace.
  • It only recovers after a restart.
  • Every operation also tries to record into an unregistered histogram.
  • The hostname/database metric labels are empty in every deployment.

Suggested fix

This is the same pattern that was fixed for ArangoDB in #4369 / #4373:

  • Register the histogram at the start of Connect, before dialing.
  • Keep the *mongo.Client returned by mongo.Connect even when the ping fails. The driver connects lazily and recovers once the server is reachable, so c.Database can be set right away. Alternatively, add a background retry like the SQL/Redis datasources.
  • Return a not-connected error instead of panicking wherever c.Database could still be nil.
  • Set c.database from the config and c.uri to the host only, not the full URI, which may contain credentials.