如何使用 lambda 使 DynamoDB 和 Cloud Search 保持同步

How can lambda be used to keep DynamoDB and Cloud Search in sync

假设我们在 DynamoDB Table 上使用 AWS 触发器,并且该触发器是 运行 一个 lambda 函数,其工作是更新进入 CloudSearch 的条目(以保持 DynamoDB 和 CS 同步).

我不太清楚 Lambda 如何始终使数据与 dynamoDB 中的数据保持同步。考虑以下流程:

  1. 应用程序更新 DynamoDB table 的记录 A(比如 A1)
  2. 紧接着应用程序更新相同 table 的相同记录 A(到 A2)
  3. 1 的触发器导致 1 的 Lambda 开始执行
  4. 2 的触发器导致 2 的 Lambda 开始执行
  5. 第 4 步先完成,因此 CloudSearch 看到 A2
  6. 现在第 3 步完成,因此 CloudSearch 看到 A1

Lambda 触发器不保证仅在上一次调用完成后启动(如有错误请更正,并提供给我 link)

如我们所见,事情不同步了。

我认为最接近的方法是使用 AWS Kinesis Streams,但也可以使用单个碎片(1MB ps 限制摄取)。如果该限制有效,则可以编写您的消费者应用程序,以便首先按顺序处理记录,即只有在前一条记录放入 CS 之后,才应处理下一条记录。假设上述说法是正确的,如果向 DynamoDB 中摄取如此多的数据以至于 Kinesis 需要多个分片,如何确保同步正确发生?

您可以使用 DynamoDB Streams 实现:

DynamoDB Streams

"A DynamoDB stream is an ordered flow of information about changes to items in an Amazon DynamoDB table."

DynamoDB Streams 保证以下内容:

  • 每个流记录在流中只出现一次。
  • 对于 DynamoDB 中修改的每个项目 table,流记录的显示顺序与项目的实际修改顺序相同。

DynamoDB Streams 的另一个很酷的地方是,如果您的 Lambda 无法处理该流(例如,在 Cloud Search 中编制索引时出现任何错误),该事件将继续重试,而其他记录流将等待您的上下文成功。

我们使用 Streams 使 Elastic Search 索引与 DynamoDB table 保持同步。

AWS Lambda F&Q Link

Q: How does AWS Lambda process data from Amazon Kinesis streams and Amazon DynamoDB Streams?

The Amazon Kinesis and DynamoDB Streams records sent to your AWS Lambda function are strictly serialized, per shard. This means that if you put two records in the same shard, Lambda guarantees that your Lambda function will be successfully invoked with the first record before it is invoked with the second record. If the invocation for one record times out, is throttled, or encounters any other error, Lambda will retry until it succeeds (or the record reaches its 24-hour expiration) before moving on to the next record. The ordering of records across different shards is not guaranteed, and processing of each shard happens in parallel.

这意味着 Lambda 会一个接一个地选择一个分片中的记录,以便它们出现在分片中,并且在处理完前一个记录之前不会执行新记录!

然而,剩下的另一个问题是,如果同一记录的条目存在于不同的分片中怎么办?值得庆幸的是,AWS DynamoDB Streams 确保主键始终仅驻留在特定的分片中。 (我认为,本质上,主键是用来查找指向分片的散列的)AWS Slide Link. See more from AWS Blog 下面:

The relative ordering of a sequence of changes made to a single primary key will be preserved within a shard. Further, a given key will be present in at most one of a set of sibling shards that are active at a given point in time. As a result, your code can simply process the stream records within a shard in order to accurately track changes to an item.