Probar gratis
6 min lectura Guide 851 of 877

Patrones de Comunicación de Microservicios

Los patrones de comunicación de microservicios permiten interacción confiable entre servicios distribuidos. GitScrum ayuda a los equipos a trackear dependencias de servicios, fallos de comunicación y coordinación inter-servicios en arquitecturas de microservicios complejas.

Fundamentos de Comunicación

La arquitectura de microservicios depende de patrones de comunicación efectivos para mantener confiabilidad y rendimiento del sistema.

Desafíos de Comunicación

DesafíoDescripciónMitigación
Confiabilidad de redServicios se comunican sobre redes propensas a fallosCircuit breakers, reintentos
LatenciaLlamadas de red son más lentas que comunicación in-processCaching, async donde posible
Consistencia de datosMantener consistencia a través de límites de servicioEventual consistency, sagas
AcoplamientoServicios pueden volverse muy dependientesContratos, versioning

Patrones Síncronos vs Asíncronos

COMPARACIÓN DE PATRONES
═══════════════════════

SÍNCRONO (Request/Response):
┌─────────────────────────────────────────────────────────────┐
│                                                             │
│  Service A ──request──► Service B                          │
│            ◄──response──                                   │
│                                                             │
│  CARACTERÍSTICAS:                                           │
│  ├── Simple de implementar y entender                      │
│  ├── Respuesta inmediata                                   │
│  ├── Acoplamiento temporal (A espera a B)                  │
│  └── Fallo en cascada si B falla                           │
│                                                             │
│  CUÁNDO USAR:                                               │
│  ├── Queries que necesitan respuesta inmediata             │
│  ├── Operaciones CRUD simples                              │
│  └── Cuando consistencia inmediata es requerida            │
│                                                             │
└─────────────────────────────────────────────────────────────┘

ASÍNCRONO (Event/Message):
┌─────────────────────────────────────────────────────────────┐
│                                                             │
│  Service A ──publish──► [Queue/Topic] ──consume──► Service B│
│  (no espera)                                               │
│                                                             │
│  CARACTERÍSTICAS:                                           │
│  ├── Desacoplamiento temporal                              │
│  ├── Mayor resiliencia                                     │
│  ├── Escalabilidad mejorada                                │
│  └── Complejidad adicional (eventual consistency)          │
│                                                             │
│  CUÁNDO USAR:                                               │
│  ├── Operaciones que no requieren respuesta inmediata      │
│  ├── Procesamiento de alto volumen                         │
│  └── Cuando resiliencia es crítica                         │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Patrones REST/HTTP

COMUNICACIÓN REST
═════════════════

PATRÓN BÁSICO:
┌─────────────────────────────────────────────────────────────┐
│                                                             │
│  Order Service                    Payment Service           │
│       │                                 │                   │
│       │ POST /payments                  │                   │
│       │ {orderId, amount}               │                   │
│       │────────────────────────────────►│                   │
│       │                                 │                   │
│       │     HTTP 201 Created            │                   │
│       │     {paymentId, status}         │                   │
│       │◄────────────────────────────────│                   │
│                                                             │
└─────────────────────────────────────────────────────────────┘

MEJORES PRÁCTICAS:
┌─────────────────────────────────────────────────────────────┐
│  ✅ Usar verbos HTTP correctamente (GET, POST, PUT, DELETE)│
│  ✅ Versionar APIs (/v1/payments, /v2/payments)            │
│  ✅ Implementar timeouts apropiados                        │
│  ✅ Retornar códigos de estado significativos              │
│  ✅ Documentar con OpenAPI/Swagger                         │
└─────────────────────────────────────────────────────────────┘

Event-Driven Architecture

ARQUITECTURA ORIENTADA A EVENTOS
════════════════════════════════

FLUJO DE EVENTO:
┌─────────────────────────────────────────────────────────────┐
│                                                             │
│  Order         Event           Inventory    Notification    │
│  Service       Bus             Service      Service         │
│     │                              │            │           │
│     │ OrderCreated                 │            │           │
│     │──────────────────►           │            │           │
│     │               │              │            │           │
│     │               │──────────────────────────►│           │
│     │               │              │            │           │
│     │               │──────────────►            │           │
│     │                              │            │           │
│                                                             │
│  Un evento, múltiples consumidores                         │
│                                                             │
└─────────────────────────────────────────────────────────────┘

TIPOS DE EVENTOS:
┌─────────────────────────────────────────────────────────────┐
│                                                             │
│  DOMAIN EVENTS:                                             │
│  ├── OrderPlaced                                           │
│  ├── PaymentCompleted                                      │
│  └── InventoryReserved                                     │
│                                                             │
│  INTEGRATION EVENTS:                                        │
│  ├── CustomerCreated (para sync entre servicios)           │
│  └── PriceUpdated (propagación de cambios)                 │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Circuit Breaker Pattern

CIRCUIT BREAKER
═══════════════

ESTADOS:
┌─────────────────────────────────────────────────────────────┐
│                                                             │
│  ┌──────────┐   failures > threshold   ┌──────────┐        │
│  │  CLOSED  │ ─────────────────────────► │   OPEN   │       │
│  │ (normal) │                           │ (failing)│        │
│  └──────────┘                           └────┬─────┘        │
│       ▲                                      │              │
│       │                                timeout              │
│       │ success                              │              │
│       │                                      ▼              │
│       │                              ┌───────────┐          │
│       └──────────────────────────────│ HALF-OPEN │          │
│                                      │  (testing)│          │
│                                      └───────────┘          │
│                                                             │
└─────────────────────────────────────────────────────────────┘

IMPLEMENTACIÓN:
┌─────────────────────────────────────────────────────────────┐
│                                                             │
│  CLOSED: Requests pasan normalmente                        │
│  ├── Contar fallos consecutivos                            │
│  └── Si fallos > umbral → OPEN                             │
│                                                             │
│  OPEN: Requests fallan inmediatamente                      │
│  ├── No llamar al servicio fallido                         │
│  ├── Retornar fallback o error                             │
│  └── Después de timeout → HALF-OPEN                        │
│                                                             │
│  HALF-OPEN: Probar si servicio se recuperó                 │
│  ├── Permitir algunos requests de prueba                   │
│  ├── Si exitosos → CLOSED                                  │
│  └── Si fallan → OPEN                                      │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Retry con Backoff

ESTRATEGIA DE REINTENTOS
════════════════════════

EXPONENTIAL BACKOFF:
┌─────────────────────────────────────────────────────────────┐
│                                                             │
│  Intento 1: Fallo → Esperar 1s                             │
│  Intento 2: Fallo → Esperar 2s                             │
│  Intento 3: Fallo → Esperar 4s                             │
│  Intento 4: Fallo → Esperar 8s                             │
│  Intento 5: Fallo → Circuit breaker / Error final          │
│                                                             │
│  CON JITTER (aleatoridad):                                 │
│  Espera = base * 2^intento + random(0, 1s)                 │
│                                                             │
│  ¿Por qué jitter?                                          │
│  └── Evita "thundering herd" cuando muchos clientes        │
│      reintentan al mismo tiempo                            │
│                                                             │
└─────────────────────────────────────────────────────────────┘

CUÁNDO REINTENTAR:
┌─────────────────────────────────────────────────────────────┐
│  ✅ Reintentar:                                             │
│  ├── Timeouts                                              │
│  ├── 503 Service Unavailable                               │
│  ├── 429 Too Many Requests (con backoff)                   │
│  └── Errores de red transitorios                           │
│                                                             │
│  ❌ NO reintentar:                                          │
│  ├── 400 Bad Request (error del cliente)                   │
│  ├── 401/403 (autenticación/autorización)                  │
│  ├── 404 Not Found                                         │
│  └── Operaciones no idempotentes                           │
└─────────────────────────────────────────────────────────────┘

Tracking en GitScrum

GESTIONANDO SERVICIOS EN GITSCRUM
═════════════════════════════════

BOARD POR SERVICIO:
┌─────────────────────────────────────────────────────────────┐
│  Payment Service                                            │
│  ──────────────────────────────────────────────────────────│
│  Backlog │ Dev │ Testing │ Staging │ Prod                  │
│                                                             │
│  [Feature: Add retry logic]                                │
│  [Bug: Timeout en high load]                               │
│  [Task: Update API contract]                               │
│                                                             │
│  Dependencies:                                              │
│  ├── Order Service (provides orders)                       │
│  └── Notification Service (consumes PaymentCompleted)      │
│                                                             │
└─────────────────────────────────────────────────────────────┘

LABELS ÚTILES:
┌─────────────────────────────────────────────────────────────┐
│  🔗 api-contract      │ Cambio de API                      │
│  📡 communication     │ Relacionado a comunicación         │
│  🔄 sync-pattern      │ Patrón síncrono                    │
│  📨 async-pattern     │ Patrón asíncrono                   │
│  🔴 breaking-change   │ Cambio incompatible                │
└─────────────────────────────────────────────────────────────┘

Soluciones Relacionadas de GitScrum