Event-driven architecture decouples microservices by processing asynchronous event streams rather than synchronous HTTP requests.
Kafka Consumer Implementation in Node.js
const { Kafka } = require('kafkajs');
const kafka = new Kafka({
clientId: 'order-service',
brokers: ['localhost:9092']
});
const consumer = kafka.consumer({ groupId: 'order-processing-group' });
const run = async () => {
await consumer.connect();
await consumer.subscribe({ topic: 'user-orders', fromBeginning: true });
await consumer.run({
eachMessage: async ({ topic, partition, message }) => {
const order = JSON.parse(message.value.toString());
console.log(`[Partition ${partition}] Processing Order ID: ${order.id}`);
},
});
};
run().catch(console.error);