0Pricing
FastAPI Backend Development Bootcamp · Lección

Comunicación entre servicios

Implemente distintos patrones de comunicación entre microservicios de FastAPI, como HTTP o colas de mensajes.

Comunicación entre servicios es una lección gratuita de FastAPI Backend Development Bootcamp en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de FastAPI Backend Development Bootcamp, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de FastAPI Backend Development Bootcamp incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Why Services Talk

In a microservices architecture, your application isn't one big program. Instead, it's many smaller, independent services working together. For these services to achieve a common goal, they need to communicate with each other.

Imagine an e-commerce system: one service handles user accounts, another manages product inventory, and a third processes orders. When a user places an order, the order service needs to talk to the inventory service to check stock and the user service to get payment details.

HTTP: Direct Conversations

The most common way for microservices to communicate is through HTTP requests. This is like one service directly calling another service's API endpoint.

  • Synchronous: The calling service waits for a response before continuing.
  • Simple: Easy to understand and implement, especially for request-response patterns.
  • Familiar: Uses the same HTTP protocol you're already familiar with for web browsing.

FastAPI services naturally expose HTTP endpoints, making this a straightforward method.

Making an HTTP Request

In Python, the requests library is excellent for making HTTP calls. Here's how one FastAPI service might call another to get user data.

Assume Service B exposes a /users/{user_id} endpoint, and Service A calls it:

import requests

def get_user_from_service_b(user_id: int):
    # In a real scenario, 'service_b_url' would be a config variable
    service_b_url = f"http://localhost:8001/users/{user_id}"
    try:
        response = requests.get(service_b_url)
        response.raise_for_status() # Raises HTTPError for bad responses (4xx or 5xx)
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"Error calling Service B: {e}")
        return None

if __name__ == "__main__":
    print("Simulating a call to Service B for user 1...")
    user_data = get_user_from_service_b(1)
    if user_data:
        print(f"Received user data: {user_data}")
    else:
        print("Failed to get user data.")
    print("\nNote: For this to truly work, a service B needs to be running at http://localhost:8001.")

Handling HTTP Responses

After making an HTTP request, it's crucial to handle the response properly. This includes checking the HTTP status code and parsing the response body.

  • Status Codes: 200 OK means success, 404 Not Found means the resource wasn't there, 500 Internal Server Error indicates a problem on the server side.
  • Response Body: Often contains data in JSON format, which you can parse using response.json().
  • Error Handling: Always wrap your requests in try-except blocks to catch network issues or server errors.

Resilient HTTP: Timeouts & Retries

Network issues or slow services can cause your HTTP calls to hang or fail. Building resilience into your communication is vital.

  • Timeouts: Set a maximum duration to wait for a response. If the service doesn't respond within this time, the request fails, preventing your service from hanging indefinitely.
  • Retries: If a request fails due to a transient error (e.g., network glitch, temporary service overload), you can automatically retry the request a few times with a delay. Libraries like tenacity can help implement this easily.

These strategies improve the robustness of your microservices.

Message Queues: Decoupling Services

Sometimes, direct HTTP calls aren't the best fit. For tasks that don't require an immediate response, or when you want to reduce direct dependencies between services, message queues are powerful.

A message queue acts as an intermediary, storing messages until a consumer service is ready to process them. Popular examples include RabbitMQ and Apache Kafka.

  • Asynchronous: The sender (producer) doesn't wait for the receiver (consumer) to process the message.
  • Decoupled: Services don't need to know about each other's direct network locations.
  • Scalable: Easily handle spikes in load by adding more consumers.

The Producer-Consumer Model

Message queues operate on a simple principle:

  • Producer: A service that creates and sends messages to a queue. It "fires and forgets" the message.
  • Queue: A temporary storage buffer that holds messages until they are processed.
  • Consumer: A service that listens to a queue, retrieves messages, and processes them.

This model allows for robust, scalable, and fault-tolerant communication, especially for background tasks or event-driven architectures.

Conceptual Message Producer

While a full, runnable message queue example is complex, here's a conceptual Python function illustrating how a service might "send" a message to a queue. In reality, this would involve a client library like pika (for RabbitMQ) or confluent-kafka.

Notice that the sender doesn't wait for the message to be processed; it just places it in the queue.

import json
import time

# This is a simplified, conceptual representation.
# In a real app, 'queue_client' would be an actual library client.

class MockQueueClient:
    def publish(self, queue_name: str, message: dict):
        print(f"[{time.time():.2f}] PRODUCER: Sending message to '{queue_name}'...")
        print(f"  Message content: {json.dumps(message)}")
        # In a real scenario, this would send to a message broker
        print("  (Message sent to broker, producer continues its work)")

def send_new_order_event(order_details: dict):
    queue_client = MockQueueClient()
    queue_client.publish("order_processing_queue", order_details)
    print("PRODUCER: Order event sent successfully.")

if __name__ == "__main__":
    order_info = {"order_id": "ORD001", "item": "Laptop", "quantity": 1}
    send_new_order_event(order_info)
    print("\nPRODUCER: Service continues other tasks while order processes.")

When to Choose HTTP

HTTP communication is generally preferred for:

  • Synchronous Requests: When the calling service needs an immediate response to continue its workflow (e.g., getting user profile data, checking inventory before confirming an order).
  • Request-Response Patterns: Simple queries, data retrieval, or operations where the client expects a direct result.
  • Tight Coupling is Acceptable: When services are designed to work closely together and direct calls are efficient.
  • Real-time User Interactions: Often used for front-end to back-end communication, or when an immediate UI update is needed.

Choosing the Right Tool

You've seen two primary ways services communicate. Each has its strengths. Consider the scenario:

A user submits a complex report generation request that might take several minutes to complete. The user doesn't need to wait for it, but wants to be notified when it's done.

Which communication pattern is best suited for the initial request submission?

Recap: Talking Services

Great job! You've explored the fundamental ways microservices communicate.

  • HTTP: Best for synchronous, request-response interactions where immediate feedback is needed. It's direct and easy to implement using libraries like requests.
  • Message Queues: Ideal for asynchronous, decoupled communication, handling long-running tasks, and enabling event-driven architectures. They use a producer-consumer model for robust message delivery.

Choosing the right pattern depends on your specific needs for coupling, latency, and reliability. In the next lesson, we'll dive into building an API Gateway!

Preguntas frecuentes

¿La lección «Comunicación entre servicios» es gratis?

Sí — el texto completo de «Comunicación entre servicios» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de FastAPI Backend Development Bootcamp, actualiza a CoddyKit PRO. El curso de FastAPI Backend Development Bootcamp incluye 4 lecciones en total.

¿Qué aprenderé en «Comunicación entre servicios»?

Implemente distintos patrones de comunicación entre microservicios de FastAPI, como HTTP o colas de mensajes. Practicas FastAPI Backend Development Bootcamp con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar FastAPI Backend Development Bootcamp?

No se requiere experiencia previa. FastAPI Backend Development Bootcamp en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.

¿Cuánto tiempo toma la lección «Comunicación entre servicios»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de FastAPI Backend Development Bootcamp?

Sí. Cada lección de FastAPI Backend Development Bootcamp incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Diseño de una arquitectura de microservicios
  2. Comunicación entre servicios
  3. Implementación de un API Gateway con FastAPI
  4. Descubrimiento de servicios y comprobaciones de estado
← Volver a FastAPI Backend Development Bootcamp