🏗️ Architecture

Microservices

Microservices Architecture (MSA)

An architectural style composed of small, independent services. Each service handles a specific business function and can be developed, deployed, and scaled independently. Widely used in large-scale systems as an alternative to monolithic architecture.

📖 Detailed Explanation

Microservices Architecture (MSA) is an architectural pattern in which one large application is divided into small, independent services. Each service focuses on a single business domain, has its own database, and communicates with other services through APIs.

Key characteristics include independent deployment (each service can be deployed separately), technological diversity (different languages/frameworks can be used for each service), fault isolation (a failure in one service does not affect the entire system), and independent scaling (only services with heavy traffic are selectively scaled out).

Inter-service communication is divided into synchronous methods (REST API, gRPC) and asynchronous methods (message queues, event streaming). Large-scale services such as Netflix, Amazon, and Uber are composed of thousands of microservices and are loosely coupled through message brokers such as Kafka or RabbitMQ.

Because operational complexity increases, infrastructure such as Kubernetes, Docker, service meshes (Istio, Linkerd), API Gateway, distributed tracing (Jaeger, Zipkin), and centralized logging (ELK Stack) is essential. In line with Conway's Law, it is also common to organize teams as small, autonomous teams per service (Two-Pizza Team).

Microservices are not suitable for every situation. For early-stage startups or small projects, the "Monolith First" strategy is recommended: start with a monolithic architecture and gradually transition to microservices as the scale grows.

💻 Code Example

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

app = FastAPI(title="Order Service")

# 환경 변수에서 다른 서비스 URL 가져오기
USER_SERVICE_URL = os.getenv("USER_SERVICE_URL", "http://user-service:8000")
PRODUCT_SERVICE_URL = os.getenv("PRODUCT_SERVICE_URL", "http://product-service:8000")
PAYMENT_SERVICE_URL = os.getenv("PAYMENT_SERVICE_URL", "http://payment-service:8000")


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


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


# 인메모리 저장소 (실제로는 독립 DB 사용)
orders_db = {}


@app.post("/orders", response_model=Order)
async def create_order(request: OrderRequest):
    """
    주문 생성 - 다른 마이크로서비스와 통신
    """
    async with httpx.AsyncClient() as client:
        # 1. 사용자 서비스에서 사용자 검증
        user_response = await client.get(
            f"{USER_SERVICE_URL}/users/{request.user_id}"
        )
        if user_response.status_code != 200:
            raise HTTPException(status_code=404, detail="사용자를 찾을 수 없습니다")

        # 2. 상품 서비스에서 상품 정보 조회
        product_response = await client.get(
            f"{PRODUCT_SERVICE_URL}/products/{request.product_id}"
        )
        if product_response.status_code != 200:
            raise HTTPException(status_code=404, detail="상품을 찾을 수 없습니다")

        product = product_response.json()
        total_price = product["price"] * request.quantity

        # 3. 결제 서비스 호출
        payment_response = await client.post(
            f"{PAYMENT_SERVICE_URL}/payments",
            json={
                "user_id": request.user_id,
                "amount": total_price,
                "order_id": f"ORD-{len(orders_db) + 1}"
            }
        )

        if payment_response.status_code != 200:
            raise HTTPException(status_code=400, detail="결제 실패")

    # 4. 주문 저장
    order_id = f"ORD-{len(orders_db) + 1}"
    order = Order(
        id=order_id,
        user_id=request.user_id,
        product_id=request.product_id,
        quantity=request.quantity,
        total_price=total_price,
        status="COMPLETED"
    )
    orders_db[order_id] = order

    return order


@app.get("/orders/{order_id}", response_model=Order)
async def get_order(order_id: str):
    if order_id not in orders_db:
        raise HTTPException(status_code=404, detail="주문을 찾을 수 없습니다")
    return orders_db[order_id]


@app.get("/health")
async def health_check():
    """헬스 체크 - Kubernetes readiness/liveness probe용"""
    return {"status": "healthy", "service": "order-service"}
// 마이크로서비스 예제 - 사용자 서비스 (Express + TypeScript)
import express, { Request, Response } from 'express';
import axios from 'axios';

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

// 서비스 디스커버리 (Consul, Eureka 등 사용 가능)
const SERVICE_REGISTRY = {
    'order-service': process.env.ORDER_SERVICE_URL || 'http://order-service:3000',
    'notification-service': process.env.NOTIFICATION_SERVICE_URL || 'http://notification-service:3000'
};

interface User {
    id: string;
    name: string;
    email: string;
    createdAt: Date;
}

// 인메모리 저장소 (실제로는 독립 DB 사용)
const usersDb = new Map();

// Circuit Breaker 패턴 구현
class CircuitBreaker {
    private failures = 0;
    private lastFailureTime = 0;
    private readonly threshold = 5;
    private readonly timeout = 30000; // 30초

    async call(fn: () => Promise): Promise {
        if (this.isOpen()) {
            throw new Error('Circuit breaker is open');
        }

        try {
            const result = await fn();
            this.reset();
            return result;
        } catch (error) {
            this.recordFailure();
            throw error;
        }
    }

    private isOpen(): boolean {
        if (this.failures >= this.threshold) {
            const timeSinceLastFailure = Date.now() - this.lastFailureTime;
            return timeSinceLastFailure < this.timeout;
        }
        return false;
    }

    private recordFailure(): void {
        this.failures++;
        this.lastFailureTime = Date.now();
    }

    private reset(): void {
        this.failures = 0;
    }
}

const notificationBreaker = new CircuitBreaker();

// 사용자 생성
app.post('/users', async (req: Request, res: Response) => {
    const { name, email } = req.body;

    const user: User = {
        id: `USER-${Date.now()}`,
        name,
        email,
        createdAt: new Date()
    };

    usersDb.set(user.id, user);

    // 알림 서비스에 이벤트 발행 (비동기, 실패해도 사용자 생성은 성공)
    try {
        await notificationBreaker.call(async () => {
            await axios.post(
                `${SERVICE_REGISTRY['notification-service']}/notifications`,
                {
                    type: 'USER_CREATED',
                    userId: user.id,
                    email: user.email,
                    message: '회원가입을 환영합니다!'
                }
            );
        });
    } catch (error) {
        console.error('알림 서비스 호출 실패 (무시됨):', error);
        // 알림 실패는 사용자 생성 실패로 이어지지 않음
    }

    res.status(201).json(user);
});

// 사용자 조회
app.get('/users/:id', (req: Request, res: Response) => {
    const user = usersDb.get(req.params.id);

    if (!user) {
        return res.status(404).json({ error: '사용자를 찾을 수 없습니다' });
    }

    res.json(user);
});

// 헬스 체크
app.get('/health', (req: Request, res: Response) => {
    res.json({
        status: 'healthy',
        service: 'user-service',
        timestamp: new Date().toISOString()
    });
});

// 메트릭 엔드포인트 (Prometheus 수집용)
app.get('/metrics', (req: Request, res: Response) => {
    res.set('Content-Type', 'text/plain');
    res.send(`
# HELP users_total Total number of users
# TYPE users_total counter
users_total ${usersDb.size}
    `);
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`User service running on port ${PORT}`);
});
# 마이크로서비스 아키텍처 구조 (Kubernetes + Docker Compose)

# ========================================
# docker-compose.yml - 로컬 개발 환경
# ========================================
version: '3.8'

services:
  # API Gateway - 모든 요청의 진입점
  api-gateway:
    image: nginx:alpine
    ports:
      - "80:80"
    depends_on:
      - user-service
      - order-service
      - product-service
    networks:
      - microservices-network

  # 사용자 서비스
  user-service:
    build: ./services/user
    environment:
      - DATABASE_URL=postgres://user-db:5432/users
      - NOTIFICATION_SERVICE_URL=http://notification-service:3000
    depends_on:
      - user-db
    networks:
      - microservices-network

  # 주문 서비스
  order-service:
    build: ./services/order
    environment:
      - DATABASE_URL=postgres://order-db:5432/orders
      - USER_SERVICE_URL=http://user-service:8000
      - PRODUCT_SERVICE_URL=http://product-service:8000
      - KAFKA_BROKERS=kafka:9092
    depends_on:
      - order-db
      - kafka
    networks:
      - microservices-network

  # 상품 서비스
  product-service:
    build: ./services/product
    environment:
      - DATABASE_URL=mongo://product-db:27017/products
    depends_on:
      - product-db
    networks:
      - microservices-network

  # 각 서비스별 독립 데이터베이스
  user-db:
    image: postgres:15
    environment:
      POSTGRES_DB: users
    volumes:
      - user-data:/var/lib/postgresql/data
    networks:
      - microservices-network

  order-db:
    image: postgres:15
    environment:
      POSTGRES_DB: orders
    networks:
      - microservices-network

  product-db:
    image: mongo:6
    networks:
      - microservices-network

  # 메시지 브로커 (비동기 통신)
  kafka:
    image: confluentinc/cp-kafka:latest
    environment:
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
    depends_on:
      - zookeeper
    networks:
      - microservices-network

  zookeeper:
    image: confluentinc/cp-zookeeper:latest
    networks:
      - microservices-network

networks:
  microservices-network:
    driver: bridge

volumes:
  user-data:

# ========================================
# 프로젝트 디렉토리 구조
# ========================================
# microservices-app/
# ├── docker-compose.yml
# ├── k8s/
# │   ├── user-service.yaml
# │   ├── order-service.yaml
# │   └── api-gateway.yaml
# ├── services/
# │   ├── user/
# │   │   ├── Dockerfile
# │   │   ├── package.json
# │   │   └── src/
# │   ├── order/
# │   │   ├── Dockerfile
# │   │   ├── requirements.txt
# │   │   └── app/
# │   └── product/
# │       ├── Dockerfile
# │       └── src/
# └── shared/
#     ├── proto/           # gRPC 프로토콜 정의
#     └── events/          # 공유 이벤트 스키마

🗣️ Say It Like This in Practice

💬 In an architecture design meeting
"I think we should separate the order domain and the inventory domain into separate microservices. Orders have different peak traffic times, and inventory requires real-time accuracy. If we publish events with Kafka, we can keep them loosely coupled."
💬 In an incident response meeting
"Even when the payment service went down, the order service had a circuit breaker, so the entire system didn't go down. Only payments were temporarily suspended, and the rest of the features worked normally. That's thanks to the fault isolation of microservices."
💬 In a Technology Adoption Discussion
"At our current scale, microservices are over-engineering. The team is small and traffic isn't high either. It's more realistic to quickly build an MVP as a monolith first, and then separate out the domains that become bottlenecks as users grow."

⚠️ Cautions & Best Practices

❌
Complexity of Distributed Transactions

Maintaining data consistency across services is difficult. Implement eventual consistency with the SAGA pattern or event sourcing.

❌
Preparing for Network Failures

Communication between services can fail at any time. Timeouts, retries, circuit breakers, and fallback patterns are essential.

❌
Operational Overhead

Managing dozens of services requires infrastructure for logging, monitoring, deployment automation, and service discovery.

✅
Best Practices

Identify boundaries with Domain-Driven Design (DDD), API versioning, independent databases (Database per Service), container orchestration (K8s), and centralized logging and distributed tracing.

🔗 Related Terms

📚 Learn More