Search code examples
apache-kafkamessagingspring-kafka

One to One and Group Messaging using Kafka


As Kafka has a topic based pub-sub architecture how can I handle One-to-One and Group Messaging part of web application using Kafka? I am using SpringBoot+Angular stack and Docker Kafka server.


Solution

  • I'll write another answer here. Based on my experience with the chatting service. You only need one topic for all the messages. Using a well designed Message body.

    public class Message {
     private String from; // user id
     private String to;  // user id or group id
    }
    

    Then you can create like 100 partitions for this topic and create two consumers to consume them (50 partitions for one consumer in the beginning). Then if your system reaches the bottleneck, you can easier scale X more consumers to handle the load.

    How to do distribute the messages in the consumer. I used to send the messages to the Mobile app, so all the app has a long-existing connection to the server, and the server sends the messages to the app by that channel. For group chat, I create a Redis cache to store all the active users in the group, so I can easier get the users who belong to this group, send them the messages.

    And another thing, Kafka stateless, means Kafka doesn't de-coupled from the business logic, only acts as a message system, transfers the messages. If you connect your business logic to Kafka, like create a topic "One-to-One" and delete some after they finished, Kafka will be very messy.