マイクロサービスアーキテクチャ設計パターン【2025年実践ガイド】
2025年、マイクロサービスアーキテクチャは大規模システム開発の標準となりました。本記事では、ドメイン駆動設計(DDD)、API Gateway、サービスメッシュなど、実践的な設計パターンを徹底解説します。
マイクロサービスとは

モノリス vs マイクロサービス
| 特性 | モノリス | マイクロサービス |
|---|---|---|
| デプロイ単位 | 全体を一括 | サービス個別 |
| 技術スタック | 統一 | サービスごとに選択可 |
| スケーリング | 全体をスケール | 必要なサービスのみ |
| 障害影響 | 全体停止のリスク | 部分的な影響に限定 |
| 開発速度 | 初期は高速 | スケール時に高速 |
| 複雑性 | 低 | 高 |
マイクロサービスの原則
- 単一責任の原則:1サービス = 1ビジネス機能
- 独立デプロイ可能:他サービスに影響を与えない
- データベース分離:各サービスが独自のDBを持つ
- 疎結合:非同期通信を優先
- 自律性:チームが独立して開発・運用
サービス分割戦略
ドメイン駆動設計(DDD)

Eコマースシステムの例
境界づけられたコンテキスト(Bounded Context):
┌─────────────────┐
│ User Service │ ユーザー管理
│ - 認証 │
│ - プロフィール │
└─────────────────┘
┌─────────────────┐
│ Product Service │ 商品管理
│ - 商品マスタ │
│ - 在庫管理 │
└─────────────────┘
┌─────────────────┐
│ Order Service │ 注文処理
│ - カート │
│ - 注文確定 │
└─────────────────┘
┌─────────────────┐
│ Payment Service │ 決済処理
│ - クレジット決済 │
│ - ポイント決済 │
└─────────────────┘
┌─────────────────┐
│ Shipping Service│ 配送管理
│ - 配送先管理 │
│ - 配送状況追跡 │
└─────────────────┘
集約(Aggregate)設計
# 注文集約の例
from dataclasses import dataclass
from typing import List
from decimal import Decimal
@dataclass
class OrderLine:
"""注文明細"""
product_id: str
product_name: str
quantity: int
unit_price: Decimal
def subtotal(self) -> Decimal:
return self.unit_price * self.quantity
@dataclass
class Order:
"""注文集約ルート"""
order_id: str
user_id: str
order_lines: List[OrderLine]
status: str # PENDING, CONFIRMED, SHIPPED, DELIVERED
def total_amount(self) -> Decimal:
"""合計金額"""
return sum(line.subtotal() for line in self.order_lines)
def confirm(self):
"""注文確定(ビジネスロジック)"""
if self.status != "PENDING":
raise ValueError("注文はすでに確定済みです")
if len(self.order_lines) == 0:
raise ValueError("注文明細が空です")
# 在庫確認(別サービスに問い合わせ)
for line in self.order_lines:
if not self._check_inventory(line.product_id, line.quantity):
raise ValueError(f"在庫不足: {line.product_name}")
self.status = "CONFIRMED"
def _check_inventory(self, product_id: str, quantity: int) -> bool:
"""在庫確認(Product Serviceへの問い合わせ)"""
# 実際にはHTTPリクエストまたはメッセージング
pass

通信パターン
1. 同期通信(REST / gRPC)
REST APIの実装例
# FastAPI(Python)
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import httpx
app = FastAPI()
class OrderRequest(BaseModel):
user_id: str
product_id: str
quantity: int
@app.post("/orders")
async def create_order(order: OrderRequest):
# 1. Product Serviceに在庫確認
async with httpx.AsyncClient() as client:
product_response = await client.get(
f"http://product-service/products/{order.product_id}"
)
if product_response.status_code != 200:
raise HTTPException(status_code=404, detail="商品が見つかりません")
product = product_response.json()
if product["stock"] < order.quantity:
raise HTTPException(status_code=400, detail="在庫不足")
# 2. 注文を作成
new_order = {
"order_id": generate_id(),
"user_id": order.user_id,
"product_id": order.product_id,
"quantity": order.quantity,
"status": "PENDING"
}
save_to_database(new_order)
# 3. Payment Serviceに決済リクエスト
async with httpx.AsyncClient() as client:
payment_response = await client.post(
"http://payment-service/payments",
json={
"order_id": new_order["order_id"],
"amount": product["price"] * order.quantity
}
)
return {"order_id": new_order["order_id"], "status": "CREATED"}
gRPCの実装例
// order.proto
syntax = "proto3";
package order;
service OrderService {
rpc CreateOrder (CreateOrderRequest) returns (CreateOrderResponse);
rpc GetOrder (GetOrderRequest) returns (Order);
}
message CreateOrderRequest {
string user_id = 1;
repeated OrderLine order_lines = 2;
}
message CreateOrderResponse {
string order_id = 1;
string status = 2;
}
message OrderLine {
string product_id = 1;
int32 quantity = 2;
}
message Order {
string order_id = 1;
string user_id = 2;
repeated OrderLine order_lines = 3;
string status = 4;
}
message GetOrderRequest {
string order_id = 1;
}
2. 非同期通信(メッセージング)
イベント駆動アーキテクチャ
Order Service
↓ OrderCreatedイベント発行
Kafka / RabbitMQ
↓
├→ Inventory Service(在庫減算)
├→ Payment Service(決済処理)
├→ Notification Service(メール送信)
└→ Analytics Service(分析データ蓄積)
Kafkaでの実装例
from confluent_kafka import Producer, Consumer
import json
# イベント発行(Producer)
def publish_order_created_event(order):
producer = Producer({'bootstrap.servers': 'kafka:9092'})
event = {
'event_type': 'OrderCreated',
'order_id': order.order_id,
'user_id': order.user_id,
'total_amount': float(order.total_amount()),
'timestamp': datetime.utcnow().isoformat()
}
producer.produce(
topic='order-events',
key=order.order_id,
value=json.dumps(event)
)
producer.flush()
# イベント購読(Consumer)
def consume_order_events():
consumer = Consumer({
'bootstrap.servers': 'kafka:9092',
'group.id': 'inventory-service',
'auto.offset.reset': 'earliest'
})
consumer.subscribe(['order-events'])
while True:
msg = consumer.poll(1.0)
if msg is None:
continue
if msg.error():
print(f"Consumer error: {msg.error()}")
continue
event = json.loads(msg.value().decode('utf-8'))
if event['event_type'] == 'OrderCreated':
# 在庫減算処理
reduce_inventory(event['order_id'])
consumer.commit()
API Gateway パターン
API Gatewayの責務
クライアント(Web/Mobile)
↓
API Gateway
├─ 認証・認可
├─ レート制限
├─ リクエストルーティング
├─ プロトコル変換
├─ レスポンス集約
└─ キャッシング
↓
├→ User Service
├→ Product Service
├→ Order Service
└→ Payment Service
Kong API Gateway設定例
_format_version: "3.0"
services:
- name: user-service
url: http://user-service:8080
routes:
- name: user-route
paths:
- /api/users
methods:
- GET
- POST
plugins:
- name: rate-limiting
config:
minute: 100
hour: 1000
- name: jwt
config:
claims_to_verify:
- exp
- name: order-service
url: http://order-service:8080
routes:
- name: order-route
paths:
- /api/orders
plugins:
- name: cors
config:
origins:
- "*"
methods:
- GET
- POST
- PUT
- DELETE
- name: request-transformer
config:
add:
headers:
- "X-Service-Name:order-service"

サービスメッシュ(Istio)
サービスメッシュの利点
| 機能 | 従来のアプローチ | サービスメッシュ |
|---|---|---|
| 負荷分散 | アプリケーションコードに実装 | Envoy Proxyが自動処理 |
| サーキットブレーカー | 各サービスで個別実装 | 統一的に設定 |
| 分散トレーシング | ライブラリ導入が必要 | 自動的に収集 |
| mTLS | 手動設定 | 自動的に暗号化 |
| カナリアデプロイ | 複雑な実装 | 設定ファイルで簡単に |
Istio設定例
# VirtualService(トラフィック管理)
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: order-service
spec:
hosts:
- order-service
http:
- match:
- headers:
x-version:
exact: "v2"
route:
- destination:
host: order-service
subset: v2
weight: 100
- route:
- destination:
host: order-service
subset: v1
weight: 90
- destination:
host: order-service
subset: v2
weight: 10 # カナリアデプロイ(10%)
---
# DestinationRule(サブセット定義)
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
name: order-service
spec:
host: order-service
trafficPolicy:
connectionPool:
tcp:
maxConnections: 100
http:
http1MaxPendingRequests: 50
http2MaxRequests: 100
outlierDetection:
consecutiveErrors: 5
interval: 30s
baseEjectionTime: 30s
maxEjectionPercent: 50
subsets:
- name: v1
labels:
version: v1
- name: v2
labels:
version: v2
データ管理パターン
1. Database per Service
Order Service → PostgreSQL (注文データ)
Product Service → PostgreSQL (商品データ)
Inventory Service → PostgreSQL (在庫データ)
Analytics Service → ClickHouse (分析データ)
Cache Service → Redis (キャッシュ)
2. Saga パターン(分散トランザクション)
from enum import Enum
from typing import List, Callable
class SagaStep:
def __init__(self, action: Callable, compensation: Callable):
self.action = action
self.compensation = compensation
class SagaOrchestrator:
def __init__(self):
self.steps: List[SagaStep] = []
self.completed_steps: List[SagaStep] = []
def add_step(self, action: Callable, compensation: Callable):
self.steps.append(SagaStep(action, compensation))
async def execute(self):
try:
# 順次実行
for step in self.steps:
await step.action()
self.completed_steps.append(step)
return True
except Exception as e:
# エラー時は補償トランザクション実行
print(f"Saga failed: {e}")
await self._compensate()
return False
async def _compensate(self):
"""補償トランザクション(ロールバック)"""
for step in reversed(self.completed_steps):
try:
await step.compensation()
except Exception as e:
print(f"Compensation failed: {e}")
# 使用例
async def create_order_saga(order_data):
saga = SagaOrchestrator()
# Step 1: 在庫予約
saga.add_step(
action=lambda: reserve_inventory(order_data),
compensation=lambda: release_inventory(order_data)
)
# Step 2: 決済処理
saga.add_step(
action=lambda: process_payment(order_data),
compensation=lambda: refund_payment(order_data)
)
# Step 3: 注文確定
saga.add_step(
action=lambda: confirm_order(order_data),
compensation=lambda: cancel_order(order_data)
)
success = await saga.execute()
return success
3. CQRS(Command Query Responsibility Segregation)
Command側(書き込み):
ユーザーアクション
↓
Order Service(PostgreSQL)
↓
イベント発行(OrderCreated)
↓
Kafka
Query側(読み取り):
Kafkaイベント購読
↓
Read Model更新(Elasticsearch)
↓
高速な検索・集計クエリ

監視とオブザーバビリティ
分散トレーシング(Jaeger)
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.jaeger.thrift import JaegerExporter
# トレーサー設定
trace.set_tracer_provider(TracerProvider())
jaeger_exporter = JaegerExporter(
agent_host_name="jaeger",
agent_port=6831
)
trace.get_tracer_provider().add_span_processor(
BatchSpanProcessor(jaeger_exporter)
)
tracer = trace.get_tracer(__name__)
# Order Serviceでのトレース
@tracer.start_as_current_span("create_order")
async def create_order(order_data):
with tracer.start_as_current_span("validate_order"):
validate(order_data)
with tracer.start_as_current_span("call_product_service"):
product = await get_product(order_data["product_id"])
with tracer.start_as_current_span("call_payment_service"):
payment_result = await process_payment(order_data)
with tracer.start_as_current_span("save_order"):
order = await save_order_to_db(order_data)
return order
ログ集約(ELK Stack)
# Filebeat設定(各サービスのログ収集)
filebeat.inputs:
- type: container
paths:
- '/var/lib/docker/containers/*/*.log'
processors:
- add_kubernetes_metadata:
host: ${NODE_NAME}
matchers:
- logs_path:
logs_path: "/var/lib/docker/containers/"
output.elasticsearch:
hosts: ["elasticsearch:9200"]
index: "microservices-logs-%{+yyyy.MM.dd}"
# Logstash設定(ログ加工)
input {
beats {
port => 5044
}
}
filter {
json {
source => "message"
}
grok {
match => { "message" => "%{TIMESTAMP_ISO8601:timestamp} %{LOGLEVEL:level} %{GREEDYDATA:message}" }
}
}
output {
elasticsearch {
hosts => ["elasticsearch:9200"]
index => "microservices-logs-%{+YYYY.MM.dd}"
}
}
セキュリティ
Zero Trust Architecture
すべてのサービス間通信をmTLSで暗号化
Service A
↓ mTLS証明書検証
Service Mesh(Envoy Proxy)
↓ mTLS証明書検証
Service B
各サービスは:
- 独自の証明書を持つ
- 相手の証明書を検証
- 通信を暗号化
OAuth 2.0 / JWTによる認証
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
SECRET_KEY = "your-secret-key"
ALGORITHM = "HS256"
def verify_token(token: str = Depends(oauth2_scheme)):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
user_id: str = payload.get("sub")
if user_id is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials"
)
return user_id
except JWTError:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid token"
)
# 保護されたエンドポイント
@app.get("/orders")
async def get_orders(user_id: str = Depends(verify_token)):
orders = fetch_orders_by_user(user_id)
return {"orders": orders}
デプロイ戦略
Blue-Green Deployment
Production Traffic
↓
Load Balancer
├→ Blue環境(現行バージョン v1.0)
└→ Green環境(新バージョン v1.1)
手順:
1. Green環境にv1.1をデプロイ
2. Green環境でテスト実施
3. トラフィックをGreenに切り替え
4. 問題があればBlueに即座にロールバック
Canary Deployment
# Istio VirtualService
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: order-service
spec:
hosts:
- order-service
http:
- route:
- destination:
host: order-service
subset: v1
weight: 95 # 現行バージョン
- destination:
host: order-service
subset: v2
weight: 5 # カナリア(新バージョン)
まとめ:マイクロサービス成功の鍵
導入すべき組織
- 100人以上の開発チーム
- 複数の製品/サービスを展開
- 高いスケーラビリティが必要
- 技術スタックを柔軟に選びたい
避けるべき組織
- 10人以下のスタートアップ
- シンプルなCRUDアプリケーション
- DevOps体制が未整備
- 複雑性を管理できるスキルが不足
マイクロサービスは銀の弾丸ではありません。ビジネス要件、チーム規模、技術的成熟度を総合的に判断して導入を検討してください。
画像生成プロンプト集(DALL-E 3 / Midjourney用)
プロンプト1:モノリス vs マイクロサービス比較図
Split diagram comparing monolithic architecture (left) vs microservices architecture (right). Monolith shows single large box, microservices shows multiple small connected boxes. Clean technical diagram style, blue and green color scheme, arrows showing communication flow.
プロンプト2:DDD境界づけられたコンテキスト図
Domain-Driven Design bounded contexts diagram for e-commerce system. Shows User, Product, Order, Payment, Shipping services as separate bounded contexts with clear boundaries. Strategic design pattern visualization, colorful boxes with labels, professional architecture style.
プロンプト3:API Gatewayアーキテクチャ
API Gateway pattern architecture diagram. Shows client devices → API Gateway (with authentication, rate limiting, routing) → multiple microservices. Network architecture style, purple and blue gradient, flowing data streams, modern tech aesthetic.
プロンプト4:Saga パターンフロー図
Saga pattern flowchart showing distributed transaction with compensating transactions. Sequential steps (reserve inventory → process payment → confirm order) with rollback paths in red. Technical process diagram, green success path, red compensation path, decision diamonds.
プロンプト5:サービスメッシュ(Istio)構成図
Service mesh architecture with Istio and Envoy proxies. Shows sidecar proxies attached to each microservice, control plane managing configuration. Cloud-native architecture style, mesh network visualization, cyan and purple colors, professional diagram layout.
著者について
DX・AI推進コンサルタント
大手企業グループのDX推進責任者・顧問CTO | 長年のIT・DXキャリア | AWS・GA4・生成AI活用を専門に実践ノウハウを発信中
#マイクロサービス #アーキテクチャ #システム設計 #クラウド #スケーラビリティ
最終更新: 2025-11-16
この記事を書いた人
nexion-lab
DX推進責任者・顧問CTO | IT業界15年以上
大手企業グループでDX推進責任者、顧問CTOとして活動。AI・生成AI活用、クラウドインフラ最適化、データドリブン経営の領域で専門性を発揮。 実務で培った知識と経験を、ブログ記事として発信しています。