🏗️ Architecture

Microservices

Microservices Architecture (MSA)

An architecture style that decomposes an application into small, independent services. Each service handles a single business function, can be deployed, scaled, and developed independently, and communicates with others through APIs.

📖 Detailed Explanation

Microservices architecture emerged to overcome the limitations of traditional monolithic architecture. A monolith consists of one huge codebase, which makes deployment and scaling difficult, and a failure in one part affects the entire system. Microservices, by contrast, solve these problems because each service operates independently.

The core principles include the Single Responsibility principle, Loose Coupling, and High Cohesion. Each service has its own database (Database per Service) and does not access other services' data directly, communicating only through APIs.

Inter-service communication is divided into synchronous and asynchronous approaches. The synchronous approach uses REST API or gRPC, while the asynchronous approach communicates in an event-driven manner through message queues (RabbitMQ, Kafka). The asynchronous approach can reduce coupling between services further.

API Gateway acts as a single entry point between clients and microservices. It handles cross-cutting concerns such as authentication, routing, load balancing, and rate limiting. Kong, AWS API Gateway, and Netflix Zuul are representative examples.

Service Mesh is an infrastructure layer that manages communication between services. Tools such as Istio and Linkerd provide traffic management, security, and observability. A sidecar proxy is placed alongside each service to separate network logic from the application code.

💻 Code Example

# 마이크로서비스 예제 - 주문 서비스 (Order Service)
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Optional
import httpx
import asyncio

app = FastAPI(title="Order Service", version="1.0.0")

# 다른 서비스 URL (환경변수로 관리)
USER_SERVICE_URL = "http://user-service:8001"
PRODUCT_SERVICE_URL = "http://product-service:8002"
PAYMENT_SERVICE_URL = "http://payment-service:8003"


class OrderRequest(BaseModel):
    user_id: str
    product_id: str
    quantity: int
    payment_method: str


class Order(BaseModel):
    id: str
    user_id: str
    product_id: str
    quantity: int
    total_amount: float
    status: str


# 서비스 간 통신 - HTTP Client
async def call_service(url: str, timeout: float = 5.0):
    """다른 마이크로서비스 호출 (Circuit Breaker 패턴 적용)"""
    async with httpx.AsyncClient(timeout=timeout) as client:
        try:
            response = await client.get(url)
            response.raise_for_status()
            return response.json()
        except httpx.TimeoutException:
            raise HTTPException(status_code=504, detail="Service timeout")
        except httpx.HTTPStatusError as e:
            raise HTTPException(status_code=e.response.status_code)


@app.post("/orders", response_model=Order)
async def create_order(request: OrderRequest):
    """
    주문 생성 - 여러 마이크로서비스와 협력
    1. 사용자 검증 (User Service)
    2. 상품 정보 조회 (Product Service)
    3. 결제 처리 (Payment Service)
    """
    # 1. 사용자 검증 (User Service 호출)
    user = await call_service(f"{USER_SERVICE_URL}/users/{request.user_id}")
    if not user.get("active"):
        raise HTTPException(status_code=400, detail="User is not active")

    # 2. 상품 정보 조회 (Product Service 호출)
    product = await call_service(f"{PRODUCT_SERVICE_URL}/products/{request.product_id}")
    if product.get("stock", 0) < request.quantity:
        raise HTTPException(status_code=400, detail="Insufficient stock")

    total_amount = product["price"] * request.quantity

    # 3. 결제 처리 (Payment Service 호출)
    async with httpx.AsyncClient() as client:
        payment_response = await client.post(
            f"{PAYMENT_SERVICE_URL}/payments",
            json={
                "user_id": request.user_id,
                "amount": total_amount,
                "method": request.payment_method
            }
        )
        if payment_response.status_code != 200:
            raise HTTPException(status_code=400, detail="Payment failed")

    # 4. 주문 생성 (로컬 DB에 저장)
    order = Order(
        id=f"ORD-{asyncio.get_event_loop().time()}",
        user_id=request.user_id,
        product_id=request.product_id,
        quantity=request.quantity,
        total_amount=total_amount,
        status="CONFIRMED"
    )

    # 5. 이벤트 발행 (비동기 처리를 위해)
    # await publish_event("order.created", order.dict())

    return order


@app.get("/health")
async def health_check():
    """헬스 체크 - Kubernetes liveness/readiness probe용"""
    return {"status": "healthy", "service": "order-service"}


# Circuit Breaker 패턴 구현
class CircuitBreaker:
    def __init__(self, failure_threshold: int = 5, reset_timeout: int = 30):
        self.failure_count = 0
        self.failure_threshold = failure_threshold
        self.reset_timeout = reset_timeout
        self.state = "CLOSED"  # CLOSED, OPEN, HALF_OPEN

    async def call(self, func, *args, **kwargs):
        if self.state == "OPEN":
            raise HTTPException(status_code=503, detail="Circuit breaker is open")

        try:
            result = await func(*args, **kwargs)
            self.failure_count = 0
            self.state = "CLOSED"
            return result
        except Exception as e:
            self.failure_count += 1
            if self.failure_count >= self.failure_threshold:
                self.state = "OPEN"
            raise e
// 마이크로서비스 예제 - 상품 서비스 (Product Service)
const express = require('express');
const axios = require('axios');
const { v4: uuidv4 } = require('uuid');

const app = express();
app.use(express.json());

// 서비스 레지스트리 (실제로는 Consul, Eureka 등 사용)
const SERVICE_REGISTRY = {
    inventory: 'http://inventory-service:8004',
    pricing: 'http://pricing-service:8005'
};

// 인메모리 데이터 (실제로는 각 서비스별 DB 사용)
const products = new Map();

/**
 * 상품 등록 API
 */
app.post('/products', async (req, res) => {
    try {
        const { name, description, category, basePrice } = req.body;

        const product = {
            id: uuidv4(),
            name,
            description,
            category,
            basePrice,
            createdAt: new Date().toISOString()
        };

        products.set(product.id, product);

        // 이벤트 발행 (다른 서비스에 알림)
        await publishEvent('product.created', product);

        res.status(201).json(product);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

/**
 * 상품 조회 API - 여러 서비스 데이터 조합
 */
app.get('/products/:id', async (req, res) => {
    try {
        const product = products.get(req.params.id);
        if (!product) {
            return res.status(404).json({ error: 'Product not found' });
        }

        // 여러 서비스에서 데이터 병렬 조회 (API Composition)
        const [inventory, pricing] = await Promise.all([
            callService(`${SERVICE_REGISTRY.inventory}/stock/${product.id}`),
            callService(`${SERVICE_REGISTRY.pricing}/price/${product.id}`)
        ]);

        // 데이터 조합하여 반환
        res.json({
            ...product,
            stock: inventory?.quantity || 0,
            price: pricing?.currentPrice || product.basePrice,
            discount: pricing?.discount || 0
        });
    } catch (error) {
        // Fallback: 기본 상품 정보만 반환
        const product = products.get(req.params.id);
        res.json({ ...product, stock: 'unavailable', price: product?.basePrice });
    }
});

/**
 * 서비스 간 HTTP 통신 (타임아웃 및 재시도 포함)
 */
async function callService(url, options = {}) {
    const { retries = 3, timeout = 3000 } = options;

    for (let i = 0; i < retries; i++) {
        try {
            const response = await axios.get(url, { timeout });
            return response.data;
        } catch (error) {
            if (i === retries - 1) throw error;
            // 지수 백오프 (Exponential Backoff)
            await new Promise(r => setTimeout(r, Math.pow(2, i) * 100));
        }
    }
}

/**
 * 이벤트 발행 (메시지 큐로 전송)
 */
async function publishEvent(eventType, data) {
    // 실제로는 Kafka, RabbitMQ 등 사용
    console.log(`[Event Published] ${eventType}:`, data);
    // await kafkaProducer.send({ topic: eventType, messages: [{ value: JSON.stringify(data) }] });
}

/**
 * 헬스 체크 엔드포인트
 */
app.get('/health', (req, res) => {
    res.json({
        status: 'healthy',
        service: 'product-service',
        timestamp: new Date().toISOString(),
        uptime: process.uptime()
    });
});

/**
 * Readiness 체크 (의존 서비스 확인)
 */
app.get('/ready', async (req, res) => {
    try {
        // 의존 서비스 헬스 체크
        await Promise.all([
            axios.get(`${SERVICE_REGISTRY.inventory}/health`, { timeout: 1000 }),
            axios.get(`${SERVICE_REGISTRY.pricing}/health`, { timeout: 1000 })
        ]);
        res.json({ status: 'ready' });
    } catch (error) {
        res.status(503).json({ status: 'not ready', error: error.message });
    }
});

const PORT = process.env.PORT || 8002;
app.listen(PORT, () => {
    console.log(`Product Service running on port ${PORT}`);
});
┌─────────────────────────────────────────────────────────────────────────┐
│                        Microservices Architecture                        │
└─────────────────────────────────────────────────────────────────────────┘

                              ┌─────────────┐
                              │   Client    │
                              │  (Web/App)  │
                              └──────┬──────┘
                                     │
                              ┌──────▼──────┐
                              │ API Gateway │  ← 인증, 라우팅, 속도제한
                              │ (Kong/Zuul) │
                              └──────┬──────┘
                                     │
           ┌─────────────────────────┼─────────────────────────┐
           │                         │                         │
    ┌──────▼──────┐          ┌──────▼──────┐          ┌──────▼──────┐
    │   User      │          │   Order     │          │  Product    │
    │  Service    │◄────────►│  Service    │◄────────►│  Service    │
    └──────┬──────┘   REST   └──────┬──────┘   REST   └──────┬──────┘
           │                        │                         │
    ┌──────▼──────┐          ┌──────▼──────┐          ┌──────▼──────┐
    │  User DB    │          │  Order DB   │          │ Product DB  │
    │ (PostgreSQL)│          │ (PostgreSQL)│          │  (MongoDB)  │
    └─────────────┘          └─────────────┘          └─────────────┘
                                    │
                                    │ Events (Kafka)
                                    ▼
           ┌─────────────────────────────────────────────────────┐
           │                   Message Queue                      │
           │                  (Apache Kafka)                      │
           └──────────┬────────────────────────────┬─────────────┘
                      │                            │
               ┌──────▼──────┐              ┌──────▼──────┐
               │  Payment    │              │ Notification│
               │  Service    │              │   Service   │
               └──────┬──────┘              └──────┬──────┘
                      │                            │
               ┌──────▼──────┐              ┌──────▼──────┐
               │ Payment DB  │              │   Redis     │
               └─────────────┘              │  (Cache)    │
                                            └─────────────┘

┌─────────────────────────────────────────────────────────────────────────┐
│ Infrastructure Layer                                                     │
├─────────────────────────────────────────────────────────────────────────┤
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐    │
│  │ Kubernetes  │  │   Istio     │  │ Prometheus  │  │   Jaeger    │    │
│  │ (Container  │  │  (Service   │  │ (Metrics)   │  │ (Tracing)   │    │
│  │  Orchestr.) │  │   Mesh)     │  │             │  │             │    │
│  └─────────────┘  └─────────────┘  └─────────────┘  └─────────────┘    │
└─────────────────────────────────────────────────────────────────────────┘

핵심 패턴:
• API Gateway: 단일 진입점, 횡단 관심사 처리
• Database per Service: 서비스별 독립 데이터베이스
• Event-Driven: 비동기 통신으로 느슨한 결합
• Circuit Breaker: 장애 전파 방지
• Service Discovery: 동적 서비스 위치 탐색
• Distributed Tracing: 요청 흐름 추적

🗣️ Say It Like This in Practice

💬 In an architecture design meeting
"As the order domain becomes more complex, the limitations of the monolith are becoming apparent. If we move to microservices, the order, payment, and shipping teams can each deploy independently, and we can selectively scale out only the services that receive heavy traffic."
💬 In a Tech Stack Discussion
"For synchronous communication between services, gRPC performs better than REST, but for externally exposed APIs, REST has higher compatibility. Between internal services, using Kafka for event-driven asynchronous communication can reduce coupling further."
💬 In an incident response meeting
"The reason the order service also stopped when the payment service went down was that there was no Circuit Breaker. You need to stop failure propagation with Hystrix or Resilience4j, and add timeout and fallback logic."

⚠️ Cautions & Best Practices

❌
Complexity of Distributed Transactions

It is difficult to guarantee ACID for transactions spanning multiple services. You need to implement compensating transactions with the Saga pattern, or accept Eventual Consistency.

❌
Adopting Microservices Too Early

In the early stages when domain boundaries are unclear, microservices cause excessive complexity. Start with a monolith and split it up after the domains become clear.

❌
Data Sharing Anti-Pattern

Sharing a database between services creates tight coupling. Each service should have its own DB, and when data is needed, synchronize it through APIs or events.

✅
Best Practices

Define service boundaries with Domain-Driven Design (DDD), deploy with containers (Docker/K8s), use centralized logging/monitoring (ELK, Prometheus), and debug with distributed tracing (Jaeger).

🔗 Related Terms

📚 Learn More