Skip to content

[PERFORMANCE]: Fix N+1 Query in list_prompts - Missing joinedload for gateway #1880

@crivetimihai

Description

@crivetimihai

Summary

The list_prompts() method in prompt_service.py triggers N+1 queries when accessing the gateway_slug property, identical to the pattern in list_tools (#1879).

Root Cause

Location: mcpgateway/services/prompt_service.py

The list_prompts() method builds queries without eager loading the gateway relationship. When convert_prompt_to_read() accesses gateway_slug (line 338):

"gateway_slug": getattr(db_prompt, "gateway_slug", None),

The gateway_slug hybrid property (db.py:3354-3360) triggers lazy loading:

@hybrid_property
def gateway_slug(self) -> Optional[str]:
    return self.gateway.slug if self.gateway else None

Affected Methods

  1. list_prompts() - line ~908 - needs joinedload(DbPrompt.gateway)
  2. list_prompts_for_user() - line ~1065 - needs joinedload(DbPrompt.gateway)

Fix

Add joinedload(DbPrompt.gateway) to queries:

from sqlalchemy.orm import joinedload

query = select(DbPrompt).options(joinedload(DbPrompt.gateway)).order_by(...)

Related

Acceptance Criteria

  • Add joinedload(DbPrompt.gateway) to list_prompts() query
  • Add joinedload(DbPrompt.gateway) to list_prompts_for_user() query
  • Verify with load test
  • Passes make verify

Metadata

Metadata

Assignees

Labels

performancePerformance related itemspythonPython / backend development (FastAPI)

Type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions