From 0c0437a2cfd52f2bf1bf72d70992684332d80d5c Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Fri, 17 Jul 2026 19:32:13 +0000 Subject: [PATCH] fix(perf): eliminate N+1 in UserService.ListAsync with bulk role/site loading ListAsync called UserManager.GetRolesAsync() per user (N queries for N users). Now loads all roles and user-site assignments in two bulk queries, grouped by userId in memory for O(1) lookup. --- .../Services/UserService.cs | 43 ++++++++++++++++--- 1 file changed, 38 insertions(+), 5 deletions(-) diff --git a/src/Heimdall.Infrastructure/Services/UserService.cs b/src/Heimdall.Infrastructure/Services/UserService.cs index a1c078b..fd44df5 100644 --- a/src/Heimdall.Infrastructure/Services/UserService.cs +++ b/src/Heimdall.Infrastructure/Services/UserService.cs @@ -31,11 +31,26 @@ public class UserService : IUserService .Take(pageSize) .ToListAsync(ct); - var items = new List(); - foreach (var user in users) - { - items.Add(await MapToResponse(user)); - } + var userIds = users.Select(u => u.Id).ToList(); + + // Bulk-load roles and site assignments (single query each, not N+1) + var roleQuery = from ur in _db.Set>() + join r in _db.Roles on ur.RoleId equals r.Id + where userIds.Contains(ur.UserId) + select new { ur.UserId, r.Name }; + var rolesByUser = (await roleQuery.ToListAsync(ct)) + .GroupBy(x => x.UserId) + .ToDictionary(g => g.Key, g => g.Select(x => x.Name!).ToList()); + + var sitesByUser = (await _db.UserSites + .Where(us => userIds.Contains(us.UserId)) + .ToListAsync(ct)) + .GroupBy(us => us.UserId) + .ToDictionary(g => g.Key, g => g.Select(us => us.SiteId).ToList()); + + var items = users.Select(u => MapToResponse(u, + rolesByUser.GetValueOrDefault(u.Id, []), + sitesByUser.GetValueOrDefault(u.Id, []))).ToList(); return ServiceResult>.Success( new PagedResult(items, total, page, pageSize)); @@ -210,6 +225,24 @@ public class UserService : IUserService user.CreatedAt); } + private static UserResponse MapToResponse(AppUser user, List roles, List siteIds) + { + return new UserResponse( + user.Id, + user.Email ?? "", + user.DisplayName, + user.Theme, + user.Language, + roles, + siteIds, + user.TwoFactorEnabled, + user.LockoutEnabled && user.LockoutEnd.HasValue && user.LockoutEnd > DateTimeOffset.UtcNow, + user.LockoutEnd?.UtcDateTime, + user.AccessFailedCount, + user.EmailConfirmed, + user.CreatedAt); + } + private static string GenerateTemporaryPassword() { const string lower = "abcdefghijklmnopqrstuvwxyz";