To expose database change information, it is necessary to monitor database data changes, then publish the information to a message queue, and open the corresponding ports for other systems to subscribe.
The relevant video sharing link is as follows:
mongo-listener Design Philosophy
Mongo Data Change Monitoring
Regarding changes to database information—or, more precisely, data heterogeneity—this refers to the scenario where, when the data in one data source changes, another data source can receive the related change information and process it accordingly. This ensures that two data stores, which may not be physically consistent, remain logically identical. Although this consistency involves a time delay, it is acceptable in most cases. For subscribing to data change events in common databases, this is typically achieved through the database's binlog. For example, MySQL and PostgreSQL provide a listen method; users can configure the relevant listening information based on the connection and invoke the listen method to retrieve the expected data changes. However, since MongoDB does not have a binlog, it requires listening to the database's oplog to achieve this. MongoDB itself exposes the corresponding functionality via the watch method, which allows monitoring data changes in the database. MySQL does not provide such an API for users to call directly. To implement this functionality, one must simulate a replica node to receive binlog synchronization from the primary node and parse the binlog to extract change information. Implementing this typically requires the use of third-party tools, such as Canal or Maxwell.
By comparing the data heterogeneity and the methods for retrieving data change information across mysql, pgsql, and mongo, we can observe that pgsql and mongo primarily abstract the relevant records of change information into an API. This API is essentially a wrapper around an oplog, which functions similarly to binlog, combined with related operational APIs. This approach integrates the subscription to data changes directly into the database's core APIs. Users are not required to introduce additional components or rely on non-standardized components to achieve the final functionality. Of course, this approach may place some burden on the database itself. After all, operation logs such as oplog and binlog records are typically only replicated and executed during master-slave synchronization. Opening up this functionality means that the parsing work is shifted to the database itself, whereas it may have previously been handled by third-party components. Consequently, this could impose a certain load on the database. These are all factors that need to be considered. In software design, the transfer of functionality is a matter that warrants careful trade-off analysis, because functionality is not just a matter of implementation; the ownership of the implementation can also lead to various pros and cons. For instance, implementing it within the database itself may place a certain load on the database, but it may be more convenient for users. If it is not implemented within the database itself, the load on the database may be relatively smaller, but users would need to do more work. In other words, when considering the transfer of functionality, one must carefully weigh the associated pros and cons, determine whether the transfer is worthwhile, and ensure that the transferred functionality can still meet the requirements.
Is a single service good?
Below, we will discuss the related issues regarding mongo-listener.
First, should this functionality be implemented as a standalone service, or distributed across various services? If implemented as a standalone service, we only need to ensure that this specific service is highly available; consequently, the entire mongo-listener service will be highly available. This is because a standalone service represents the overall mongo-listener functionality, meaning the focus is entirely on the standalone service itself. If distributed across various services, ensuring the high availability of mongo-listener would require ensuring the high availability of each of its distributed host services. This is more complex, implying that the high availability of the entire mongo-listener depends on the high availability of multiple host services. To focus solely on the availability of a single mongo-listener service and to avoid introducing excessive complexity into the implementation, the approach of writing it as a standalone service has been chosen.
Partial and Complete
Next, we will discuss the functionality of mongo-listener, how to implement it, and how to ensure high availability. We will use a simple example to illustrate monitoring documents within a collection, specifically focusing only on data insertion. The relevant operations involve connecting to the database, obtaining the operation instance for the corresponding entity, and initiating a watch monitor. watch returns a corresponding stream, which can be understood as a network connection; a stream is an abstraction of network data. Subsequently, we bind relevant events to the stream. Here, the primary focus is the change event, which returns the corresponding information changes. These changes include not only the content after the change but also a crucial marker. This marker is a unique token, which is unique and ordered throughout the data change process. This means that obtaining any token reveals the specific point in time associated with that token, and using this token allows you to continue subscribing to messages from that point onward. You can think of this token as a marker representing the sequence of data changes over time. In this way, we not only obtain the entity information of the data change but also receive a token. In the official documentation, this token is called resumeToken. Considering that resumeToken allows you to retrieve the value at a certain moment and continue consuming accumulated messages based on the timestamp of the resumeToken after a certain period, ideally, when our program crashes, we should save the latest resumeToken. Upon the next startup, we check this value and initialize the watch based on this resumeToken. Therefore, this value is critical for the high availability of the program. Once the change information is obtained, how is it delivered?
Confirming the Introduction of buffer
When retrieving change information and delivering it to the queue, several issues require attention. Pay close attention to data input, as the uncertainty of inputs introduces uncontrollable factors that affect system stability. External requests are also considered a form of input. This is a classic producer-consumer model. For instance, consider whether there is a significant rate disparity between message reception and consumption. A large disparity implies message accumulation. Since messages have size, accumulation inevitably occurs within the program, manifesting as excessive memory usage, potentially leading to OOM. From the perspective of message production and consumption rates, the ultimate source of message production is mongo. Although the watch feature can limit message frequency—meaning the rate at which mongo sends related messages to subscribers decreases—enabling this feature implies that the program's message processing performance may not reach its maximum potential. The best way to solve this problem is to find a buffer to cache these messages. The buffer should not be the program itself, as a large accumulation of messages will cause memory issues. Moreover, the speed at which messages enter the cache should ideally match the production speed. These are the key points. Therefore, messages should not be directly consumed from the message queue here, as the speed at which the message queue delivers messages is difficult to match or keep close to the production speed. Here, redis is chosen as a buffer for caching. Subsequently, the redis queue is subscribed to, and messages are delivered to the message queue incrementally. The choice of redis is based on two main considerations. First, the delivery speed is absolutely faster than kafka. The network environment of kafka may affect delivery speed, whereas redis here is entirely local and does not need to expose any external ports, participating as an internal dependency. Second, it is the persistence of redis. Essentially, choosing redis or an internal program buffer will both lead to increased memory usage. However, redis can limit resources through system isolation. In the face of a sudden program crash, large amounts of message accumulation are completely helpless, and a large buffer will be directly lost. In contrast, redis can ensure message accumulation through persistence. However, it is important to note that redis persistence is asynchronous, meaning redis persistence occurs in the background. By using redis as an intermediate buffering middleware, the only remaining task for the current program is to deliver the final messages to the message queue or distributed queue. The implementation is also relatively simple, but the delivery method and operations differ due to the requirements for system availability and business correctness. The core of availability revolves around persistence, while the core of business correctness revolves around ordering.
Save?
Overall, mongo-listener needs to ensure the persistence of the resumeToken so that upon the next startup, it can continue unsubscribing from messages prior to the previously established time point. Determining exactly what this time point is requires obtaining either the resumeToken of the first message that has not yet been persisted or the already persisted resumeToken. Once this is achieved, the service can seamlessly resume unsubscribing from messages prior to that time point. Of course, the last persisted message must be excluded if it is received again. Regarding message persistence, both Redis and the message queue need to have persistence enabled. Therefore, if the service crashes, the last message persisted to Redis will necessarily be the last message successfully delivered to Redis. This also raises the issue of delivery ordering, which is temporarily set aside. Consequently, every time a message is successfully delivered to Redis, the resumeToken should be updated and persisted. This persistence operation is relatively costly; in practice, it ultimately executes an update operation, and the actual persistence work is scheduled to run periodically by a timer. Naturally, this timing means that the persisted resumeToken will be equal to or earlier than the resumeToken of the last persisted message in the timeline. The consequence of this issue is that a few messages at the end are prone to duplication when the service is suspended and restarted. Therefore, deduplication logic must be considered. The method for deduplication involves maintaining a list that stores the resumeTokens of all messages from the last persistence event to the next one. This discussion does not cover messages already delivered to the message queue, because, thanks to Redis handling message accumulation, as long as the flow from messages to Redis and from Redis to the message queue is handled correctly, there will be no message loss. The middleware the program interacts with most directly is Redis. Delivery to the message queue is entirely driven by Redis message notifications. The program’s persistence and high availability are primarily centered around the resumeToken.
Redis persistence requires enabling the relevant configuration and mounting the corresponding volume. Otherwise, when a container is deleted and recreated, if no volume with the relevant data storage is mounted, all keys will still disappear. Further details about the related configuration and volume operations are omitted here.
The message queue uses Kafka. The main operations for persistence involve mounting data to the corresponding volume, configuring relevant persistence policies, and setting related configurations. We will not elaborate further on the configuration details or volume operations here. For Kafka, the producer side also requires specific handling to ensure transactional message delivery. This guarantees that messages successfully enter Kafka's persistence process and are fully persisted, rather than being in a state where they have entered Kafka but have not yet been persisted. If Kafka crashes in the latter scenario, it results in message loss. We will not go into further detail here; we will share more about Kafka's message integrity later.
Persistence ensures high availability for the overall system. First, this guarantees the high availability of the application itself: even if it crashes, as long as it can restart, it can resume subscriptions from its previous state. During the subscription process, the saved resumeToken may not be the most up-to-date one. In this case, we check the list maintained in Redis. If the token exists, we do not proceed with further delivery to Redis; if it does not exist, we proceed with delivery. Once messages are persisted in Redis, they can be delivered at a controlled pace while ensuring delivery order. Atomic message delivery is used to guarantee that no messages are lost.
Ordered? Unordered?
There are several issues to consider regarding sequences. The information initially received by the program is necessarily ordered. It is not necessary to guarantee that all subsequent information remains ordered. If ordering is required, how should it be guaranteed? The answer to whether ordering must always be guaranteed is negative. For some single events, such as additions or deletions, it may not be necessary to guarantee ordering. However, this is not necessarily the case for modifications, as it depends on the content of the modification itself. This means the program can switch between ordered and unordered states and can be configured accordingly.
Below is an analysis of the design related to ordering. First, during the process of delivering messages to redis, local network communication is involved. Although common network blocking issues may not occur, ordering still cannot be guaranteed. This issue is left pending for further consideration later.
If the delivery of each message is maintained in a queue, starting delivery from the first item in the queue and continuing to the next only after a successful delivery, this approach can indeed guarantee both ordering and successful delivery. However, performance may not be optimal. Is it possible to merge processing when there is a large volume of items in the queue? For example, sending concurrently those items in the sequence that can be merged or do not have strict ordering requirements is one potential improvement idea. There may be other ways to modify this approach. This issue is also left pending.
For delivery from redis to kafka, if ordering must be guaranteed, it is sufficient to process messages one by one after receiving the message notifications from redis. The issue of merging still exists in this context. The strategy used for handling messages in redis can basically be reused. At the same time, message merging can be effectively combined with transactions, as transactions, while ensuring persistence, incur relatively high overhead, not only in terms of network connections.
Configuration
The above describes the handling of a simplified model. In reality, many different businesses may need to subscribe, which requires the program to support multiple subscriptions, perform related configurations, and address issues such as program logging, monitoring, and alerts. Monitoring will not be considered for now due to the lack of infrastructure; simple resource limits should serve as a basic safety net. Program logging needs to record relevant states during critical runtime operations. For alerts, we will initially consider integrating a webhook for notifications, as this method is simple and quick. Configuration will cover related pipeline information, resumeToken information, and the destination topic information. The structure will be extended from a single object to an array of objects, and the program logic will be extended to handle arrays using the same processing approach. This "same processing" refers to a single unified logic. In fact, it might be more effective to run different program instances based on different configurations, since there is no relationship between different configurations, and they use different redis and kafka queues. Forcing everything into a single program instance is indeed a bit of a stretch and places considerable pressure on that instance.
Deployment-Related
After completing the implementation of the relevant programs, deploy the orchestration program images and the yml files for the related services. It is important to note that the externally exposed message queue ports require SSL configuration, which can likely be accomplished by configuring nginx. Security considerations are also critical; it is recommended to configure scram for kafka with complex account credentials and to manage permissions for the relevant queues to ensure the security of external access. redis does not require exposing any ports to the host or external networks, as it runs purely as an adjunct to the application, thus not requiring additional security configurations.
Summary
The unresolved issues mentioned above require further consideration. There may still be many shortcomings in the overall trade-offs and design, and there might already be existing solutions available. This section merely presents some preliminary thoughts.
The high availability discussed above is actually not implemented thoroughly enough. The overall design approach is still based on a single-machine mode. In the event of a single machine failure, relevant handling is still required. However, this issue can be addressed through multi-node deployment. The challenge with multi-node deployment is ensuring data consistency across the nodes, which requires further investigation.
Regarding compensation mechanisms, since MongoDB itself supports a limited number of watchable pipelines, it is necessary to add auxiliary services to provide compensation, enabling more flexible data subscriptions such as table joins.
更新 相关视频分享链接
哈哈哈,写的挺好的,居然回复了GPT的评论 :D
得空我再改改
好的, 相关问题我会持续进行改进