Meh*_*ran 11 consistency eventual-consistency amazon-web-services amazon-dynamodb
The whole reason why DynamoDB is fast and scalable is based on the fact that it is eventually consistent. But at the same time, it comes with this ConsistentRead option for operations like get, batchGet, and query which helps you make sure that the data you are reading is the latest one.
My question is about the update operation. First of all, it does not have the ConsistentRead option (one reason would be, update is not a read!). But at the same time, you can update a record in an atomic manner with ConditionExpression, like this:
await docClient.update({
TableName: 'SomeTable',
Key: {id},
UpdateExpression: "set #status = :new_status",
ConditionExpression: '#status = :old_status',
ExpressionAttributeNames: {
"#status": "status",
},
ExpressionAttributeValues: {
":old_status": "available",
":new_status": "done",
},
}).promise()
Run Code Online (Sandbox Code Playgroud)
这将确保在更新时,旧值是available,如果不是,操作将失败并抛出异常。所以,从某种意义上说,你可以说这update是高度一致的。
但我的问题是关于您需要确保记录存在的场景。假设您有一个插入记录的函数。另一个更新相同的记录(给定它的id)。我担心的是,如果在update执行操作时,由于 DynamoDB 的最终一致性,没有匹配的记录并且更新失败会怎样。如前所述,该update操作没有提供ConsistentRead使其高度一致的选项。
这是一个有效的担忧吗?有什么我可以做的吗?
没有强一致的更新;强一致性适用于读,基本上在写入后立即查看的数据对于实体的所有观察者来说都是一致的。
\n当您的应用程序将数据写入 DynamoDB 表并收到 HTTP 200 响应 (OK) 时,写入已发生(至少在一个存储位置)并且是持久的。数据最终在所有存储位置上保持一致,通常在一秒或更短的时间内。然后你可以选择阅读以最终一致性或强一致性方式
\n对同一项目的并发写入应使用乐观并发来处理,您可以进行条件写入使用 DynamoDB 事务库(在适用于 Java 的 AWS 开发工具包中提供)
\n如果您需要自动更新多个项目,您可以使用 DynamoDB 事务。
\n\n\nDynamoDB 事务为开发人员提供跨单个 AWS 账户和区域内的一个或多个表的原子性、一致性、隔离性和持久性 (ACID)。在构建需要协调插入、删除或更新多个项目作为单个逻辑业务操作的一部分的应用程序时,您可以使用事务。
\nhttps://aws.amazon.com/blogs/aws/new-amazon-dynamodb-transactions/
\n
CRUD 操作是原子的;然而,官方文档并未提及它们被隔离(在 DynamoDB 事务之外)。原则上,竞争条件可能会发生并且有条件更新可能会返回错误。
\n在此处查看更多信息:https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html
\n或者,您的用例可能会受益于DynamoDB 全局表,该表使用 \xe2\x80\x9clast writer wons\xe2\x80\x9d 协调并发写入之间的关系。
\n