Java – Message Driven Architecture and Horizontal Scaling

javamessage-queuemicroservices

During working on a pet project in microservice event driven architecture, I've faced a problem of delivering responses to a client.

enter image description here

Each microservice (API Gateway etc) has many replicas and has it's own loadbalancer (Kubernetes Service).

Use case:

  1. 20 clients (JS App) sends "Register account request"

  2. 10 clients get connected to "API Gateway 1" and 10 – "API Gateway
    2". Gateways hold connection (long polling)

  3. Each API Gateway delegates request processing to Data Processors via
    Apache Kafka, topic "registerAccount"

  4. Data processors are subscribed to "registerAccount" topic.
    onMessage() registers account and push new account's ID back to
    Kafka, topic "newAccountId"

  5. API Gateways receive newAccountId (which one? all of them?)

  6. API Gateways send newAccountId to appropriate client (how can API
    Gateway decide which client must receive this newAccountId?)

The only resolution I've found is to add client id to each message and then filter messages.

Have anybody experienced such problem?

Best Answer

The way that you effectively load balance a Consumer in Kafka is that you register each of your client nodes/processes into a single Consumer Group.

Consumers label themselves with a consumer group name, and each record published to a topic is delivered to one consumer instance within each subscribing consumer group. Consumer instances can be in separate processes or on separate machines.

If all the consumer instances have the same consumer group, then the records will effectively be load balanced over the consumer instances.

If all the consumer instances have different consumer groups, then each record will be broadcast to all the consumer processes.

[Source] https://kafka.apache.org/intro

This is rather basic Client configuration. There is no concept of a "Message Queue" in Kafka, however you can reliably handle transaction based message driven events in this way.

Related Topic