Skip to content

Use a connection pool instead of a single DB connection - #408

Merged
domdomegg merged 2 commits into
modelcontextprotocol:mainfrom
rdimitrov:use-pool
Sep 10, 2025
Merged

domdomegg merged 2 commits into
modelcontextprotocol:mainfrom
rdimitrov:use-pool

Conversation

@rdimitrov

@rdimitrov rdimitrov commented Sep 10, 2025 •

Copy link
Copy Markdown
Member

Motivation and Context

The following PR should fix the recent "conn busy" issue caused by the PostgreSQL implementation using a single database connection (*pgx.Conn) instead of a connection pool (*pgxpool.Pool). When multiple concurrent requests try to access the endpoint, they would conflict trying to use the same connection.

How Has This Been Tested?

Builds locally

Breaking Changes

No

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation update

Checklist

  • I have read the MCP Documentation
  • My code follows the repository's style guidelines
  • New and existing tests pass locally
  • I have added appropriate error handling
  • I have added or updated documentation as needed

Additional context

Related to #400, #405 and #407

@rdimitrov
rdimitrov requested a review from Copilot September 10, 2025 11:01

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR replaces the single PostgreSQL database connection with a connection pool to resolve "conn busy" issues occurring during concurrent requests. The change migrates from using *pgx.Conn to *pgxpool.Pool to better handle multiple simultaneous database operations.

  • Replaces single database connection with a connection pool configuration
  • Updates all database operations to use the pool instead of direct connection
  • Adds connection pool settings optimized for stability and concurrent load handling

Reviewed Changes

Copilot reviewed 2 out of 3 changed files in this pull request and generated no comments.

File Description
internal/database/postgres.go Migrates from single connection to connection pool with configured settings and updates all database operations
go.mod Adds required dependencies for connection pooling (puddle/v2 and golang.org/x/sync)

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

@rdimitrov

rdimitrov commented Sep 10, 2025 •

Copy link
Copy Markdown
Member Author

@claude - please review this PR while making sure it addresses the referenced issues

edit: I assume it fails because I'm using a fork instead of a branch in origin

@claude

claude Bot commented Sep 10, 2025 •

Copy link
Copy Markdown
Contributor

Claude encountered an error —— View job

Failed with exit code 128

I'll analyze this and get back to you.

@tadasant

Copy link
Copy Markdown
Member
Review from Claude Code locally

Code Review for PR #408: Use a connection pool instead of a single DB connection

This PR addresses a critical production issue where concurrent requests to the PostgreSQL database were failing with "conn busy" errors. The solution correctly migrates from using a single database connection (*pgx.Conn) to a
connection pool (*pgxpool.Pool).

✅ Strengths

  1. Fixes the core issue: Moving to a connection pool directly addresses the concurrency problem described in issues failed to query servers: failed to deallocate cached statement(s): conn busy #400, API 500 Error: Database connection pool issue on /v0/servers endpoints #405, and 400 error when trying to publish #407.

  2. Sensible pool configuration: The pool settings show good production awareness:

    config.MaxConns = 30                      // Handle good concurrent load
    config.MinConns = 5                       // Keep connections warm for fast response
    config.MaxConnIdleTime = 30 * time.Minute // Keep connections available for bursts
    config.MaxConnLifetime = 2 * time.Hour    // Refresh connections regularly for stability
  3. Proper resource management: The migration approach for acquiring a connection from the pool and releasing it after migrations is correct.

  4. Clean interface preservation: All the database interface methods remain unchanged, maintaining API compatibility.

🔧 Suggestions for Improvement

  1. Error handling improvement in migration setup

The current migration setup could be more robust:

// Current code:
conn, err := pool.Acquire(ctx)
if err != nil {
return nil, fmt.Errorf("failed to acquire connection for migrations: %w", err)
}
defer conn.Release()

migrator := NewMigrator(conn.Conn())

Suggestion: Add cleanup in case migration fails:

conn, err := pool.Acquire(ctx)
if err != nil {
pool.Close() // Clean up pool if migration setup fails
return nil, fmt.Errorf("failed to acquire connection for migrations: %w", err)
}
defer conn.Release()

migrator := NewMigrator(conn.Conn())
if err := migrator.Migrate(ctx); err != nil {
pool.Close() // Clean up pool if migrations fail
return nil, fmt.Errorf("failed to run database migrations: %w", err)
}

  1. Consider making pool settings configurable

The hardcoded pool settings might not be optimal for all deployment environments:

// Consider adding to config struct:
type DatabaseConfig struct {
ConnectionURI string
MaxConns int32 // Default: 30
MinConns int32 // Default: 5
MaxConnIdleTime time.Duration // Default: 30 minutes
MaxConnLifetime time.Duration // Default: 2 hours
}

  1. Add context timeout for pool creation

Consider adding a timeout for pool creation to prevent hanging during startup:

// Create connection pool with configured settings
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()

pool, err := pgxpool.NewWithConfig(ctx, config)

  1. Pool metrics/monitoring consideration

For production observability, consider exposing pool stats:

// Add method to expose pool stats for monitoring
func (db *PostgreSQL) Stats() *pgxpool.Stat {
return db.pool.Stat()
}

🧪 Testing Recommendations

The PR mentions "Builds locally" but doesn't include tests for the pool functionality. Consider adding:

  1. Integration test for concurrent access:
    func TestPostgreSQLConcurrency(t *testing.T) {
    // Test multiple goroutines accessing database simultaneously
    }
  2. Pool configuration test:
    func TestPostgreSQLPoolConfig(t *testing.T) {
    // Verify pool settings are applied correctly
    }

🔍 Code Quality

  • The go.mod changes look correct with the new puddle/v2 and golang.org/x/sync dependencies
  • Method signatures remain identical, preserving backward compatibility
  • Error messages are clear and actionable
  • Code style is consistent with the existing codebase

✅ Overall Assessment

This is a solid fix for a critical production issue. The approach is sound and the implementation is clean. The suggested improvements are mostly about robustness and configurability rather than correctness.

Recommendation: ✅ Approve with minor suggestions

The core fix is correct and will resolve the immediate "conn busy" issues in production. The suggestions above can be addressed in this PR or follow-up PRs depending on urgency.

I don't think its suggestions are needed. Maybe the observability bit would be nice, so we know if we are butting up against the limits regularly, but can fast follow if we want that.

Thank you for fixing!!

@domdomegg domdomegg left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ty, happy to approve this for now

In future would it be better to use pgbouncer so if we scale replicas etc. the connections don't also vary? I think CloudNative Postgres, what we use for hosting the database, supports this fairly easily: https://cloudnative-pg.io/documentation/1.16/connection_pooling/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants