有没有一种方法可以使用 GCP Firestore、PubSub 和消息排序来实现事务性发件箱模式

Is there a way to implement transactional outbox pattern with GCP Firestore, PubSub and message ordering

我们正在开发一项在 GCP Firestore 中存储内部数据的服务。对于一些数据的变化,我们需要向外部服务发送消息。

为确保可靠性,当且仅当更改我们内部数据的事务已提交时,我们才发送消息。

为了实现这个目标,我们将使用 transactional outbox pattern. So we created a Firestore collection to which we append new events/messages as documents. Because Firestore has no concept of transactions WAL (at least as Public API) we cannot use transaction log tailing pattern. So that the only option that we have is polling-publisher 模式。但这会导致缺少消息排序,因为我们无法确定事务发件箱集合中的哪些事件首先创建。 请注意,仅应用程序端的文档时间戳不是一个选项,因为它不会告诉我们哪个事务首先提交。

注意:我们可以使用 cloud functions 获取有关事务发件箱集合中新文档的更新,但它也不能保证顺序。

注 2:我们使用 GCP PubSub 作为队列,我们​​在其中传播来自事务发件箱集合的事件。

问题是:GCP Firestore 中是否有任何我们遗漏的功能可以帮助我们按照在 Firestore 集合中创建事件的相同顺序将事件传播到 PubSub 主题?

根据 Firestore documentation, when your system creates a document, you can attach in it a server timestamp。此时间戳可以帮助您在基于创建的文档中建立顺序:

Important: Unlike "push IDs" in the Firebase Realtime Database, Cloud Firestore auto-generated IDs do not provide any automatic ordering. If you want to be able to order your documents by creation date, you should store a timestamp as a field in the documents

下一步将是在 Cloud Function that publishes documents to Pub/Sub based on the timestamp. The order of publishing messages to Pub/Sub and the order in which subscribers received them can be preserved by using Pub/Sub ordering. Pub/Sub ordering is based on an ordering key 中创建逻辑,将多个消息与一个实体相关联,并 Pub/Sub 根据发布顺序对交付进行排序。

根据您对按时间顺序排列的交易发件箱的要求,这可以实现该目的。