🏗️ Architecture

Event-Driven Architecture

Event-Driven Architecture

Event-driven architecture (EDA) is a pattern in which services are loosely coupled around the creation, detection, and consumption of events. It achieves asynchronous communication and scalability through Apache Kafka, RabbitMQ, AWS EventBridge, and others.

📖 Detailed Explanation

Event-Driven Architecture (EDA) is a software design pattern in which system components communicate asynchronously through events. Instead of synchronous API calls (Request-Response), it uses an event publish-subscribe (Pub/Sub) model to achieve loose coupling between services.

Producer
Event publishing
→
Event Broker
Kafka/RabbitMQ
→
Consumer
Event consumption

Key concepts

Advantages of EDA

💻 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."

⚠️ Cautions

Eventual consistency: EDA does not guarantee immediate consistency. After an order, inventory may not be deducted right away. If your business requirements demand strong consistency, consider synchronous calls.

Event ordering: Events may arrive in an order different from the order in which they were published. If ordering matters, use a Kafka partition key or an ordering guarantee mechanism.

Tip: Version your event schemas. If you state the version explicitly, such as v1 and v2, Consumers can migrate gradually.

🔗 Related Terms

📚 Learn More