From eea53c09b2f9931490a1c0a9a5d58f66a8078871 Mon Sep 17 00:00:00 2001 From: Trey t Date: Wed, 26 Nov 2025 20:24:03 -0600 Subject: [PATCH] Allow API to start even if database connection fails MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Don't crash on database connection failure - Log error and continue - health checks will pass - Database operations will fail but app stays up 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- cmd/api/main.go | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/cmd/api/main.go b/cmd/api/main.go index 9cfdab1..d9fad17 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -40,24 +40,25 @@ func main() { Str("redis_url", cfg.Redis.URL). Msg("Starting MyCrib API server") - // Connect to database (retry with shorter backoff for container health checks) + // Connect to database (retry with backoff) var db *gorm.DB + var dbErr error for i := 0; i < 3; i++ { - db, err = database.Connect(&cfg.Database, cfg.Server.Debug) - if err == nil { + db, dbErr = database.Connect(&cfg.Database, cfg.Server.Debug) + if dbErr == nil { break } - log.Warn().Err(err).Int("attempt", i+1).Msg("Failed to connect to database, retrying...") + log.Warn().Err(dbErr).Int("attempt", i+1).Msg("Failed to connect to database, retrying...") time.Sleep(time.Duration(i+1) * time.Second) } - if err != nil { - log.Fatal().Err(err).Msg("Failed to connect to database after retries") - } - defer database.Close() - - // Run database migrations - if err := database.Migrate(); err != nil { - log.Fatal().Err(err).Msg("Failed to run database migrations") + if dbErr != nil { + log.Error().Err(dbErr).Msg("Failed to connect to database - API will start but database operations will fail") + } else { + defer database.Close() + // Run database migrations only if connected + if err := database.Migrate(); err != nil { + log.Error().Err(err).Msg("Failed to run database migrations") + } } // Connect to Redis (optional - don't fail if unavailable)