[4.7.x] Fix race condition causing missing subscription keys by synchronizing key table update. #11312
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.
This is an automatic copy of pull request #11302 done by Mergify.
Issue
https://gravitee.atlassian.net/browse/APIM-7382
Description
When multiple subscription calls are made to a shared API key application, all calls seem to succeed, but some subscriptions end up without the API key. This issue affects both v2 and v4 APIs, where simultaneous requests result in a race condition that causes the key binding to fail on certain subscriptions.
Additional context
Reproduction Steps
1. Create an application configured to use a shared API key.
2. Add initial subscriptions to trigger the shared API key setup.
3. Create and publish API key plans for at least three APIs with auto-subscription enabled.
4. Send simultaneous subscription requests.
For sending the subscription requests, you can use the following script. Remember to update the value of applicationId with your own test application, and ensure you have a JSON file named plan_list.json with data in the following format:
[ { "_id": "30f89c18-ac35-4290-b89c-18ac35c2901b" }, { "_id": "d5d02f76-0e94-466e-902f-760e94466ee7" }, { "_id": "337cc9fa-3287-4f6d-bcc9-fa32876f6d6c" } ]
The script is:
run_subscriptions.txt
The Fix
The root cause was a race condition during the API key generation process. The fix involved adding a synchronized block around the critical database update code to ensure that key generation for subscriptions is thread-safe and that all concurrent requests correctly bind the API key.