Skip to content

fix: avoid blocking the event loop during OAuth token exchange#1342

Open
kratos0718 wants to merge 1 commit into
khoj-ai:masterfrom
kratos0718:fix/async-blocking-oauth-post
Open

fix: avoid blocking the event loop during OAuth token exchange#1342
kratos0718 wants to merge 1 commit into
khoj-ai:masterfrom
kratos0718:fix/async-blocking-oauth-post

Conversation

@kratos0718

Copy link
Copy Markdown

Overview

The Google OAuth callback (src/khoj/routers/auth.py, the async auth route) exchanges the authorization code for a token using a synchronous requests.post:

async def auth(request: Request):
    ...
    verified_data = requests.post("https://oauth2.googleapis.com/token", ...)

A blocking call inside an async handler blocks the entire event loop for the duration of the network round-trip. So during every login's token exchange, all other in-flight requests the server is handling are frozen.

Fix

Offload the blocking call to a worker thread with asyncio.to_thread, keeping the loop responsive:

verified_data = await asyncio.to_thread(
    requests.post,
    "https://oauth2.googleapis.com/token",
    headers={"Content-Type": "application/x-www-form-urlencoded"},
    data=payload,
)

asyncio is already imported in this module; no new dependency, behavior unchanged.

  • python -m py_compile clean.

The Google OAuth callback handler (async auth route) exchanges the code
for a token with a synchronous requests.post(). A blocking call inside an
async handler freezes the entire event loop for the network round-trip,
so every other in-flight request stalls during each login. Offload it
with asyncio.to_thread so the loop stays responsive.
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