Chapter 9

The Unbreakable Promise: Data Consistency with Kafka

Subhash Choudhary · 11 min read

We had done it. We had performed our first successful surgery on the monolith. Our new, independent storefront-service was live, fast, and scaling beautifully. The Strangler Fig Pattern had given us a safe, repeatable process for the future. For a brief moment, it felt like we had unlocked the secret to managing our growing complexity.

But in the world of distributed systems, solving one problem often reveals a deeper, more fundamental one lurking beneath. Our services were now separate entities, living in different buildings. The simple telephone line we had set up between them-our clever but fragile cache invalidation system-was about to snap under the first real sign of pressure, showing us that communication is not just a feature, but the very foundation of a microservices architecture.

Part 1: The Flaky Listener

Life with our first microservice was good. The storefront team could deploy changes without fear of breaking the payment system, and the core API team was happy to have the massive storefront traffic handled by a separate fleet of servers. The separation was working.

The linchpin holding our data consistency together was the small, standalone Python script we had built in Chapter 7: the "Cache Invalidator." This single script was connected to our master database, constantly LISTENing for NOTIFY messages. When a product price changed, it would hear the message and dutifully delete the correct entry from Redis.

For a few weeks, it worked flawlessly. But then, the glitches started.

One afternoon, a seller called support, frustrated. "I've been trying to run a flash sale for the last hour! I keep changing the price of my main product, but my customers are all seeing the old price. I'm losing all the momentum!"

We jumped into the server logs. We checked the Cache Invalidator script. It had crashed. A temporary network hiccup between the script and the database had caused the connection to drop, and the script hadn't automatically recovered. It had been silently dead for over an hour. During that time, every single product update made by our sellers had failed to invalidate the cache. Our stores were filled with stale data.

We restarted the script, and the problem was solved, but the damage was done. We had a single point of failure.

Identifying the Problem: A System Built on a Prayer

The incident exposed the fundamental weakness of our event-driven system. The LISTEN/NOTIFY mechanism was a clever feature of Postgres, but it was not a robust, production-grade messaging system.

Our system was built on the hope that a single, fragile script would stay online forever. This was not engineering; it was prayer.

We realized we needed to replace our simple telephone line with a full-blown, industrial-strength postal service. We needed a system that could guarantee message delivery, allow multiple recipients, and keep a record of every message sent. We needed a real message bus.

Part 2: The Postal Service vs. The Newspaper

We knew we needed a message bus, a reliable way to send information from one service to another. But as we started researching, we realized there were two fundamentally different philosophies for how to build such a system: the traditional Message Queue and the more modern Distributed Log.

Choosing between them was a critical decision that would shape the future of our entire architecture.

Technical Deep Dive: Message Queues vs. A Distributed Log

This is a crucial concept in modern system design, so let's break it down.

1. The Message Queue (e.g., RabbitMQ): The Postal Service

A traditional message queue works like a post office or a shared to-do list.

This model is great for distributing tasks. It guarantees that a specific job will be done by one worker. But its key characteristic is that the message is ephemeral. Once consumed, it's gone.

2. The Distributed Log (e.g., Apache Kafka): The Newspaper

A distributed log like Apache Kafka works on a completely different principle. It's not a post office; it's a newspaper publisher.

This was the lightbulb moment for us. Our problem wasn't just about telling one service to invalidate a cache. We were starting to see a future where many different parts of our system would need to react to the same events. When an order is placed, we need to:

The newspaper (Kafka) model was a perfect fit for this one-to-many communication pattern. Its durability (the newspaper doesn't get destroyed after being read) gave us the reliability we craved. If our Cache Invalidator crashed, the product_updates articles would just pile up safely in the newspaper. When the service came back online, it could just pick up the newspaper and start reading from where it left off, without missing a single update.

We had found our solution. We were going to build Dukaan's central nervous system on Apache Kafka.

Technical Deep Dive: Kafka as Dukaan's Central Nervous System

We ripped out the fragile LISTEN/NOTIFY system and began integrating Kafka. To do that, we had to understand its core components.

We had chosen our new foundation. The next step was the implementation: to officially retire our flaky listener and make our monolith a full-time journalist, publishing every important event to our new, indestructible, central newspaper.

Part 3: The Implementation and the New Reality

We had our new blueprint. We were going to replace our flimsy telephone line with a robust, central nervous system powered by Apache Kafka. The next step was the actual surgery: ripping out the old, fragile listener and wiring our entire application into this new, powerful message bus.

Technical Deep Dive: The Implementation

Step 1: Setting up the Kafka Cluster

Kafka is a complex, distributed system. In the long run, we would learn to host and manage it ourselves. But in the beginning, our goal was speed and reliability, not becoming Kafka experts. So, we made a strategic decision: we used a managed Kafka service.

Services like Confluent Cloud or Aiven allow you to spin up a production-ready, fault-tolerant Kafka cluster with a few clicks. They handle all the difficult parts-backups, monitoring, and failure recovery-for a monthly fee. This was a crucial lesson: in the early days of adopting a complex technology, lean on managed services. It allows your team to focus on using the tool, not just keeping it alive. We had our Kafka "newspaper press" up and running in under an hour.

Step 2: The Magic of Change Data Capture (CDC) with Debezium

Now, how would we get our monolith to publish articles to our new newspaper?

The naive approach would be to go through our entire Django codebase and sprinkle kafka_producer.send() commands everywhere. After every product.save(), we'd add a line to send a Kafka message. This would have been a nightmare. It would clutter our code, and a developer could easily forget to add it in a new feature, leading to data inconsistency.

Instead, we used a magical tool called Debezium.

Debezium is an open-source Change Data Capture (CDC) platform. To understand what it does, let's go back to our library analogy.

This was revolutionary for us. Our monolith application didn't even need to know that Kafka existed. We made zero changes to our application's write logic. We just kept saving data to our PostgreSQL database as we always had. Debezium worked in the background, completely independently, watching the database's WAL and faithfully publishing every single change to our Kafka topics. This completely decoupled our application from our messaging system. It was cleaner, more reliable, and impossible for a developer to forget.

Step 3: Rewriting the Consumer

The final step was to upgrade our Cache Invalidator service. This was simple. We removed all the old, complex code for connecting directly to Postgres and listening for notifications. We replaced it with a standard, battle-tested Kafka consumer library.

The new service simply subscribed to the product_updates topic (which was now being reliably populated by Debezium). When a message came in, it would read the store_id from the message payload and fire off the redis_client.del() command. Thanks to Kafka's consumer groups, we could now run two or three instances of this service at the same time. If one crashed, the others would seamlessly pick up the slack. Our single point of failure was gone.

The New Blueprint

Our data consistency architecture was now robust, scalable, and elegant. The flow was completely different.

Monolith App -> Master DB (WAL) -> Debezium -> Kafka Topic -> Consumer Service(s) -> Redis

The application writes to the database, and the rest of the system reacts to that event, with Kafka and Debezium acting as the indestructible transport layer.

The New Problem: Operational Complexity

We had solved our data consistency problem. Our system was now more reliable than ever. But our architecture diagram had a new, big, complicated box in it. We had introduced a stateful, distributed system into the heart of our operations.

Kafka is incredibly powerful, but it's not magic. It's a complex piece of infrastructure that needs to be managed and monitored. We now had to worry about new things:

We had traded the fragility of our old system for the operational complexity of the new one. Our simple house was now a complex estate with its own power plant. The power plant is far more reliable, but it requires skilled engineers to maintain it. This was a necessary trade-off, the price of admission for building a true microservices architecture.

Key Takeaways

  • A simple messaging system is a single point of failure. For reliable communication between services, you need a durable, persistent event log like Apache Kafka.
  • Change Data Capture (CDC) is a powerful pattern. Using tools like Debezium to stream changes directly from your database log is far more reliable and decouples your application code from your messaging system.
  • Use managed services for complex infrastructure in the beginning. Focus on using the new technology to solve your business problem, not on the low-level details of keeping it online.
  • Every powerful tool you add to your stack increases its operational complexity. Be prepared to invest in the monitoring and expertise required to manage the new systems you introduce.
  • With a central nervous system in place, you now have a foundation. This reliable event stream is the key that unlocks the ability to safely break apart the rest of the monolith into a true, scalable microservices architecture.