简体   繁体   English

在多个请求期间防止更新查询中的 MongoDB 竞争条件

[英]Prevent MongoDB race condition in update query during multiple requests

I have a simple web application in Flask and I use Mongoengine as ORM.我在 Flask 中有一个简单的 web 应用程序,我使用 Mongoengine 作为 ORM。 The API takes in a request, adds the request to a worker queue, decreases the user's license count and save it back. API 接收请求,将请求添加到工作队列,减少用户的许可证计数并将其保存回来。 Example code given below:下面给出的示例代码:

def process_request(body):
    user = User.objects.get(username=username_from_session)

    add_request_to_worker_queue(body['data'])
    
    user.total_license_count = user.total_license_count - 1

    user.save()

This works as expected.这按预期工作。 But I noticed when multiple requests are sent from the same user at the same time, the license_count is not decreased as expected.但是我注意到,当同一用户同时发送多个请求时,license_count 并没有按预期减少。 I suppose this is because the other requests do not see the update of the first request as it is still processing.我想这是因为其他请求没有看到第一个请求的更新,因为它仍在处理中。

I tried adding a random delay to the requests but it did not help.我尝试在请求中添加随机延迟,但没有帮助。 I don't know if there is some form of lock mechanism in MongoDB to wait till the other process finishes processing.我不知道 MongoDB 中是否有某种形式的锁定机制来等待其他进程完成处理。 How do I fix this to prevent this from happening.我该如何解决这个问题以防止这种情况发生。

My stack is Python, Flask, Mongoengine, MongoDB我的堆栈是 Python,Flask,Mongoengine,MongoDB

Use conditional updates, set condition as license_count > 0, use $inc operator to perform the decrement and read the number of updates done to see if the count started out positive.使用条件更新,将条件设置为 license_count > 0,使用 $inc 运算符执行递减并读取完成的更新次数以查看计数是否开始为正。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 防止出现争用情况,在这种情况下许多请求可能会同时触发仅应运行一次的呼叫 - Prevent a race condition where a many requests may concurrent trigger a call which should run only once 防止在Python3中进行信号处理的竞争条件 - Prevent a race condition for Signal handling in Python3 如何在多个进程尝试写入然后同时从文件读取时防止竞争条件 - How to prevent a race condition when multiple processes attempt to write to and then read from a file at the same time 更新与 mongodb 中的查询匹配的多个数组元素 - update multiple array elements matching a query in mongodb $push 和 $set 在同一个更新查询中,条件为 $cond pymongo mongodb - $push and $set in same update query with condition $cond pymongo mongodb 在创建具有递增字段的对象期间避免竞争条件 - Avoid race condition during creating object with incremented field 如何通过限制SUM防止INSERT上Django中的竞争条件? - How to prevent race condition in Django on INSERT with limiting SUM? 使用 json 文件时,多处理锁不会阻止竞争条件 - multiprocessing lock doesnt prevent race condition when working with json file 在单独的 python 脚本中拥有“关键资源”以防止竞争条件 - Having 'Critical Resource' in separate python script to prevent race condition Mongodb 带条件的聚合查询 - Mongodb aggregate query with condition
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM