Kafka phù hợp cho high-throughput event streaming. NestJS có built-in Kafka transport.
Consumer (Microservice):
typescript
// main.ts
app.connectMicroservice<MicroserviceOptions>({
transport: Transport.KAFKA,
options: {
client: { brokers: ['kafka:9092'] },
consumer: { groupId: 'orders-consumer' },
},
});
// Controller
@EventPattern('order.created')
async handleOrderCreated(@Payload() data: OrderCreatedEvent) {
await this.ordersService.process(data);
}Producer (API Gateway):
typescript
ClientsModule.register([{
name: 'KAFKA_SERVICE',
transport: Transport.KAFKA,
options: {
client: { clientId: 'api-gateway', brokers: ['kafka:9092'] },
producer: { allowAutoTopicCreation: true },
},
}])
// Service
this.kafkaClient.emit('order.created', { orderId, userId, items });Kafka patterns: @EventPattern cho pub/sub (fire-and-forget), @MessagePattern cho request-reply.
Dùng Avro schema registry cho type-safe messages trong production.