-
Notifications
You must be signed in to change notification settings - Fork 615
[PERFORMANCE]: Fix N+1 queries in Gateway single-entity retrieval functions #1994
Copy link
Copy link
Closed
Copy link
Labels
performancePerformance related itemsPerformance related itemspythonPython / backend development (FastAPI)Python / backend development (FastAPI)
Milestone
Description
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 queryProposed Fix
Apply the same pattern used for Server in PR #1975:
- Add
email_teamrelationship 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- 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),
],
)-
Remove
_get_team_name()helper method from GatewayService -
Update any admin views that assign
gateway.team = ...to usejoinedloadinstead
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
- [PERFORMANCE]: Fix N+1 queries in single-entity retrieval functions (get_server, get_gateway, etc.) #1962 - Original N+1 issue for Server (fixed)
- fix(#1962): resolve N+1 query fixes breaking tests #1975 - PR that fixed Server N+1 queries
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
performancePerformance related itemsPerformance related itemspythonPython / backend development (FastAPI)Python / backend development (FastAPI)