Middle
What types of interactions between microservices exist?
sobes.tech AI
Answer from AI
-
Synchronous interaction (Request/Response): ServiceB waits for a response from ServiceA before continuing execution.
- HTTP/REST
- gRPC
-
Asynchronous interaction (Event-driven): ServiceA sends a message or event to a message broker, and ServiceB subscribes to these events and processes them independently.
- Message brokers (Kafka, RabbitMQ, ActiveMQ)
- Message queues (SQS, Azure Service Bus)
-
Mixed interaction: A combination of synchronous and asynchronous approaches. For example, synchronous requests for data retrieval and asynchronous events for change notifications.
Comparison table:
| Type of interaction | Advantages | Disadvantages |
|---|---|---|
| Synchronous | Implementation simplicity, predictable data flow | High coupling, blocking, cascading failures |
| Asynchronous | Low coupling, scalability, resilience | Debugging complexity, eventual consistency, state management |
Example of asynchronous interaction (pseudo-code):
<?php
// Service A (Publisher)
class OrderService
{
private MessageBroker $broker;
public function __construct(MessageBroker $broker)
{
$this->broker = $broker;
}
public function placeOrder(array $orderData): void
{
// Order processing...
echo "Order placed.";
// Publish event
$this->broker->publish('order.placed', json_encode($orderData));
}
}
// Service B (Subscriber)
class ShippingService
{
private MessageBroker $broker;
public function __construct(MessageBroker $broker)
{
$this->broker = $broker;
$this->broker->subscribe('order.placed', [$this, 'handleOrderPlaced']);
}
public function handleOrderPlaced(string $eventPayload): void
{
$orderData = json_decode($eventPayload, true);
// Handle event: initiate delivery
echo "Shipping order for customer {$orderData['customer_id']}.";
}
}
// Usage example (simplified)
// $broker = new RabbitMQBroker(); // Or another broker
// $orderService = new OrderService($broker);
// $shippingService = new ShippingService($broker);
//
// $orderService->placeOrder(['customer_id' => 123, 'items' => [...]]);