Hello folks,
I have 2 Parse Servers hosting the same application on production (500+ requests/second). Requests are distributed using a load balancer. I have encountered an issue with Parse Cloud Code.
Minimum reproducible code of the problem.
Parse.Cloud.afterSave("Shop", async (request) => {
// Ad Creation
const pShop = request.object; // Parse Object 'Shop'
const shopName = pShop.get('name'); // Name of the Shop
const shopIdentifier = `"${pShop.id}.${shopName}"`; // Formatted for logging
// Check for any existing advertisements
const query = new Parse.Query('Advertisement');
query.equalTo('shop', pShop); // 'shop' field is of type Shop Pointer
query.equalTo('active', true); // Only active ads are searched
const result = await query.first();
if (result === undefined) {
// No ads exists, create a new one.
console.log(`Ad not found. Creating one for ${shopIdentifier}`);
const pAd = new Parse.Object('Advertisement');
pAd.set('shop', pShop);
pAd.set('active', true);
// Random title set for the reproducible code, production may have different titles based on modification.
pAd.set('title', `Random Title #${Math.floor(Math.random() * 100)}`);
await pAd.save();
/*
* PROBLEM: When the Shop is modified concurrently by multiple users (> 100) at the same time,
*
* This block is executed multiple times which ends up
* creating a lot of duplicate Ads for the same shop.
*/
} else {
console.log(`An Advertisement already exists for ${shopIdentifier}`);
}
});
Some kind of central locking system could possibly solve this. I would like to know the thoughts of the community as to how to overcome this problem in Cloud Code. Thank You.