Skip to content

Fix/ resolve race condition in /generate-blog endpoint#204

Open
Unnati1007 wants to merge 2 commits into
vanshaggarwal27:mainfrom
Unnati1007:fix/race-condition
Open

Fix/ resolve race condition in /generate-blog endpoint#204
Unnati1007 wants to merge 2 commits into
vanshaggarwal27:mainfrom
Unnati1007:fix/race-condition

Conversation

@Unnati1007

@Unnati1007 Unnati1007 commented Jun 8, 2026

Copy link
Copy Markdown

Description

This PR resolves a race condition in backend/main.py within the /generate-blog endpoint.

Previously, the code checked the database for an existing successful record using find_one(). However, because there was no concurrency locking mechanism, if multiple identical requests hit the server at the exact same time, all of them passed the find_one() check simultaneously. This resulted in multiple expensive parallel calls to the AI provider and identical duplicate posts being pushed to the publishing platforms simultaneously.

Fix #184

Implemented a distributed atomic lock using MongoDB's unique _id indexing.
Before processing a blog, the endpoint attempts to insert a record into a dedicated locks collection using a unique ID derived from the problem title, author, and user email. Only one request can successfully insert this lock. All other concurrent requests instantly receive a DuplicateKeyError and are cleanly rejected with a 400 Bad Request indicating the blog has already been published.

Steps to Reproduce

  1. Start the FastAPI server locally (uvicorn main:app --port 10000).
  2. Temporarily bypass authentication (for testing purposes) or pass a valid JWT token.
  3. Run a Python script utilizing the threading and requests library to send 5 concurrent HTTP POST requests to /generate-blog simultaneously with identical JSON payloads.
  4. Observe that exactly 1 request acquires the lock and begins processing, while the other 4 requests are immediately rejected by the lock.

@Unnati1007

Copy link
Copy Markdown
Author

@vanshaggarwal27 please check the pr and merge it

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.

[BUG] Race condition in /generate-blog endpoint allows duplicate concurrent AI executions and blog posts

1 participant