Repository logo
 
Loading...
Thumbnail Image
Publication

Migrar aplicações REST para gRPC

Use this identifier to reference this record.

Abstract(s)

The communication between services in distributed architectures in microservices has traditionally been supported by REST, due to its simplicity, generalized adoption, and easy integration with multiple platforms. However, as the systems grow in scale and complexity, relevant limitations associated with REST emerge. It is hard to impose, it is built on top of HTTP 1.X and makes use of text formats readable by humans, which is inefficient for service-to-service interactions and there’s the absence of well-defined and strongly typed service definitions. Those limitations become even clearer on systems that require high performance, low latency and strong consistency in service communication. Google’s gRPC presents an as alternative capable of filling those gaps. In particular, gRPC outperforms the traditional REST paradigm, particularly in inter-service communication within microservices architectures, in key metrics such as throughput, response time, bandwidth efficiency, and bi-directional streaming. Moreover, as gRPC uses Protocol Buffers to define services, gRPC service contracts clearly define the types that will be used for interaction between the applications. This helps in overcoming common runtime and interoperability errors that are typically faced when applications are built by multiple teams and different technologies. However, the adoption of gRPC in already developed REST systems is not a straightforward process. It involves technical and organizational challenges, which go from ensuring the compatibility of clients and servers during the transition to the lack of good practices. In addition, the information about how to effectively migrate REST applications to gRPC is extremely limited, as there is a significant gap in academic literature regarding a methodical and strategic way to perform a migration. The work’s objective, at a high level, is to explore, design and compare migration approaches of REST projects to gRPC, and implement one or more of the developed strategies, providing an extensive analysis of the results. That is achieved by delving particularly into gRPC, but also studying other frameworks, dissecting their differences and identifying their benefits and downsides and what led to their adoption. In the end, the final goal is to provide helpful insights and guidelines for engineering teams studying modernization in their communication protocols, contributing to the broader discussion about the transformation and progression of distributed systems and API architectures. For that, a systematic literature review was conducted and then complemented by an analysis of real cases in the industry, in order to identify methodologies, challenges, tools and good practices relevant for the migration process. The systematic review revealed a lack of scientific sources directly focused on a migration from REST to gRPC, with the contributions from technical blogs from companies like WePay, Google Cloud and LinkedIn being very helpful. Those cases showed that a migration can be successful with a proper plan, adoption of gradual strategies, automation tools, and thorough testing. The adopted methodology is based on the practical application of the obtained knowledge by migrating an open-source project, which represents modern microservice-based architectures. The process began with the detailed analysis of each service, endpoint mapping and understanding the interaction between components. Then, the gRPC contracts were defined following strict structure and naming conventions and centralized in a separate repository for the effect in order to make the management, versioning, and integration easier. The automatic generation of code to servers, clients and gateway was done using Protocol Buffer Compiler and the necessary plugins for Java and Go. During the migration, special attention was given to the coexistence of REST and gRPC, resorting to the gRPC Gateway to ensure that REST clients kept working without any changes. This approach allowed a gradual and smooth transition, while minimizing the risks. The validation of the migration’s success was made with automatic and manual tests, especially to ensure functional equivalence after the process is complete. The experience also demonstrated the importance of automation mechanisms in CI pipelines for the generation, publishing and validation of stubs. Among the faced challenges, the lack of a formal API Specification for REST APIs, which requires a manual analysis of the code, and the low test coverage are highlighted. Nevertheless, the acquired experience allowed the definition of a clear set of guidelines to support engineering teams planning a transition. The results showed that the migration of REST systems to gRPC is viable and beneficial, as long as it is thoroughly planned, has a good level of automation, and good engineering practices. The adoption of bridge tools and contract centralization allows for minimizing the risks and ensuring the operational uninterruptedness of the systems during the migration. The experience also highlights the need for as much documentation, testing, and automation as possible.
A comunicação entre serviços em arquiteturas distribuídas de microserviços tem sido tradicionalmente desenvolvida em REST, devido à sua simplicidade, adoção generalizada e fácil integração com múltiplas plataformas. No entanto, à medida que os sistemas crescem em escala e complexidade, surgem limitações relevantes associadas ao REST. É difícil de impor, é desenvolvido em HTTP 1.X e faz uso de formatos de texto legíveis por humanos, o que é ineficiente para interações entre serviços, e há a ausência de definições de serviço bem definidas e fortemente tipadas. Essas limitações tornam-se ainda mais claras em sistemas que requerem alta performance, baixa latência e forte consistência na comunicação entre serviços. O gRPC, desenvolvido pela Google, apresenta-se como uma alternativa capaz de preencher essas lacunas. Em particular, o gRPC ultrapassa o paradigma REST tradicional, especialmente na comunicação inter-serviços dentro de arquiteturas de microserviços, em métricas importantes como throughput, tempo de resposta, eficiência de largura de banda e streaming bidirecional. Além disso, como o gRPC usa Protocol Buffers para definir serviços, os contratos de serviço gRPC definem claramente os tipos que serão usados para interação entre as aplicações. Isso ajuda a ultrapassar erros comuns de runtime e interoperabilidade que são tipicamente enfrentados quando aplicações são construídas por múltiplas equipas e tecnologias diferentes. No entanto, a adoção do gRPC em sistemas REST já desenvolvidos não é um processo direto. Envolve desafios técnicos e organizacionais, que vão desde garantir a compatibilidade de clientes e servidores durante a transição até a falta de boas práticas. Além disso, a informação sobre como migrar efetivamente aplicações REST para gRPC é extremamente limitada, pois há falta de literatura académica no que se refere a uma forma metódica e estratégica de realizar uma migração. O objetivo do trabalho, num nível mais abrangente, é explorar, desenhar e comparar abordagens de migração de projetos REST para gRPC, e implementar uma ou mais das estratégias desenvolvidas, fornecendo uma análise extensa dos resultados. Isso é alcançado aprofundando particularmente o gRPC, mas também estudando outras frameworks, dissecando as suas diferenças e identificando os seus benefícios e desvantagens e o que levou à sua adoção. No final, o objetivo final é fornecer diretrizes para equipas de engenharia que estão a estudar uma modernização nos seus protocolos de comunicação, contribuindo para a discussão mais ampla sobre a transformação e progressão de sistemas distribuídos e arquiteturas de API. Para isso, foi conduzida uma revisão sistemática da literatura e depois complementada por uma análise de casos reais na indústria, de forma a identificar metodologias, desafios, ferramentas e boas práticas relevantes para o processo de migração. A revisão sistemática revelou uma falta de fontes científicas diretamente focadas numa migração de REST para gRPC, sendo as contribuições de blogs técnicos de empresas como WePay, Google Cloud e LinkedIn muito úteis. Esses casos mostraram que uma migração pode ser bem-sucedida com um plano adequado, adoção de estratégias graduais, ferramentas de automação e testes rigorosos. A metodologia adotada baseia-se na aplicação prática do conhecimento obtido através da migração de um projeto open-source, que representa arquiteturas modernas baseadas em microserviços. O processo começou com a análise detalhada de cada serviço, mapeamento de endpoints e compreensão da interação entre componentes. Em seguida, os contratos gRPC foram definidos seguindo uma estrutura rigorosa e convenções de nomenclatura e centralizados num repositório separado para o efeito, de forma a tornar a gestão, versionamento e integração mais fáceis. A geração automática de código para servidores, clientes e gateway foi feita usando o Protocol Buffer Compiler e os plugins necessários para Java e Go. Durante a migração, foi dada especial atenção à coexistência de REST e gRPC, recorrendo ao gRPC Gateway para garantir que os clientes REST continuassem a funcionar sem quaisquer alterações. Esta abordagem permitiu uma transição gradual e suave, minimizando os riscos. A validação do sucesso da migração foi feita com testes automáticos e manuais, especialmente para garantir a equivalência funcional após o processo estar completo. A experiência também demonstrou a importância de mecanismos de automação em pipelines CI para a geração, publicação e validação de stubs. Entre os desafios enfrentados, destacam-se a falta de uma especificação de API formal para APIs REST, que requer uma análise manual do código, e a baixa cobertura de testes. Não obstante, a experiência adquirida permitiu a definição de um conjunto claro de diretrizes para apoiar equipas de engenharia que planeiam uma transição. Os resultados mostraram que a migração de sistemas REST para gRPC é viável e benéfica, desde que seja minuciosamente planeada, tenha um bom nível de automação e boas práticas de engenharia. A adoção de ferramentas de que fazema a ponte entre sistemas e centralização de contratos permite minimizar os riscos e garantir a continuidade operacional dos sistemas durante a migração. A experiência também destaca a necessidade de tanta documentação, testes e automação quanto possível.

Description

Keywords

gRPC REST software migration

Pedagogical Context

Citation

Research Projects

Organizational Units

Journal Issue

Publisher

CC License

Without CC licence