Description
There is a race condition in backend/main.py within the /generate-blog endpoint. The code attempts to prevent duplicate blog generations for the same problem by checking the database for an existing successful record using find_one().
However, because there is no concurrency locking mechanism, if multiple identical requests hit the server at the exact same time, all of them will pass the find_one() check simultaneously (since the database hasn't been updated by the first request yet). This results in multiple expensive, parallel calls to the AI provider and identical duplicate posts being pushed to the publishing platforms simultaneously.
Steps To Reproduce
Create a simple Python script using the threading library to send 5 concurrent HTTP POST requests to /generate-blog.
Ensure the payload has the exact same title (e.g., "Race Condition Test") and publish_as_draft: true.
Execute the script so all 5 requests hit the backend at the exact same millisecond.
Check the FastAPI terminal logs to see 5 simultaneous AI generation processes running.
Check your Dev.to or Hashnode drafts dashboard to see 5 identical duplicate blog posts created.
Expected Behavior
One request should successfully trigger the AI generation and database logging process. The other 4 concurrent requests should instantly be blocked and return the error message: "Solution for '{title}' has already been published!
Environment
OS: Any
Browser: N/A (Backend API issue)
Version: Latest main branch
Description
There is a race condition in backend/main.py within the /generate-blog endpoint. The code attempts to prevent duplicate blog generations for the same problem by checking the database for an existing successful record using find_one().
However, because there is no concurrency locking mechanism, if multiple identical requests hit the server at the exact same time, all of them will pass the find_one() check simultaneously (since the database hasn't been updated by the first request yet). This results in multiple expensive, parallel calls to the AI provider and identical duplicate posts being pushed to the publishing platforms simultaneously.
Steps To Reproduce
Create a simple Python script using the threading library to send 5 concurrent HTTP POST requests to /generate-blog.
Ensure the payload has the exact same title (e.g., "Race Condition Test") and publish_as_draft: true.
Execute the script so all 5 requests hit the backend at the exact same millisecond.
Check the FastAPI terminal logs to see 5 simultaneous AI generation processes running.
Check your Dev.to or Hashnode drafts dashboard to see 5 identical duplicate blog posts created.
Expected Behavior
One request should successfully trigger the AI generation and database logging process. The other 4 concurrent requests should instantly be blocked and return the error message: "Solution for '{title}' has already been published!
Environment
OS: Any
Browser: N/A (Backend API issue)
Version: Latest main branch