74

We have a micro-services architecture, with Kafka used as the communication mechanism between the services. Some of the services have their own databases. Say the user makes a call to Service A, which should result in a record (or set of records) being created in that service’s database. Additionally, this event should be reported to other services, as an item on a Kafka topic. What is the best way of ensuring that the database record(s) are only written if the Kafka topic is successfully updated (essentially creating a distributed transaction around the database update and the Kafka update)?

We are thinking of using spring-kafka (in a Spring Boot WebFlux service), and I can see that it has a KafkaTransactionManager, but from what I understand this is more about Kafka transactions themselves (ensuring consistency across the Kafka producers and consumers), rather than synchronising transactions across two systems (see here: “Kafka doesn't support XA and you have to deal with the possibility that the DB tx might commit while the Kafka tx rolls back.”). Additionally, I think this class relies on Spring’s transaction framework which, at least as far as I currently understand, is thread-bound, and won’t work if using a reactive approach (e.g. WebFlux) where different parts of an operation may execute on different threads. (We are using reactive-pg-client, so are manually handling transactions, rather than using Spring’s framework.)

Some options I can think of:

  1. Don’t write the data to the database: only write it to Kafka. Then use a consumer (in Service A) to update the database. This seems like it might not be the most efficient, and will have problems in that the service which the user called cannot immediately see the database changes it should have just created.
  2. Don’t write directly to Kafka: write to the database only, and use something like Debezium to report the change to Kafka. The problem here is that the changes are based on individual database records, whereas the business significant event to store in Kafka might involve a combination of data from multiple tables.
  3. Write to the database first (if that fails, do nothing and just throw the exception). Then, when writing to Kafka, assume that the write might fail. Use the built-in auto-retry functionality to get it to keep trying for a while. If that eventually completely fails, try to write to a dead letter queue and create some sort of manual mechanism for admins to sort it out. And if writing to the DLQ fails (i.e. Kafka is completely down), just log it some other way (e.g. to the database), and again create some sort of manual mechanism for admins to sort it out.

Anyone got any thoughts or advice on the above, or able to correct any mistakes in my assumptions above?

Thanks in advance!

Yoni Gibbs
  • 6,518
  • 2
  • 24
  • 37
  • Any transaction management is tied to the `Thread`. It is just impossible to include DB into the Kafka TX, if they are on different thread. You can take a look into the `ChainedKafkaTransactionManager`, but that still is about Spring transactions. Also you can take a look into the Reactor Kafka, if everything is reactive in your project: https://github.com/reactor/reactor-kafka – Artem Bilan Sep 06 '18 at 16:27
  • Thanks. So presumably the transaction handling in reactor kafka is just for kafka transactions, between producers and consumers, and cannot be synchronised in any way with a DB transaction? – Yoni Gibbs Sep 06 '18 at 18:39
  • Well, you can register `TransactionSynchronization` with the DB TX Manager. See `TransactionSynchronizationManager`, although I don't know how it is going to help you since you worry about reactive and non-single thread execution... – Artem Bilan Sep 06 '18 at 18:44
  • Thanks very much. I'll take a look at those classes. With reactive-pg-client the thread you initiate things on isn't necessarily what it completes on, hence the question about threading. – Yoni Gibbs Sep 06 '18 at 19:27
  • 1
    Just to avoid describing a solution you don't need: Do you really have the need to make sure that the Kafka message has been sent before committing your data to db or is it sufficient that you can ensure that it'll be sent (in other words: you can be sure that the message will be in Kafka soon after the data is committed)? – Jonas Dec 28 '18 at 11:42
  • 2
    Thanks @Jonas. The order doesn't matter us. Things just need to be atomic: either BOTH the DB and Kafka need to be updated, or NEITHER of them get updated. The CDC approach using Debezium is what we've gone with but it would be interesting to hear other options if you have them. – Yoni Gibbs Dec 28 '18 at 16:24
  • @YoniGibbs Now suppose we first successfully publish to kafka, then after that DB update failes.How to handle this scenerio ? – Udit Kumawat Mar 31 '20 at 02:01
  • I don't think you can handle it (nicely). That's exactly why we didn't use this "double-write" approach. We only write to the DB (in a normal DB transaction), and let Debezium report that to Kafka when the DB commits. See the answer about Debezium below. – Yoni Gibbs Mar 31 '20 at 06:24
  • What about a scenario in which you successfully committed to the database and then your app crashes before the producer even sends the messeges to kafka? I am looking for a solution to this, so no messages are lost? – Yoni Mar 04 '21 at 13:43
  • @Yoni, that's still as above, I think: it's this "double-write" that we wanted to avoid, for the exact problem you describe. CDC (e.g. using Debezium) is one solution to this. – Yoni Gibbs Mar 04 '21 at 15:09

5 Answers5

37

I'd suggest to use a slightly altered variant of approach 2.

Write into your database only, but in addition to the actual table writes, also write "events" into a special table within that same database; these event records would contain the aggregations you need. In the easiest way, you'd simply insert another entity e.g. mapped by JPA, which contains a JSON property with the aggregate payload. Of course this could be automated by some means of transaction listener / framework component.

Then use Debezium to capture the changes just from that table and stream them into Kafka. That way you have both: eventually consistent state in Kafka (the events in Kafka may trail behind or you might see a few events a second time after a restart, but eventually they'll reflect the database state) without the need for distributed transactions, and the business level event semantics you're after.

(Disclaimer: I'm the lead of Debezium; funnily enough I'm just in the process of writing a blog post discussing this approach in more detail)

Here are the posts

https://debezium.io/blog/2018/09/20/materializing-aggregate-views-with-hibernate-and-debezium/

https://debezium.io/blog/2019/02/19/reliable-microservices-data-exchange-with-the-outbox-pattern/

Yan Khonski
  • 12,225
  • 15
  • 76
  • 114
Gunnar
  • 18,095
  • 1
  • 53
  • 73
  • That being said, I'm curious about the business level semantics of your events would be, apart from representing a join of multiple tables? Perhaps you could come to our [mailing list](https://groups.google.com/forum/#!forum/debezium) and provide some details of your use case? We'd like to better understand these sorts of use cases and have planned to provide better support for them. Thanks! – Gunnar Sep 07 '18 at 06:24
  • 1
    Thanks Gunnar. Interestingly, I've just been reading [this](https://www.confluent.io/blog/messaging-single-source-truth/) which suggests the CDC-style approach you recommend (though without your "events table" suggestion). And yes, you're right that it basically is data based on joins from multiple tables that are considered as a single business-significant entity, which we'd probably want to report to Kafka. We're in R&D stage just now but once we have more details we'll join your mailing list and post more details there. Thanks again! – Yoni Gibbs Sep 07 '18 at 12:47
  • Also, I'd be very interested to read your upcoming blog post: maybe you could post a link here when it's ready? – Yoni Gibbs Sep 07 '18 at 12:49
  • 6
    If anyone's interested, Gunnar's post is now [here](https://debezium.io/blog/2018/09/20/materializing-aggregate-views-with-hibernate-and-debezium/) – Yoni Gibbs Sep 24 '18 at 17:09
  • 3
    We've published another, more generic, post about this pattern ("outbox pattern") [a while ago](https://debezium.io/blog/2019/02/19/reliable-microservices-data-exchange-with-the-outbox-pattern/) on the Debezium blog. – Gunnar Mar 29 '19 at 14:34
20

first of all, I have to say that I’m no Kafka, nor a Spring expert but I think that it’s more a conceptual challenge when writing to independent resources and the solution should be adaptable to your technology stack. Furthermore, I should say that this solution tries to solve the problem without an external component like Debezium, because in my opinion each additional component brings challenges in testing, maintaining and running an application which is often underestimated when choosing such an option. Also not every database can be used as a Debezium-source.

To make sure that we are talking about the same goals, let’s clarify the situation in an simplified airline example, where customers can buy tickets. After a successful order the customer will receive a message (mail, push-notification, …) that is sent by an external messaging system (the system we have to talk with).

In a traditional JMS world with an XA transaction between our database (where we store orders) and the JMS provider it would look like the following: The client sets the order to our app where we start a transaction. The app stores the order in its database. Then the message is sent to JMS and you can commit the transaction. Both operations participate at the transaction even when they’re talking to their own resources. As the XA transaction guarantees ACID we’re fine.

Let’s bring Kafka (or any other resource that is not able to participate at the XA transaction) in the game. As there is no coordinator that syncs both transactions anymore the main idea of the following is to split processing in two parts with a persistent state.

When you store the order in your database you can also store the message (with aggregated data) in the same database (e.g. as JSON in a CLOB-column) that you want to send to Kafka afterwards. Same resource – ACID guaranteed, everything fine so far. Now you need a mechanism that polls your “KafkaTasks”-Table for new tasks that should be send to a Kafka-Topic (e.g. with a timer service, maybe @Scheduled annotation can be used in Spring). After the message has been successfully sent to Kafka you can delete the task entry. This ensures that the message to Kafka is only sent when the order is also successfully stored in application database. Did we achieve the same guarantees as we have when using a XA transaction? Unfortunately, no, as there is still the chance that writing to Kafka works but the deletion of the task fails. In this case the retry-mechanism (you would need one as mentioned in your question) would reprocess the task an sends the message twice. If your business case is happy with this “at-least-once”-guarantee you’re done here with a imho semi-complex solution that could be easily implemented as framework functionality so not everyone has to bother with the details.

If you need “exactly-once” then you cannot store your state in the application database (in this case “deletion of a task” is the “state”) but instead you must store it in Kafka (assuming that you have ACID guarantees between two Kafka topics). An example: Let’s say you have 100 tasks in the table (IDs 1 to 100) and the task job processes the first 10. You write your Kafka messages to their topic and another message with the ID 10 to “your topic”. All in the same Kafka-transaction. In the next cycle you consume your topic (value is 10) and take this value to get the next 10 tasks (and delete the already processed tasks).

If there are easier (in-application) solutions with the same guarantees I’m looking forward to hear from you!

Sorry for the long answer but I hope it helps.

Jonas
  • 494
  • 4
  • 7
  • 1
    CDC is the best approach but when you don't want the complication and when events are huge in number, you can reduce polling (SPOF risk) size by letting Async Kafka do its job with "full ack=all guarantees" and when Kafka Publisher responds in its callback at its own time (within timeout), you can updates a database column that Kafka message has been published successfully. The "polled data to find messages not published" will then go down significantly assuming, there is very limited data loss only when JVM crashes or message is not published. – kisna May 21 '20 at 00:17
  • 2
    This is a very robust solution . Regarding the "exactly-once" semantics: simply put I don't think that is a concern. Ideally your consumers are already coding defensively against the possibility of duplicate messages (duplicates can occur naturally under variable network conditions as per kafka's documentation). – mattbrosenberg Oct 01 '20 at 13:43
12

All the approach described above are the best way to approach the problem and are well defined pattern. You can explore these in the links provided below.

Pattern: Transactional outbox

Publish an event or message as part of a database transaction by saving it in an OUTBOX in the database. http://microservices.io/patterns/data/transactional-outbox.html

Pattern: Polling publisher

Publish messages by polling the outbox in the database. http://microservices.io/patterns/data/polling-publisher.html

Pattern: Transaction log tailing

Publish changes made to the database by tailing the transaction log. http://microservices.io/patterns/data/transaction-log-tailing.html

Huseyin Yagli
  • 9,896
  • 6
  • 41
  • 50
user3107673
  • 423
  • 4
  • 9
1

Debezium is a valid answer but (as I've experienced) it can require some extra overhead of running an extra pod and making sure that pod doesn't fall over. This could just be me griping about a few back to back instances where pods OOM errored and didn't come back up, networking rule rollouts dropped some messages, WAL access to an aws aurora db started behaving oddly... It seems that everything that could have gone wrong, did. Not saying Debezium is bad, it's fantastically stable, but often for devs running it becomes a networking skill rather than a coding skill.

As a KISS solution using normal coding solutions that will work 99.99% of the time (and inform you of the .01%) would be:

  • Start Transaction
  • Sync save to DB
  • -> If fail, then bail out.
  • Async send message to kafka.
  • Block until the topic reports that it has received the message.
  • -> if it times out or fails Abort Transaction.
  • -> if it succeeds Commit Transaction.
WhiteleyJ
  • 1,393
  • 1
  • 22
  • 29
1

I'd suggest to use a new approach 2-phase message. In this new approach, much less codes are needed, and you don't need Debeziums any more.

https://betterprogramming.pub/an-alternative-to-outbox-pattern-7564562843ae

For this new approach, what you need to do is:

  1. When writing your database, write an event record to an auxiliary table.
  2. Submit a 2-phase message to DTM
  3. Write a service to query whether an event is saved in the auxiliary table.

With the help of DTM SDK, you can accomplish the above 3 steps with 8 lines in Go, much less codes than other solutions.

msg := dtmcli.NewMsg(DtmServer, gid).
  Add(busi.Busi+"/TransIn", &TransReq{Amount: 30})
err := msg.DoAndSubmitDB(busi.Busi+"/QueryPrepared", db, func(tx *sql.Tx) error {
    return AdjustBalance(tx, busi.TransOutUID, -req.Amount)
})
app.GET(BusiAPI+"/QueryPrepared", dtmutil.WrapHandler2(func(c *gin.Context) interface{} {
    return MustBarrierFromGin(c).QueryPrepared(db)
}))

Each of your origin options has its disadvantage:

  1. The user cannot immediately see the database changes it have just created.
  2. Debezium will capture the log of the database, which may be much larger than the events you wanted. Also deployment and maintenance of Debezium is not an easy job.
  3. "built-in auto-retry functionality" is not cheap, it may require much codes or maintenance efforts.
yedf
  • 176
  • 5