From c45201a8a2a31a4faaa61cd038a701e83d8dbe0c Mon Sep 17 00:00:00 2001 From: Sihyeon Jang Date: Wed, 3 Sep 2025 05:25:26 +0900 Subject: [PATCH] perf: fix N+1 query issue in get_prompts method - Replace individual user queries with batch fetching - Use single query to fetch all required users at once - Implement O(1) user lookup with dictionary mapping - Reduce query count from 1+N to 1+1 pattern Signed-off-by: Sihyeon Jang --- backend/open_webui/models/prompts.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/backend/open_webui/models/prompts.py b/backend/open_webui/models/prompts.py index 8ef4cd2bec..706f0096ca 100644 --- a/backend/open_webui/models/prompts.py +++ b/backend/open_webui/models/prompts.py @@ -103,10 +103,16 @@ class PromptsTable: def get_prompts(self) -> list[PromptUserResponse]: with get_db() as db: - prompts = [] + all_prompts = db.query(Prompt).order_by(Prompt.timestamp.desc()).all() - for prompt in db.query(Prompt).order_by(Prompt.timestamp.desc()).all(): - user = Users.get_user_by_id(prompt.user_id) + user_ids = list(set(prompt.user_id for prompt in all_prompts)) + + users = Users.get_users_by_user_ids(user_ids) if user_ids else [] + users_dict = {user.id: user for user in users} + + prompts = [] + for prompt in all_prompts: + user = users_dict.get(prompt.user_id) prompts.append( PromptUserResponse.model_validate( {