Fix race condition in _GENAI_CLIENT initialization using async lock#102
Open
kirandharmar867-maker wants to merge 2 commits intoINCF:mainfrom
Open
Fix race condition in _GENAI_CLIENT initialization using async lock#102kirandharmar867-maker wants to merge 2 commits intoINCF:mainfrom
kirandharmar867-maker wants to merge 2 commits intoINCF:mainfrom
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Issue: _GENAI_CLIENT singleton not thread-safe on cold start
Root Cause:
The GenAI client was being initialized lazily without any synchronization.
When multiple requests hit the server at the same time (especially during cold start), they could all see _GENAI_CLIENT as None and create multiple instances.
Changes:
Added an asyncio.Lock to make initialization thread-safe.
Used double-check locking to ensure the client is created only once.
Converted _get_genai_client() to async.
Updated all usages to await _get_genai_client().
Impact:
Prevents duplicate client creation
Fixes race condition during concurrent requests
Makes initialization safe and stable
No change in existing functionality
Steps to Test:
Run the backend server
Send multiple requests at the same time
Verify only one client is initialized and everything works normally
Files Modified:
backend/agents.py