💻 Code Example
Kafka Producer (Node.js)
// services/order/OrderService.ts
import { Kafka } from 'kafkajs';
const kafka = new Kafka({ brokers: ['localhost:9092'] });
const producer = kafka.producer();
export class OrderService {
async placeOrder(orderData: CreateOrderDTO) {
// 1. 주문 생성 (도메인 로직)
const order = Order.create(orderData);
await this.orderRepository.save(order);
// 2. 이벤트 발행 (비동기)
await producer.send({
topic: 'order-events',
messages: [{
key: order.id,
value: JSON.stringify({
type: 'OrderPlaced',
data: {
orderId: order.id,
customerId: order.customerId,
items: order.items,
totalAmount: order.totalAmount,
},
occurredAt: new Date().toISOString(),
}),
}],
});
return order;
}
}
Kafka Consumer
// services/notification/NotificationConsumer.ts
import { Kafka } from 'kafkajs';
const kafka = new Kafka({ brokers: ['localhost:9092'] });
const consumer = kafka.consumer({ groupId: 'notification-service' });
async function startConsumer() {
await consumer.connect();
await consumer.subscribe({ topic: 'order-events', fromBeginning: false });
await consumer.run({
eachMessage: async ({ topic, partition, message }) => {
const event = JSON.parse(message.value!.toString());
switch (event.type) {
case 'OrderPlaced':
await sendOrderConfirmationEmail(event.data);
break;
case 'OrderShipped':
await sendShippingNotification(event.data);
break;
}
},
});
}
startConsumer();
AWS EventBridge + Lambda
// 이벤트 발행
import { EventBridge } from '@aws-sdk/client-eventbridge';
const eventBridge = new EventBridge({});
export async function publishOrderEvent(order: Order) {
await eventBridge.putEvents({
Entries: [{
Source: 'com.myapp.orders',
DetailType: 'OrderPlaced',
Detail: JSON.stringify({
orderId: order.id,
customerId: order.customerId,
totalAmount: order.totalAmount,
}),
EventBusName: 'default',
}],
});
}
// Lambda Consumer (이벤트 핸들러)
export const handler = async (event: any) => {
const orderEvent = event.detail;
// 재고 차감 처리
await inventoryService.decreaseStock(orderEvent.items);
return { statusCode: 200 };
};
Event schema definition
// shared/events/OrderEvents.ts
export interface DomainEvent {
eventId: string;
eventType: string;
aggregateId: string;
occurredAt: string;
version: number;
}
export interface OrderPlaced extends DomainEvent {
eventType: 'OrderPlaced';
data: {
orderId: string;
customerId: string;
items: Array<{
productId: string;
quantity: number;
unitPrice: number;
}>;
totalAmount: number;
shippingAddress: string;
};
}
export interface OrderCancelled extends DomainEvent {
eventType: 'OrderCancelled';
data: {
orderId: string;
reason: string;
cancelledBy: string;
};
}
💬 Real-world conversation examples
👨💼 PM
"When an order is completed, notifications, inventory deduction, and point accrual all have to be linked, but if one part is slow, won't the whole thing slow down?"
👩💻 Backend developer
"You can handle it asynchronously with event-driven architecture. The order service only publishes an OrderPlaced event and responds immediately. The notification, inventory, and points services each subscribe to the event and process it independently."
👨💻 Junior developer
"What happens if processing an event fails? What if the order goes through but the points aren't credited?"
👩💻 Senior developer
"We set up a Dead Letter Queue (DLQ) and a retry policy. Failed events go to the DLQ, and we reprocess them later or get notified. We accept Eventual Consistency."