Ways of communication between services in a Microservice system

Anh Trần Tuấn - Aug 16 - - Dev Community

1. Synchronous Communication

Synchronous communication involves a real-time interaction where one service sends a request to another and pauses its operation until a response is received. REST APIs and gRPC are common protocols used to facilitate this type of communication.

Image

1.1 RESTful API

A RESTful API (Representational State Transfer) is one of the most common methods for services to communicate with each other in a microservices system. REST utilizes HTTP/HTTPS and JSON or XML formats for data exchange.

Typically, services interact with each other by directly invoking the API of another service.

Example request and response:

GET /users/12345 HTTP/1.1
Host: api.userservice.com
Accept: application/json
Authorization: Bearer your-access-token

{
  "userId": "12345",
  "name": "Michel J",
  "email": "MJ@example.com",
  "address": "Mountain View, Santa Clara, California"
}
Enter fullscreen mode Exit fullscreen mode

Source code example

import org.springframework.web.client.RestTemplate;
import org.springframework.http.ResponseEntity;

public class OrderService {

    private final RestTemplate restTemplate = new RestTemplate();
    private final String userServiceUrl = "https://api.userservice.com/users/";

    public User getUserById(String userId) {
        String url = userServiceUrl + userId;
        ResponseEntity<User> response = restTemplate.getForEntity(url, User.class);
        return response.getBody();
    }
}
Enter fullscreen mode Exit fullscreen mode

Advantages:

Easy to deploy and integrate with various languages and tools.

Can easily use testing and monitoring tools.

Disadvantages:

May not be efficient for high-speed requirements due to its synchronous nature.

May encounter difficulties in handling network errors or disconnections.

1.2 gRPC

gRPC, standing for Google Remote Procedure Call, is a high-performance, open-source universal RPC framework. It utilizes HTTP/2 for efficient data transfer and typically relies on Protocol Buffers, a language-neutral, platform-neutral, extensible mechanism for serializing structured data, to define the structure of the data being sent and received.

Example, Definition of Protocol Buffers

syntax = "proto3";

package userservice;

// Define message User
message User {
    string userId = 1;
    string name = 2;
    string email = 3;
    string address = 4;
}

// Define service UserService
service UserService {
    rpc GetUserById (UserIdRequest) returns (User);
}

// Define message UserIdRequest
message UserIdRequest {
    string userId = 1;
}
Enter fullscreen mode Exit fullscreen mode

For the User Management service, you should implement a gRPC server that adheres to the service definition provided in the .proto file. This includes creating the necessary server-side logic to handle incoming gRPC requests and generate appropriate responses.

import io.grpc.stub.StreamObserver;
import userservice.User;
import userservice.UserIdRequest;
import userservice.UserServiceGrpc;

public class UserServiceImpl extends UserServiceGrpc.UserServiceImplBase {

    @Override
    public void getUserById(UserIdRequest request, StreamObserver<User> responseObserver) {
        // Assuming you have a database to retrieve user information.
        User user = User.newBuilder()
                .setUserId(request.getUserId())
                .setName("Michel J")
                .setEmail("MJ@example.com")
                .setAddress("Mountain View, Santa Clara, California")
                .build();

        responseObserver.onNext(user);
        responseObserver.onCompleted();
    }
}

import io.grpc.Server;
import io.grpc.ServerBuilder;

public class UserServer {
    public static void main(String[] args) throws Exception {
        Server server = ServerBuilder.forPort(9090)
                .addService(new UserServiceImpl())
                .build()
                .start();

        System.out.println("Server started on port 9090");
        server.awaitTermination();
    }
}
Enter fullscreen mode Exit fullscreen mode

Advantages:

High performance and bandwidth efficiency due to the use of HTTP/2 and Protocol Buffers.

Supports multiple programming languages and has good scalability.

Disadvantages:

Requires a translation layer if services do not support gRPC.

Can be more complex to deploy and manage.

2. Asynchronous Communication

Asynchronous communication refers to the process of a service sending a request to another service without blocking its own operation to await a reply. This is commonly achieved through message queues or publish/subscribe systems.

Image

1. Message Queues

Message queuing systems, like RabbitMQ and Apache ActiveMQ, facilitate asynchronous communication between services.

Advantages:

Improved scalability and fault tolerance: The system can better handle increased workloads and is less susceptible to failures.

Reduced load on services: By decoupling request sending and receiving, the main services can focus on processing tasks without being overwhelmed by constant requests.

Disadvantages:

May require additional effort to manage and maintain: Queue-based systems can be more complex and require more resources to operate.

Difficulty in handling ordering and ensuring message delivery: Ensuring that requests are processed in the correct order and that no messages are lost can be a technical challenge.

2.2. Pub/Sub System

A Pub/Sub (Publish/Subscribe) system, such as Apache Kafka or Google Pub/Sub, allows services to publish messages and subscribe to topics.

Advantages:

Supports large scale and high throughput data streams.

Reduces dependencies between services.

Disadvantages:

Requires a more complex layer to manage and monitor topics and messages.

Can be challenging to handle ordering and reliability issues with messages."

If you are interested, you can read my previous articles on the pub/sub topic.

Dead Letter Queue in a Message Broker part 1

Dead Letter Queue in a Message Broker part 2

Consistency and reliability concerns within the Message Broker system

3. Event-Driven Communication

Event-driven communication is when a service emits an event and other services respond or take actions based on those events.

3.1. Synchronous Events

Synchronous events occur when a service emits an event and waits for a response from other services.

Advantages:

Easy to control and monitor the event processing process.

Disadvantages:

Can cause bottlenecks if responding services are slow or encounter errors

3.2. Asynchronous Events

Asynchronous events occur when a service emits an event and does not need to wait for an immediate response.

Advantages:

Reduces waiting time and improves scalability.

Helps services operate more independently and reduces mutual dependencies.

Disadvantages:

Requires additional mechanisms to ensure events are processed correctly and timely.

Difficulty in ensuring order and handling duplicate events.

4. Conclusion

The choice of communication method between services in a microservices system depends on factors such as performance requirements, reliability, and system complexity. Each method has its own advantages and disadvantages, and understanding these methods will help you build a more efficient and flexible microservices system. Carefully consider the requirements of your system to choose the most suitable communication method.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player