Skip to content

core: users/groups reduce number of database queries - #20431

Merged
gergosimonyi merged 7 commits into
goauthentik:mainfrom
ryanpesek:optimize-users-groups-v2
Apr 28, 2026
Merged

gergosimonyi merged 7 commits into
goauthentik:mainfrom
ryanpesek:optimize-users-groups-v2

Conversation

@ryanpesek

@ryanpesek ryanpesek commented Feb 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Optimizations for the users and groups API endpoints to reduce N+1 queries and database load.

Changes

Users API

  1. Annotate is_superuser to avoid N+1 queries
    Changed is_superuser from a direct BooleanField to a SerializerMethodField that uses a database annotation. The get_queryset method now annotates each user with _annotated_is_superuser using an Exists subquery that checks superuser group membership (including inherited membership via group ancestry).

Before: Each user's is_superuser property triggered a separate query to check group membership.
After: A single annotated query determines superuser status for all users in the response.

  1. Always prefetch groups/roles with ID-only optimization
    When include_groups=false or include_roles=false, the queryset now uses Prefetch with .only() to fetch just the primary keys instead of skipping the prefetch entirely.

Why: The groups and roles PKs are always serialized in the response. Previously, when include_groups=false, no prefetch occurred, causing N+1 queries when serializing the PK list. Now we always prefetch, but use ID-only queries when full objects aren't needed.

Groups API

  1. Always prefetch parents and children
    Changed get_queryset to always prefetch parents and children alongside roles, removing the conditional prefetch logic.

Why: The parents and children PKs are always serialized in the response regardless of the include_parents/include_children query parameters (those control whether the full objects are included). Always prefetching avoids N+1 queries when serializing the PK lists.

  1. Bulk validation for users field
    Added BulkPrimaryKeyRelatedField and BulkManyRelatedField classes that validate all user PKs in a single COUNT query instead of one query per PK.

Before: Updating a group with 1000 users triggered 1000 individual SELECT queries to validate each user PK exists.
After: A single SELECT COUNT(*) query validates all PKs exist. Per-PK queries only run when there's an actual validation error (to report which specific PK is invalid).


Checklist

  • Local tests pass (ak test authentik/)
  • The code has been formatted (make lint-fix)

If an API change has been made

  • The API schema has been updated (make gen-build)

If changes to the frontend have been made

  • The code has been formatted (make web)

If applicable

  • The documentation has been updated
  • The documentation has been formatted (make docs)

@ryanpesek
ryanpesek requested a review from a team as a code owner February 20, 2026 03:40
@netlify

netlify Bot commented Feb 20, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for authentik-docs ready!

Name Link
🔨 Latest commit 3d4ee64
🔍 Latest deploy log https://app.netlify.com/projects/authentik-docs/deploys/69bd3cbae4f27f0008d5a90f
😎 Deploy Preview https://deploy-preview-20431--authentik-docs.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@ryanpesek ryanpesek mentioned this pull request Feb 20, 2026
2 of 6 tasks
@codecov

codecov Bot commented Feb 20, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 56.36364% with 24 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.13%. Comparing base (2a02726) to head (10f4d72).
⚠️ Report is 62 commits behind head on main.

Files with missing lines Patch % Lines
authentik/core/api/groups.py 50.00% 22 Missing ⚠️
authentik/core/api/users.py 81.81% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #20431      +/-   ##
==========================================
- Coverage   93.21%   93.13%   -0.09%     
==========================================
  Files        1016     1016              
  Lines       58042    58089      +47     
  Branches      327      327              
==========================================
- Hits        54104    54100       -4     
- Misses       3938     3989      +51     
Flag Coverage Δ
conformance 36.68% <41.81%> (+<0.01%) ⬆️
e2e 42.57% <54.54%> (-0.05%) ⬇️
integration 33.60% <40.00%> (-0.04%) ⬇️
rust 0.00% <ø> (ø)
unit 91.98% <56.36%> (-0.03%) ⬇️
unit-migrate 92.03% <56.36%> (-0.03%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@netlify

netlify Bot commented Feb 21, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for authentik-integrations ready!

Name Link
🔨 Latest commit 3d4ee64
🔍 Latest deploy log https://app.netlify.com/projects/authentik-integrations/deploys/69bd3cbafd2cda00083b24ae
😎 Deploy Preview https://deploy-preview-20431--authentik-integrations.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@netlify

netlify Bot commented Feb 21, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for authentik-storybook ready!

Name Link
🔨 Latest commit 3d4ee64
🔍 Latest deploy log https://app.netlify.com/projects/authentik-storybook/deploys/69bd3cba201c65000830afd0
😎 Deploy Preview https://deploy-preview-20431--authentik-storybook.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@gergosimonyi gergosimonyi left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi Ryan!

Re:

  1. Bulk validation for users field
    Added BulkPrimaryKeyRelatedField and BulkManyRelatedField classes that validate all user PKs in a single COUNT query instead of one query per PK.

Before: Updating a group with 1000 users triggered 1000 individual SELECT queries to validate each user PK exists.
After: A single SELECT COUNT(*) query validates all PKs exist. Per-PK queries only run when there's an actual validation error (to report which specific PK is invalid).

How did you produce this issue? I tried on current main (ea4848c at the time of writing) with a group that has exactly 1000 users, from the admin interface, and found that whether I

  • update the group object (I toggledis_superuser), or
  • update group memberships (I added a 1001st user)

the number of SQL queries was way below 1000. Scanning through them I didn't find a section that seemed to validate current users.

Am I misunderstanding something? Or is this only an issue in a very specific case I didn't try?

@ryanpesek

Copy link
Copy Markdown
Contributor Author

Hi Ryan!

Re:

  1. Bulk validation for users field
    Added BulkPrimaryKeyRelatedField and BulkManyRelatedField classes that validate all user PKs in a single COUNT query instead of one query per PK.

Before: Updating a group with 1000 users triggered 1000 individual SELECT queries to validate each user PK exists.
After: A single SELECT COUNT(*) query validates all PKs exist. Per-PK queries only run when there's an actual validation error (to report which specific PK is invalid).

How did you produce this issue? I tried on current main (ea4848c at the time of writing) with a group that has exactly 1000 users, from the admin interface, and found that whether I

  • update the group object (I toggledis_superuser), or
  • update group memberships (I added a 1001st user)

the number of SQL queries was way below 1000. Scanning through them I didn't find a section that seemed to validate current users.

Am I misunderstanding something? Or is this only an issue in a very specific case I didn't try?

Hey @gergosimonyi thanks for taking a look. This fix is for the PUT endpoint /core/groups/{group_uuid}/ as we update group membership in bulk. I am pretty sure when you use the admin UI, that is calling the POST /core/groups/{group_uuid}/add_user/ or POST /core/groups/{group_uuid}/remove_user/ which only accept one user pk at a time. The PUT endpoint has to validate that all user pk in the users attribute are valid

@gergosimonyi

gergosimonyi commented Apr 28, 2026 •

Copy link
Copy Markdown
Member

Ohhh, I see. We don't allow the viewset's default POST/PUT/PATCH action to change many-to-many on [some other API endpoint] and I automatically assumed it was not allowed here either. My bad.

This seems like a reasonable workaround until such time that the issue is fixed in DRF. They already know about it: encode/django-rest-framework#9607

Thank you for this contribuiton!

@gergosimonyi
gergosimonyi enabled auto-merge (squash) April 28, 2026 11:45
@gergosimonyi
gergosimonyi merged commit e63ff69 into goauthentik:main Apr 28, 2026
103 of 104 checks passed
kensternberg-authentik added a commit that referenced this pull request Apr 29, 2026
* main: (782 commits)
  web: bump knip from 6.4.1 to 6.6.0 in /web (#21957)
  core: bump github.com/getsentry/sentry-go from 0.45.1 to 0.46.0 (#21955)
  core: bump uvicorn[standard] from 0.44.0 to 0.45.0 (#21956)
  core: bump rustls from 0.23.39 to 0.23.40 (#21958)
  core: support hashed password in users API + automated install (#18686)
  core, web: update translations (#21952)
  providers/saml: generate issuer url when provider is set on app (#18022)
  root: fix rust build with uv-installed Python (#21858)
  core: add support for hiding applications from the user dashboard (#21530)
  core: bump ruff from 0.15.11 to 0.15.12 (#21871)
  packages/ak-axum/router: add X-Powered-By to all responses (#21940)
  core: bump microsoft-kiota-serialization-form from 1.9.8 to v1.10.1 (#21909)
  core: bump pytest-randomly from 4.0.1 to 4.1.0 (#21873)
  core: users/groups reduce number of database queries (#20431)
  core: bump types-channels from 4.3.0.20260408 to 4.3.0.20260421 (#21872)
  ci: bump taiki-e/install-action from 2.75.21 to 2.75.22 in /.github/actions/setup (#21877)
  core, web: update translations (#21870)
  sources/oauth: ensure user ID is returned as str (#21880)
  translate: Updates for project authentik and language no_NO (#21862)
  core: bump maxminddb from 3.0.0 to v3.1.1 (#21907)
  ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants