---
name: service-discovery-registry
description: Service discovery and registry patterns for GoodGo microservices including service registry, health check orchestration, load balancing strategies, and service mesh integration.
---

# Service Discovery & Registry Patterns
# Các Patterns Service Discovery & Registry

## When to Use This Skill / Khi Nào Sử Dụng Skill Này

Use this skill when:
Sử dụng skill này khi:
- Implementing service discovery mechanisms / Triển khai cơ chế service discovery
- Managing service registry / Quản lý service registry
- Orchestrating health checks / Điều phối health checks
- Implementing load balancing strategies / Triển khai các chiến lược load balancing
- Integrating with service mesh / Tích hợp với service mesh
- Managing dynamic service registration / Quản lý đăng ký service động
- Implementing DNS-based discovery / Triển khai discovery dựa trên DNS
- Building service catalog / Xây dựng service catalog

## Core Concepts / Khái Niệm Cốt Lõi

### Service Discovery Types / Các Loại Service Discovery

1. **Client-Side Discovery / Discovery Phía Client**: Client queries service registry / Client truy vấn service registry
2. **Server-Side Discovery / Discovery Phía Server**: Load balancer queries registry (Kubernetes DNS) / Load balancer truy vấn registry (Kubernetes DNS)
3. **Service Mesh / Service Mesh**: Automatic service discovery (Istio, Linkerd) / Service discovery tự động (Istio, Linkerd)

### Service Registry / Service Registry

- **Static Configuration / Cấu Hình Tĩnh**: Hardcoded service addresses / Địa chỉ service được hardcode
- **Dynamic Registry / Registry Động**: Services register/unregister dynamically / Services đăng ký/hủy đăng ký động
- **DNS-Based / Dựa Trên DNS**: Use DNS for service discovery (Kubernetes) / Sử dụng DNS cho service discovery (Kubernetes)

## Service Registration Flow / Luồng Đăng Ký Service

The service registration lifecycle involves startup registration, periodic heartbeats, and graceful shutdown unregistration.

Vòng đời đăng ký service bao gồm đăng ký khi khởi động, heartbeat định kỳ, và hủy đăng ký khi shutdown.

```mermaid
sequenceDiagram
    participant Service as Service Instance
    participant Registry as Service Registry
    participant Health as Health Check

    Note over Service,Registry: Service Startup
    Service->>Registry: Register service info<br/>(name, url, version)
    Registry->>Registry: Store service metadata
    Registry-->>Service: Registration confirmed

    Note over Service,Registry: Heartbeat Loop (every 30s)
    loop Every 30 seconds
        Service->>Health: Check own health status
        Health-->>Service: Health status
        Service->>Registry: Update registration<br/>(status, lastHeartbeat)
        Registry->>Registry: Update service record
    end

    Note over Service,Registry: Service Shutdown
    Service->>Registry: Unregister service
    Registry->>Registry: Remove service record
    Registry-->>Service: Unregistration confirmed
```

## Health Check Orchestration / Điều Phối Health Check

Health checks ensure services are available and functioning correctly. The system aggregates health status from multiple services to determine overall system health.

Health checks đảm bảo services có sẵn và hoạt động đúng. Hệ thống tổng hợp trạng thái health từ nhiều services để xác định health tổng thể của hệ thống.

```mermaid
flowchart TD
    Start([Health Check Request]) --> GetServices[Get All Services from Registry]
    GetServices --> CheckEach{For Each Service}
    
    CheckEach --> CheckHealth[Check Service Health Endpoint]
    CheckHealth --> HealthOK{Health OK?}
    
    HealthOK -->|Yes| UpdateHealthy[Update Status: Healthy]
    HealthOK -->|No| UpdateUnhealthy[Update Status: Unhealthy]
    
    UpdateHealthy --> CheckTimeout{Last Heartbeat<br/>< 60s?}
    UpdateUnhealthy --> CheckTimeout
    
    CheckTimeout -->|Yes| MarkActive[Mark as Active]
    CheckTimeout -->|No| MarkStale[Mark as Stale]
    
    MarkActive --> NextService{More Services?}
    MarkStale --> NextService
    
    NextService -->|Yes| CheckEach
    NextService -->|No| AggregateStatus[Aggregate Overall Status]
    
    AggregateStatus --> CountUnhealthy[Count Unhealthy Services]
    CountUnhealthy --> DetermineStatus{Unhealthy Count}
    
    DetermineStatus -->|0| StatusHealthy[Status: Healthy]
    DetermineStatus -->|< 50%| StatusDegraded[Status: Degraded]
    DetermineStatus -->|>= 50%| StatusUnhealthy[Status: Unhealthy]
    
    StatusHealthy --> ReturnResult[Return Health Status]
    StatusDegraded --> ReturnResult
    StatusUnhealthy --> ReturnResult
    
    ReturnResult --> End([End])
```

## Load Balancing Strategies / Các Chiến Lược Load Balancing

Load balancing distributes requests across multiple service instances. Different strategies are used based on service characteristics and requirements.

Load balancing phân phối requests qua nhiều service instances. Các chiến lược khác nhau được sử dụng dựa trên đặc điểm và yêu cầu của service.

```mermaid
flowchart TD
    Start([Incoming Request]) --> GetInstances[Get Available Service Instances]
    GetInstances --> SelectStrategy{Load Balancing Strategy}
    
    SelectStrategy -->|Round Robin| RoundRobin[Round Robin Algorithm]
    SelectStrategy -->|Least Connections| LeastConn[Least Connections Algorithm]
    SelectStrategy -->|Weighted| Weighted[Weighted Round Robin]
    
    RoundRobin --> SelectNext[Select Next Instance in Order]
    SelectNext --> UseInstance[Use Selected Instance]
    
    LeastConn --> CompareConn[Compare Connection Counts]
    CompareConn --> SelectMin[Select Instance with<br/>Minimum Connections]
    SelectMin --> UseInstance
    
    Weighted --> CalculateWeight[Calculate Total Weight]
    CalculateWeight --> RandomSelect[Random Selection Based on Weights]
    RandomSelect --> UseInstance
    
    UseInstance --> ForwardRequest[Forward Request to Instance]
    ForwardRequest --> UpdateStats[Update Statistics]
    UpdateStats --> End([Request Completed])
    
    style RoundRobin fill:#e1f5ff
    style LeastConn fill:#e1f5ff
    style Weighted fill:#e1f5ff
```

## Kubernetes DNS Discovery / Discovery DNS Kubernetes

Kubernetes provides built-in DNS-based service discovery. Services are automatically discoverable via DNS names.

Kubernetes cung cấp service discovery dựa trên DNS tích hợp sẵn. Services có thể được discover tự động qua tên DNS.

```typescript
// EN: Use Kubernetes DNS for service discovery
// VI: Sử dụng Kubernetes DNS cho service discovery
const serviceUrl = `http://user-service.production.svc.cluster.local`;
```

### DNS Patterns / Các Pattern DNS

- **Short form / Dạng ngắn** (same namespace / cùng namespace): `http://user-service`
- **Full form / Dạng đầy đủ** (cross-namespace / khác namespace): `http://user-service.production.svc.cluster.local`
- **With port / Với port**: `http://user-service.production.svc.cluster.local:5000`

## Service Registry Implementation / Triển Khai Service Registry

### Register Service / Đăng Ký Service

```typescript
// EN: Register service
// VI: Đăng ký service
await serviceRegistry.register({
  name: 'user-service',
  version: '1.0.0',
  url: 'http://user-service:5000',
  healthCheckUrl: 'http://user-service:5000/health',
  status: 'healthy',
  lastHeartbeat: new Date(),
});
```

### Discover Service / Tìm Service

```typescript
// EN: Discover service
// VI: Tìm service
const service = await serviceRegistry.discover('user-service');
if (service?.status === 'healthy') {
  // EN: Use service
  // VI: Sử dụng service
}
```

### List Healthy Services / Liệt Kê Services Healthy

```typescript
// EN: List all healthy services
// VI: Liệt kê tất cả services healthy
const healthyServices = await serviceRegistry.listHealthyServices();
```

## Health Check Aggregation / Tổng Hợp Health Check

Aggregate health status from multiple services to determine overall system health.

Tổng hợp trạng thái health từ nhiều services để xác định health tổng thể của hệ thống.

```typescript
// EN: Aggregate health from multiple services
// VI: Tổng hợp health từ nhiều services
const health = await healthAggregator.getAggregatedHealth();
// EN: Returns: { status: 'healthy' | 'degraded' | 'unhealthy', services: [...] }
// VI: Trả về: { status: 'healthy' | 'degraded' | 'unhealthy', services: [...] }
```

## Load Balancing Implementation / Triển Khai Load Balancing

### Round Robin / Round Robin

```typescript
const instance = loadBalancer.roundRobin(instances);
```

### Least Connections / Least Connections

```typescript
const instance = loadBalancer.leastConnections(instances);
```

### Weighted Round Robin / Weighted Round Robin

```typescript
const instance = loadBalancer.weightedRoundRobin(instances);
```

## Service Mesh Integration / Tích Hợp Service Mesh

Service mesh solutions like Istio provide automatic service discovery and advanced routing capabilities.

Các giải pháp service mesh như Istio cung cấp service discovery tự động và khả năng routing nâng cao.

```yaml
apiVersion: networking.istio.io/v1alpha3
kind: ServiceEntry
metadata:
  name: external-service
spec:
  hosts:
    - external-api.example.com
  ports:
    - number: 443
      name: https
      protocol: HTTPS
  location: MESH_EXTERNAL
  resolution: DNS
```

## Best Practices / Thực Hành Tốt

1. **Kubernetes DNS / Kubernetes DNS**: Use Kubernetes DNS for service discovery in K8s environments / Sử dụng Kubernetes DNS cho service discovery trong môi trường K8s
2. **Health Checks / Health Checks**: Implement comprehensive health checks (`/health`, `/health/live`, `/health/ready`) / Triển khai health checks toàn diện (`/health`, `/health/live`, `/health/ready`)
3. **Service Registry / Service Registry**: Use registry for dynamic services that need runtime discovery / Sử dụng registry cho các services động cần discovery tại runtime
4. **Load Balancing / Load Balancing**: Choose appropriate load balancing strategy based on service characteristics / Chọn chiến lược load balancing phù hợp dựa trên đặc điểm service
5. **Monitoring / Giám Sát**: Monitor service discovery and health check metrics / Giám sát metrics service discovery và health check
6. **Heartbeat / Heartbeat**: Implement periodic heartbeat (every 30 seconds) to keep registry updated / Triển khai heartbeat định kỳ (mỗi 30 giây) để giữ registry được cập nhật
7. **Graceful Shutdown / Shutdown Nhẹ Nhàng**: Always unregister services on shutdown to prevent stale entries / Luôn hủy đăng ký services khi shutdown để tránh entries cũ
8. **Fallback / Dự Phòng**: Provide fallback mechanisms when registry is unavailable / Cung cấp cơ chế dự phòng khi registry không khả dụng

## Common Mistakes / Các Lỗi Thường Gặp

1. **Hardcoded Service URLs / Hardcode Service URLs**: Breaks in different environments / Phá vỡ trong các môi trường khác nhau
   ```typescript
   // ❌ BAD: Hardcoded
   const url = 'http://user-service:5000';

   // ✅ GOOD: Use discovery or env vars
   const url = discovery.getServiceUrl('user-service');
   ```

2. **No Heartbeat / Không Có Heartbeat**: Stale registry entries / Entries registry cũ
   ```typescript
   // ❌ BAD: Register once
   await registry.register(service);

   // ✅ GOOD: Periodic heartbeat
   setInterval(() => registry.register(service), 30000);
   ```

3. **Missing Graceful Shutdown / Thiếu Graceful Shutdown**: Orphaned registrations / Đăng ký bị bỏ lại
   ```typescript
   // ✅ Always unregister on shutdown
   process.on('SIGTERM', async () => {
     await registry.unregister(serviceName);
     process.exit(0);
   });
   ```

4. **No Fallback / Không Có Fallback**: Fails when registry unavailable / Lỗi khi registry không khả dụng
   ```typescript
   // ❌ BAD: No fallback
   const url = await registry.discover('service');

   // ✅ GOOD: Fallback to default
   const url = await registry.discover('service')
     ?? process.env.SERVICE_FALLBACK_URL;
   ```

## Quick Reference / Tham Khảo Nhanh

### Discovery Types / Các Loại Discovery

| Discovery Type | Implementation | Use Case |
|----------------|----------------|----------|
| **K8s DNS** | `service.namespace.svc.cluster.local` | Internal services |
| **Service Registry** | Database-backed | Dynamic services |
| **Service Mesh** | Istio/Linkerd | Complex routing |
| **Environment Vars** | `process.env.SERVICE_URL` | Simple/external |

### Health Check Endpoints / Các Endpoint Health Check

| Endpoint | Purpose |
|----------|---------|
| `/health` | Basic health |
| `/health/live` | K8s liveness probe |
| `/health/ready` | K8s readiness probe |

### Load Balancing Strategies / Các Chiến Lược Load Balancing

| Strategy | When to Use |
|----------|-------------|
| **Round Robin** | Equal capacity servers |
| **Least Connections** | Varying request durations |
| **Weighted** | Different server capacities |

### Service Registration Lifecycle / Vòng Đời Đăng Ký Service

```
Startup → Register → Heartbeat (30s) → ... → Shutdown → Unregister
```

## Resources / Tài Nguyên

- [Deployment Kubernetes](./deployment-kubernetes.md) - Kubernetes deployment patterns / Các pattern deployment Kubernetes
- [Observability & Monitoring](./observability-monitoring.md) - Health checks and monitoring / Health checks và giám sát
- [Project Rules](./project-rules.md) - GoodGo standards / Các tiêu chuẩn GoodGo
- Skill Source: `.cursor/skills/service-discovery-registry/SKILL.md`
