Skip to content

[PERFORMANCE]: Fix N+1 queries in Gateway single-entity retrieval functions #1994

@crivetimihai

Description

@crivetimihai

Summary

Similar to #1962 (which fixed Server N+1 queries), Gateway single-entity retrieval functions use db.get() without eager loading and make extra queries via _get_team_name().

Problem

get_gateway() in gateway_service.py:2078 fetches a gateway without eager loading, then calls _get_team_name() which executes an additional query:

# gateway_service.py:2078
gateway = db.get(DbGateway, gateway_id)
# ...
gateway.team = self._get_team_name(db, getattr(gateway, "team_id", None))  # Extra query

Proposed Fix

Apply the same pattern used for Server in PR #1975:

  1. Add email_team relationship to Gateway model:
email_team: Mapped[Optional["EmailTeam"]] = relationship(
    "EmailTeam",
    primaryjoin="and_(Gateway.team_id == EmailTeam.id, EmailTeam.is_active == True)",
    foreign_keys=[team_id],
)

@property
def team(self) -> Optional[str]:
    return self.email_team.name if self.email_team else None
  1. Add eager loading to get_gateway():
gateway = db.get(
    DbGateway,
    gateway_id,
    options=[
        selectinload(DbGateway.tools),
        selectinload(DbGateway.prompts),
        selectinload(DbGateway.resources),
        joinedload(DbGateway.email_team),
    ],
)
  1. Remove _get_team_name() helper method from GatewayService

  2. Update any admin views that assign gateway.team = ... to use joinedload instead

Affected Functions

Service Function Line Impact
gateway_service get_gateway() 2078 Medium
gateway_service toggle_gateway_status() 2107 Medium
gateway_service update_gateway() TBD Medium

Related

Metadata

Metadata

Assignees

Labels

performancePerformance related itemspythonPython / backend development (FastAPI)

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions