Skip to content

fix: offload blocking Keycloak introspect to thread pool - #694

Open
suhr25 wants to merge 1 commit into
aiondemand:developfrom
suhr25:fix/async-event-loop-blocking
Open

fix: offload blocking Keycloak introspect to thread pool#694
suhr25 wants to merge 1 commit into
aiondemand:developfrom
suhr25:fix/async-event-loop-blocking

Conversation

@suhr25

@suhr25 suhr25 commented Feb 20, 2026

Copy link
Copy Markdown

Summary
Fixes a performance issue where blocking I/O was executed inside async code, causing the event loop to stall under load.

Problem

  • In src/authentication.py, _get_user() called keycloak_openid.introspect(token), which uses synchronous requests, blocking the asyncio event loop.
  • In src/middleware/access_log.py, a synchronous DB sess.commit() ran inside async middleware, blocking request handling.

Fix

  1. Offload Keycloak introspection to a thread pool
loop = asyncio.get_running_loop()
userinfo = await loop.run_in_executor(None, keycloak_openid.introspect, token)
  1. Move access log DB write to a background task
response.background = BackgroundTask(
    _write_access_log, resource_type, asset_id, response.status_code
)

Verification

  • Existing tests pass without modification
  • Mocked introspect() works correctly with executor
  • Concurrent requests no longer block each other
  • Access logs are still written correctly
  • Load testing shows reduced latency and improved throughput under concurrency

Run python-keycloak's synchronous introspect() via run_in_executor so it
no longer freezes the asyncio event loop on every authenticated request.
Move access log DB write to a BackgroundTask so it runs after the
response is sent instead of blocking the event loop inline.

Signed-off-by: suhr25 <suhridmarwah07@gmail.com>
@suhr25

suhr25 commented Feb 21, 2026

Copy link
Copy Markdown
Author

Hi @geetu040,
Fixed event loop blocking by offloading the Keycloak introspection call to a thread pool and moving the DB write to a background task. This restores proper async behavior and improves performance under load without changing functionality.

@suhr25

suhr25 commented Feb 23, 2026

Copy link
Copy Markdown
Author

Hi @geetu040 @fkiraly,
Just noticed the workflow is awaiting approval, so CI hasn’t run yet.
Would appreciate approval when possible. Thank you!

@suhr25

suhr25 commented Feb 28, 2026

Copy link
Copy Markdown
Author

Hi @geetu040,
Please let me know if any change is needed or it is ready to merge?

@suhr25

suhr25 commented Mar 7, 2026

Copy link
Copy Markdown
Author

Hi @geetu040 @fkiraly,
Can you please review this PR.
Thanks!

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.

1 participant