SlideShare a Scribd company logo
1 of 22
Download to read offline
Microservices Communication
Patterns with gRPC
Kasun Indrasiri
Author “gRPC Up and Running”, Product Manager @WSO2
About Me
● Author “gRPC Up & Running”, “Microservices for Enterprise”
● Product Manager/Senior Director at WSO2.
● Committer and PMC member at Apache Software Foundation.
● Founder “Bay area Microservices, APIs and Integration” meetup
group.
What is gRPC?
● Modern Inter-process communication technology.
● Invoking remote functions as easy as making a local function invocation.
● Contract-first.
● Binary messaging on the wire on top of HTTP2
● Polyglot.
● Defines the business capabilities of
your service.
● Protocol Buffers used as the IDL for
define services.
● Protocol Buffers :
○ A language-agnostic, platform-neutral,
extensible mechanism to serializing
structured data.
● Defines service, remote methods, and
data types.
Fundamentals of gRPC - Service Definition
syntax = "proto3";
package ecommerce;
service ProductInfo {
rpc addProduct(Product) returns (ProductID);
rpc getProduct(ProductID) returns (Product);
}
message Product {
string id = 1;
string name = 2;
string description = 3;
float price = 4;
}
message ProductID {
string value = 1;
}
ProductInfo.proto
Fundamentals of gRPC - gRPC Service
● gRPC service implements the
business logic.
● Generate server side skeleton from
service definition.
● Implements business logic on top of
the generated code.
● Run server application.
// AddProduct implements ecommerce.AddProduct
func (s *server) AddProduct(ctx context.Context,
in *pb.Product) (*pb.ProductID,
error) {
// Business logic
}
// GetProduct implements ecommerce.GetProduct
func (s *server) GetProduct(ctx context.Context, in
*pb.ProductID) (*pb.Product, error) {
// Business logic
}
// gRPC server
func main() {
lis, err := net.Listen( "tcp", port)
...
s := grpc.NewServer()
pb.RegisterProductInfoServer(s, &server{})
if err := s.Serve(lis); err != nil {
log.Fatalf( "failed to serve: %v" , err)
}
}
Fundamentals of gRPC - gRPC Client
● Connect to a gRPC service and
invokes a remote method.
● Generate client-side code(client stub)
from service definition and invoke the
remote method.
ManagedChannel channel =
ManagedChannelBuilder.forAddress("localhost", 50051)
.usePlaintext()
.build();
ProductInfoGrpc.ProductInfoBlockingStub stub =
ProductInfoGrpc.newBlockingStub(channel);
ProductInfoOuterClass.Product product =
stub.getProduct(productID);
logger.info("Product: " + product.toString());
Why gRPC?
● Efficient.
● Strict specification and well-defined service contracts.
● Strongly Typed.
● Polyglot.
● Duplex Streaming.
● Native integration with cloud native ecosystem.
gRPC in the Microservices Landscape
● Coexistence of gRPC with other communication protocols.
gRPC vs OpenAPI/REST vs GraphQL
REST/OAS
Protocol HTTP 1.x, HTTP2 HTTP2 HTTP 1.x, HTTP2
Payload Text - JSON, XML
(large, human readable)
Binary - Protocol Buffers
(small, binary)
Text - JSON
Service Definition OAS (optional) gRPC IDL/Protocol
Buffer(required)
GraphQL (required)
Code generation Optional, via third party libs Required and natively
supported.
Optional
Prescriptiveness Loose, (need to follow best
practices)
Strict Strict
Streaming No first class support First class support No first class support
Browser support Yes No (require grpc-web) Yes
Unary/Simple RPC
● Client sends a single request to the
server and gets a single response.
service OrderManagement {
rpc getOrder(google.protobuf.StringValue) returns (Order);
}
message Order { ... }
order_mgt.proto
c := pb.NewOrderManagementClient(conn)
retrievedOrder , err := c.GetOrder(ctx,
&wrapper.StringValue{Value: "106"})
gRPC Client (Go)
func (s *server) GetOrder(ctx context.Context, orderId
*wrapper.StringValue) (*pb.Order, error) {
ord := orderMap[orderId.Value]
return &ord, nil
}
Service Impl (Go)
Server Streaming RPC
● Server sends back a sequence of
responses(stream) after getting the
client’s request message.
● After sending all the responses
server marks the end of stream.
service OrderManagement {
rpc searchOrders(google.protobuf.StringValue) returns
(stream Order);
}
message Order { ... }
order_mgt.proto
searchStream, _ := c.SearchOrders(ctx,
&wrapper.StringValue{Value: "Google"})
searchOrder, err := searchStream.Recv()
gRPC Client (Go)
func (s *server) SearchOrders(searchQuery
*wrappers.StringValue, stream
pb.OrderManagement_SearchOrdersServer) error {
// Business logic
stream.Send(&order1)
stream.Send(&order2)
return nil
}
Service Impl (Go)
Client Streaming RPC
● Client sends multiple messages to
the server instead of a single
request.
● Server sends back a single response
to the client.
service OrderManagement {
rpc updateOrders(stream Order) returns
(google.protobuf.StringValue);
}
order_mgt.proto
updateStream, _ := c.UpdateOrders(ctx)
_ = updateStream.Send(&updOrder1)
_ = updateStream.Send(&updOrder2)
_ = updateStream.Send(&updOrder3)
updateRes, _ := updateStream.CloseAndRecv()
gRPC Client (Go)
func (s *server) UpdateOrders(stream
pb.OrderManagement_UpdateOrdersServer) error {
for {
order, err := stream.Recv()
if err == io.EOF {
// Finished reading the order stream.
return stream.SendAndClose(&wrapper.StringValue{
Value: "Orders processed " + ordersStr})
} ...
Service Impl (Go)
Bidirectional-Streaming RPC
● Client is sending a request to the
server as a stream of messages.
● Server also responds with a stream
of messages.
● Client has to initiated the RPC.
rpc processOrders(stream google.protobuf.StringValue)
returns (stream CombinedShipment);
order_mgt.proto
streamProcOrder, _ := c.ProcessOrders(ctx)
_ = streamProcOrder.Send(&wrapper.StringValue{Value:"102"})
_ = streamProcOrder.Send(&wrapper.StringValue{Value:"103"})
...
channel := make(chan bool, 1)
go asncClientBidirectionalRPC(streamProcOrder, channel)
...
gRPC Client (Go)
func (s *server) ProcessOrders(stream
pb.OrderManagement_ProcessOrdersServer) error {
...
for {
orderId, err := stream.Recv()
for _, comb := range combinedShipmentMap {
stream.Send(&comb)
} ...
Service Impl (Go)
gRPC Interceptors
● Mechanism to execute some common
logic before or after the execution of the
remote function for server or client
application.
● Server Side and Client Side interceptors.
● Unary Interceptors
○ Phases : preprocessing, invoking the RPC
method, and postprocessing
● Streaming interceptors
○ Intercepts any streaming RPC
● Useful for logging, authentication, metrics
etc.
Deadlines
● A deadline is expressed in absolute
time from the beginning of a request
and applied across multiple service
invocations.
● gRPC client applications sets
deadline when invoking remote
functions.
clientDeadline := time.Now().Add(time.Duration(2 *
time.Second))
ctx, cancel := context.WithDeadline(context.Background(),
clientDeadline)
// Invoke RPC
gRPC Client App
Metadata
● Information directly related to the service’s
business logic and consumer is part of the
remote method invocation arguments.
● Use Metadata to share information about the
RPC calls that are not related to the business
context of the RPC (e.g. Security Headers)
● Structured as K-V pairs.
● Exchanged as gRPC headers.
Multiplexing
● Running multiple gRPC services on the
same gRPC server.
grpcServer := grpc.NewServer()
// Register Order Management service on gRPC orderMgtServer
ordermgt_pb.RegisterOrderManagementServer(grpcServer,
&orderMgtServer{})
// Register Greeter Service on gRPC orderMgtServer
hello_pb.RegisterGreeterServer(grpcServer, &helloServer{})
gRPC Server App
Cancellation
● When either the client or server application wants to terminate the RPC this
can be done by Cancelling the RPC.
● No further RPCs can be done over that connection.
● When one party cancels the RPC, the other party can determine it by checking
the context of the RPC.
○ E.g. stream.Context().Err() == context.Canceled.
API Management with gRPC
● Managed gRPC services.
○ Management at Remote method level or service level.
○ Authentication
■ Authentication schemes are JWT, Basic Auth and API Key
○ Authorization
■ Granular authorization at method level.
○ Rate limiting
■ Applied for per-service or per-method basis.
● Versioning
○ Versioning at protocol buffer packages. E.g. ‘package product.v1;’
● API definition
○ Extend protocol buffer definition to cater to API Management features.
REST/Open API ←→ gRPC Bridge
● gRPC Gateway : REST/HTTP 1.1 -> gRPC Bridge.
● gRPC gateway plug-in enables the protocol buffer
compiler to read the gRPC service definition and
generate a reverse proxy server, which translates
a RESTful JSON API into gRPC.
Resources
● gRPC Up and Running Book.
○ Gives you a comprehensive understanding of gRPC.
○ gRPC communication patterns and advanced concepts.
○ Running gRPC in production.
○ Dozens of samples written in Go and Java.
● Use cases and source code in Java and Go -
https://grpc-up-and-running.github.io/
● gRPC.io
● Visit WSO2 booth!
Thank You

More Related Content

What's hot

Kong, Keyrock, Keycloak, i4Trust - Options to Secure FIWARE in Production
Kong, Keyrock, Keycloak, i4Trust - Options to Secure FIWARE in ProductionKong, Keyrock, Keycloak, i4Trust - Options to Secure FIWARE in Production
Kong, Keyrock, Keycloak, i4Trust - Options to Secure FIWARE in ProductionFIWARE
 
Common issues with Apache Kafka® Producer
Common issues with Apache Kafka® ProducerCommon issues with Apache Kafka® Producer
Common issues with Apache Kafka® Producerconfluent
 
Design Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIsDesign Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIsStormpath
 
Building a Microservices-based ERP System
Building a Microservices-based ERP SystemBuilding a Microservices-based ERP System
Building a Microservices-based ERP SystemMongoDB
 
Spring Cloud Gateway
Spring Cloud GatewaySpring Cloud Gateway
Spring Cloud GatewayVMware Tanzu
 
KSQL-ops! Running ksqlDB in the Wild (Simon Aubury, ThoughtWorks) Kafka Summi...
KSQL-ops! Running ksqlDB in the Wild (Simon Aubury, ThoughtWorks) Kafka Summi...KSQL-ops! Running ksqlDB in the Wild (Simon Aubury, ThoughtWorks) Kafka Summi...
KSQL-ops! Running ksqlDB in the Wild (Simon Aubury, ThoughtWorks) Kafka Summi...confluent
 
What is gRPC introduction gRPC Explained
What is gRPC introduction gRPC ExplainedWhat is gRPC introduction gRPC Explained
What is gRPC introduction gRPC Explainedjeetendra mandal
 
[Main Session] 카프카, 데이터 플랫폼의 최강자
[Main Session] 카프카, 데이터 플랫폼의 최강자[Main Session] 카프카, 데이터 플랫폼의 최강자
[Main Session] 카프카, 데이터 플랫폼의 최강자Oracle Korea
 
Resilience testing with Wiremock and Spock
Resilience testing with Wiremock and SpockResilience testing with Wiremock and Spock
Resilience testing with Wiremock and SpockDavid Schmitz
 
Implementing security requirements for banking API system using Open Source ...
 Implementing security requirements for banking API system using Open Source ... Implementing security requirements for banking API system using Open Source ...
Implementing security requirements for banking API system using Open Source ...Yuichi Nakamura
 
Working with Terraform on Azure
Working with Terraform on AzureWorking with Terraform on Azure
Working with Terraform on Azuretombuildsstuff
 
Big Data Redis Mongodb Dynamodb Sharding
Big Data Redis Mongodb Dynamodb ShardingBig Data Redis Mongodb Dynamodb Sharding
Big Data Redis Mongodb Dynamodb ShardingAraf Karsh Hamid
 
gRPC Design and Implementation
gRPC Design and ImplementationgRPC Design and Implementation
gRPC Design and ImplementationVarun Talwar
 
Introduction to Kafka Streams
Introduction to Kafka StreamsIntroduction to Kafka Streams
Introduction to Kafka StreamsGuozhang Wang
 
Reactive Card Magic: Understanding Spring WebFlux and Project Reactor
Reactive Card Magic: Understanding Spring WebFlux and Project ReactorReactive Card Magic: Understanding Spring WebFlux and Project Reactor
Reactive Card Magic: Understanding Spring WebFlux and Project ReactorVMware Tanzu
 
Grafana optimization for Prometheus
Grafana optimization for PrometheusGrafana optimization for Prometheus
Grafana optimization for PrometheusMitsuhiro Tanda
 
Real Time UI with Apache Kafka Streaming Analytics of Fast Data and Server Push
Real Time UI with Apache Kafka Streaming Analytics of Fast Data and Server PushReal Time UI with Apache Kafka Streaming Analytics of Fast Data and Server Push
Real Time UI with Apache Kafka Streaming Analytics of Fast Data and Server PushLucas Jellema
 

What's hot (20)

Hashicorp Vault ppt
Hashicorp Vault pptHashicorp Vault ppt
Hashicorp Vault ppt
 
Kong, Keyrock, Keycloak, i4Trust - Options to Secure FIWARE in Production
Kong, Keyrock, Keycloak, i4Trust - Options to Secure FIWARE in ProductionKong, Keyrock, Keycloak, i4Trust - Options to Secure FIWARE in Production
Kong, Keyrock, Keycloak, i4Trust - Options to Secure FIWARE in Production
 
Grafana
GrafanaGrafana
Grafana
 
Common issues with Apache Kafka® Producer
Common issues with Apache Kafka® ProducerCommon issues with Apache Kafka® Producer
Common issues with Apache Kafka® Producer
 
Apache kafka
Apache kafkaApache kafka
Apache kafka
 
Design Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIsDesign Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIs
 
Building a Microservices-based ERP System
Building a Microservices-based ERP SystemBuilding a Microservices-based ERP System
Building a Microservices-based ERP System
 
Spring Cloud Gateway
Spring Cloud GatewaySpring Cloud Gateway
Spring Cloud Gateway
 
KSQL-ops! Running ksqlDB in the Wild (Simon Aubury, ThoughtWorks) Kafka Summi...
KSQL-ops! Running ksqlDB in the Wild (Simon Aubury, ThoughtWorks) Kafka Summi...KSQL-ops! Running ksqlDB in the Wild (Simon Aubury, ThoughtWorks) Kafka Summi...
KSQL-ops! Running ksqlDB in the Wild (Simon Aubury, ThoughtWorks) Kafka Summi...
 
What is gRPC introduction gRPC Explained
What is gRPC introduction gRPC ExplainedWhat is gRPC introduction gRPC Explained
What is gRPC introduction gRPC Explained
 
[Main Session] 카프카, 데이터 플랫폼의 최강자
[Main Session] 카프카, 데이터 플랫폼의 최강자[Main Session] 카프카, 데이터 플랫폼의 최강자
[Main Session] 카프카, 데이터 플랫폼의 최강자
 
Resilience testing with Wiremock and Spock
Resilience testing with Wiremock and SpockResilience testing with Wiremock and Spock
Resilience testing with Wiremock and Spock
 
Implementing security requirements for banking API system using Open Source ...
 Implementing security requirements for banking API system using Open Source ... Implementing security requirements for banking API system using Open Source ...
Implementing security requirements for banking API system using Open Source ...
 
Working with Terraform on Azure
Working with Terraform on AzureWorking with Terraform on Azure
Working with Terraform on Azure
 
Big Data Redis Mongodb Dynamodb Sharding
Big Data Redis Mongodb Dynamodb ShardingBig Data Redis Mongodb Dynamodb Sharding
Big Data Redis Mongodb Dynamodb Sharding
 
gRPC Design and Implementation
gRPC Design and ImplementationgRPC Design and Implementation
gRPC Design and Implementation
 
Introduction to Kafka Streams
Introduction to Kafka StreamsIntroduction to Kafka Streams
Introduction to Kafka Streams
 
Reactive Card Magic: Understanding Spring WebFlux and Project Reactor
Reactive Card Magic: Understanding Spring WebFlux and Project ReactorReactive Card Magic: Understanding Spring WebFlux and Project Reactor
Reactive Card Magic: Understanding Spring WebFlux and Project Reactor
 
Grafana optimization for Prometheus
Grafana optimization for PrometheusGrafana optimization for Prometheus
Grafana optimization for Prometheus
 
Real Time UI with Apache Kafka Streaming Analytics of Fast Data and Server Push
Real Time UI with Apache Kafka Streaming Analytics of Fast Data and Server PushReal Time UI with Apache Kafka Streaming Analytics of Fast Data and Server Push
Real Time UI with Apache Kafka Streaming Analytics of Fast Data and Server Push
 

Similar to Microservices Communication Patterns with gRPC

Driving containerd operations with gRPC
Driving containerd operations with gRPCDriving containerd operations with gRPC
Driving containerd operations with gRPCDocker, Inc.
 
gRPC and Microservices
gRPC and MicroservicesgRPC and Microservices
gRPC and MicroservicesJonathan Gomez
 
Bringing Learnings from Googley Microservices with gRPC - Varun Talwar, Google
Bringing Learnings from Googley Microservices with gRPC - Varun Talwar, GoogleBringing Learnings from Googley Microservices with gRPC - Varun Talwar, Google
Bringing Learnings from Googley Microservices with gRPC - Varun Talwar, GoogleAmbassador Labs
 
Build microservice with gRPC in golang
Build microservice with gRPC in golangBuild microservice with gRPC in golang
Build microservice with gRPC in golangTing-Li Chou
 
Microservices summit talk 1/31
Microservices summit talk   1/31Microservices summit talk   1/31
Microservices summit talk 1/31Varun Talwar
 
CRUD Operation With Dgraph
CRUD Operation With DgraphCRUD Operation With Dgraph
CRUD Operation With DgraphKnoldus Inc.
 
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...apidays
 
What we learnt at carousell tw for golang gathering #31
What we learnt at carousell tw for golang gathering #31What we learnt at carousell tw for golang gathering #31
What we learnt at carousell tw for golang gathering #31Ronald Hsu
 
Building a maintainable bi-directional cross platform protocol
Building a maintainable bi-directional cross platform protocolBuilding a maintainable bi-directional cross platform protocol
Building a maintainable bi-directional cross platform protocolPavel Dovbush
 
gRPC or Rest, why not both?
gRPC or Rest, why not both?gRPC or Rest, why not both?
gRPC or Rest, why not both?Mohammad Murad
 
gRPC - Fastest Data Transfer Protocol
gRPC - Fastest Data Transfer ProtocolgRPC - Fastest Data Transfer Protocol
gRPC - Fastest Data Transfer ProtocolSougata Pal
 
The new (is it really ) api stack
The new (is it really ) api stackThe new (is it really ) api stack
The new (is it really ) api stackLuca Mattia Ferrari
 
APIdays Helsinki 2019 - gRPC: Lightning Fast, Self-Documenting APIs with Moha...
APIdays Helsinki 2019 - gRPC: Lightning Fast, Self-Documenting APIs with Moha...APIdays Helsinki 2019 - gRPC: Lightning Fast, Self-Documenting APIs with Moha...
APIdays Helsinki 2019 - gRPC: Lightning Fast, Self-Documenting APIs with Moha...apidays
 
Up and Running with gRPC & Cloud Career [GDG-Cloud-Dhaka-IO/2022}
Up and Running with gRPC & Cloud Career [GDG-Cloud-Dhaka-IO/2022}Up and Running with gRPC & Cloud Career [GDG-Cloud-Dhaka-IO/2022}
Up and Running with gRPC & Cloud Career [GDG-Cloud-Dhaka-IO/2022}Md. Sadhan Sarker
 
ASP.NET Core 3.0 Deep Dive
ASP.NET Core 3.0 Deep DiveASP.NET Core 3.0 Deep Dive
ASP.NET Core 3.0 Deep DiveJon Galloway
 
Implementing OpenAPI and GraphQL services with gRPC
Implementing OpenAPI and GraphQL services with gRPCImplementing OpenAPI and GraphQL services with gRPC
Implementing OpenAPI and GraphQL services with gRPCTim Burks
 

Similar to Microservices Communication Patterns with gRPC (20)

Apa itu gRPC_.pptx
Apa itu gRPC_.pptxApa itu gRPC_.pptx
Apa itu gRPC_.pptx
 
Driving containerd operations with gRPC
Driving containerd operations with gRPCDriving containerd operations with gRPC
Driving containerd operations with gRPC
 
gRPC and Microservices
gRPC and MicroservicesgRPC and Microservices
gRPC and Microservices
 
gRPC services testing
gRPC services testinggRPC services testing
gRPC services testing
 
GRPC.pptx
GRPC.pptxGRPC.pptx
GRPC.pptx
 
Bringing Learnings from Googley Microservices with gRPC - Varun Talwar, Google
Bringing Learnings from Googley Microservices with gRPC - Varun Talwar, GoogleBringing Learnings from Googley Microservices with gRPC - Varun Talwar, Google
Bringing Learnings from Googley Microservices with gRPC - Varun Talwar, Google
 
Build microservice with gRPC in golang
Build microservice with gRPC in golangBuild microservice with gRPC in golang
Build microservice with gRPC in golang
 
Microservices summit talk 1/31
Microservices summit talk   1/31Microservices summit talk   1/31
Microservices summit talk 1/31
 
gRPC in Go
gRPC in GogRPC in Go
gRPC in Go
 
CRUD Operation With Dgraph
CRUD Operation With DgraphCRUD Operation With Dgraph
CRUD Operation With Dgraph
 
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...
 
What we learnt at carousell tw for golang gathering #31
What we learnt at carousell tw for golang gathering #31What we learnt at carousell tw for golang gathering #31
What we learnt at carousell tw for golang gathering #31
 
Building a maintainable bi-directional cross platform protocol
Building a maintainable bi-directional cross platform protocolBuilding a maintainable bi-directional cross platform protocol
Building a maintainable bi-directional cross platform protocol
 
gRPC or Rest, why not both?
gRPC or Rest, why not both?gRPC or Rest, why not both?
gRPC or Rest, why not both?
 
gRPC - Fastest Data Transfer Protocol
gRPC - Fastest Data Transfer ProtocolgRPC - Fastest Data Transfer Protocol
gRPC - Fastest Data Transfer Protocol
 
The new (is it really ) api stack
The new (is it really ) api stackThe new (is it really ) api stack
The new (is it really ) api stack
 
APIdays Helsinki 2019 - gRPC: Lightning Fast, Self-Documenting APIs with Moha...
APIdays Helsinki 2019 - gRPC: Lightning Fast, Self-Documenting APIs with Moha...APIdays Helsinki 2019 - gRPC: Lightning Fast, Self-Documenting APIs with Moha...
APIdays Helsinki 2019 - gRPC: Lightning Fast, Self-Documenting APIs with Moha...
 
Up and Running with gRPC & Cloud Career [GDG-Cloud-Dhaka-IO/2022}
Up and Running with gRPC & Cloud Career [GDG-Cloud-Dhaka-IO/2022}Up and Running with gRPC & Cloud Career [GDG-Cloud-Dhaka-IO/2022}
Up and Running with gRPC & Cloud Career [GDG-Cloud-Dhaka-IO/2022}
 
ASP.NET Core 3.0 Deep Dive
ASP.NET Core 3.0 Deep DiveASP.NET Core 3.0 Deep Dive
ASP.NET Core 3.0 Deep Dive
 
Implementing OpenAPI and GraphQL services with gRPC
Implementing OpenAPI and GraphQL services with gRPCImplementing OpenAPI and GraphQL services with gRPC
Implementing OpenAPI and GraphQL services with gRPC
 

More from WSO2

Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessWSO2
 
How to Create a Service in Choreo
How to Create a Service in ChoreoHow to Create a Service in Choreo
How to Create a Service in ChoreoWSO2
 
Ballerina Tech Talk - May 2023
Ballerina Tech Talk - May 2023Ballerina Tech Talk - May 2023
Ballerina Tech Talk - May 2023WSO2
 
Platform Strategy to Deliver Digital Experiences on Azure
Platform Strategy to Deliver Digital Experiences on AzurePlatform Strategy to Deliver Digital Experiences on Azure
Platform Strategy to Deliver Digital Experiences on AzureWSO2
 
GartnerITSymSessionSlides.pdf
GartnerITSymSessionSlides.pdfGartnerITSymSessionSlides.pdf
GartnerITSymSessionSlides.pdfWSO2
 
[Webinar] How to Create an API in Minutes
[Webinar] How to Create an API in Minutes[Webinar] How to Create an API in Minutes
[Webinar] How to Create an API in MinutesWSO2
 
Modernizing the Student Journey with Ethos Identity
Modernizing the Student Journey with Ethos IdentityModernizing the Student Journey with Ethos Identity
Modernizing the Student Journey with Ethos IdentityWSO2
 
Choreo - Build unique digital experiences on WSO2's platform, secured by Etho...
Choreo - Build unique digital experiences on WSO2's platform, secured by Etho...Choreo - Build unique digital experiences on WSO2's platform, secured by Etho...
Choreo - Build unique digital experiences on WSO2's platform, secured by Etho...WSO2
 
CIO Summit Berlin 2022.pptx.pdf
CIO Summit Berlin 2022.pptx.pdfCIO Summit Berlin 2022.pptx.pdf
CIO Summit Berlin 2022.pptx.pdfWSO2
 
Delivering New Digital Experiences Fast - Introducing Choreo
Delivering New Digital Experiences Fast - Introducing ChoreoDelivering New Digital Experiences Fast - Introducing Choreo
Delivering New Digital Experiences Fast - Introducing ChoreoWSO2
 
Fueling the Digital Experience Economy with Connected Products
Fueling the Digital Experience Economy with Connected ProductsFueling the Digital Experience Economy with Connected Products
Fueling the Digital Experience Economy with Connected ProductsWSO2
 
A Reference Methodology for Agile Digital Businesses
 A Reference Methodology for Agile Digital Businesses A Reference Methodology for Agile Digital Businesses
A Reference Methodology for Agile Digital BusinessesWSO2
 
Workflows in WSO2 API Manager - WSO2 API Manager Community Call (12/15/2021)
Workflows in WSO2 API Manager - WSO2 API Manager Community Call (12/15/2021)Workflows in WSO2 API Manager - WSO2 API Manager Community Call (12/15/2021)
Workflows in WSO2 API Manager - WSO2 API Manager Community Call (12/15/2021)WSO2
 
Lessons from the pandemic - From a single use case to true transformation
 Lessons from the pandemic - From a single use case to true transformation Lessons from the pandemic - From a single use case to true transformation
Lessons from the pandemic - From a single use case to true transformationWSO2
 
Adding Liveliness to Banking Experiences
Adding Liveliness to Banking ExperiencesAdding Liveliness to Banking Experiences
Adding Liveliness to Banking ExperiencesWSO2
 
Building a Future-ready Bank
Building a Future-ready BankBuilding a Future-ready Bank
Building a Future-ready BankWSO2
 
WSO2 API Manager Community Call - November 2021
WSO2 API Manager Community Call - November 2021WSO2 API Manager Community Call - November 2021
WSO2 API Manager Community Call - November 2021WSO2
 
[API World ] - Managing Asynchronous APIs
[API World ] - Managing Asynchronous APIs[API World ] - Managing Asynchronous APIs
[API World ] - Managing Asynchronous APIsWSO2
 
[API World 2021 ] - Understanding Cloud Native Deployment
[API World 2021 ] - Understanding Cloud Native Deployment[API World 2021 ] - Understanding Cloud Native Deployment
[API World 2021 ] - Understanding Cloud Native DeploymentWSO2
 
[API Word 2021] - Quantum Duality of “API as a Business and a Technology”
[API Word 2021] - Quantum Duality of “API as a Business and a Technology”[API Word 2021] - Quantum Duality of “API as a Business and a Technology”
[API Word 2021] - Quantum Duality of “API as a Business and a Technology”WSO2
 

More from WSO2 (20)

Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with Platformless
 
How to Create a Service in Choreo
How to Create a Service in ChoreoHow to Create a Service in Choreo
How to Create a Service in Choreo
 
Ballerina Tech Talk - May 2023
Ballerina Tech Talk - May 2023Ballerina Tech Talk - May 2023
Ballerina Tech Talk - May 2023
 
Platform Strategy to Deliver Digital Experiences on Azure
Platform Strategy to Deliver Digital Experiences on AzurePlatform Strategy to Deliver Digital Experiences on Azure
Platform Strategy to Deliver Digital Experiences on Azure
 
GartnerITSymSessionSlides.pdf
GartnerITSymSessionSlides.pdfGartnerITSymSessionSlides.pdf
GartnerITSymSessionSlides.pdf
 
[Webinar] How to Create an API in Minutes
[Webinar] How to Create an API in Minutes[Webinar] How to Create an API in Minutes
[Webinar] How to Create an API in Minutes
 
Modernizing the Student Journey with Ethos Identity
Modernizing the Student Journey with Ethos IdentityModernizing the Student Journey with Ethos Identity
Modernizing the Student Journey with Ethos Identity
 
Choreo - Build unique digital experiences on WSO2's platform, secured by Etho...
Choreo - Build unique digital experiences on WSO2's platform, secured by Etho...Choreo - Build unique digital experiences on WSO2's platform, secured by Etho...
Choreo - Build unique digital experiences on WSO2's platform, secured by Etho...
 
CIO Summit Berlin 2022.pptx.pdf
CIO Summit Berlin 2022.pptx.pdfCIO Summit Berlin 2022.pptx.pdf
CIO Summit Berlin 2022.pptx.pdf
 
Delivering New Digital Experiences Fast - Introducing Choreo
Delivering New Digital Experiences Fast - Introducing ChoreoDelivering New Digital Experiences Fast - Introducing Choreo
Delivering New Digital Experiences Fast - Introducing Choreo
 
Fueling the Digital Experience Economy with Connected Products
Fueling the Digital Experience Economy with Connected ProductsFueling the Digital Experience Economy with Connected Products
Fueling the Digital Experience Economy with Connected Products
 
A Reference Methodology for Agile Digital Businesses
 A Reference Methodology for Agile Digital Businesses A Reference Methodology for Agile Digital Businesses
A Reference Methodology for Agile Digital Businesses
 
Workflows in WSO2 API Manager - WSO2 API Manager Community Call (12/15/2021)
Workflows in WSO2 API Manager - WSO2 API Manager Community Call (12/15/2021)Workflows in WSO2 API Manager - WSO2 API Manager Community Call (12/15/2021)
Workflows in WSO2 API Manager - WSO2 API Manager Community Call (12/15/2021)
 
Lessons from the pandemic - From a single use case to true transformation
 Lessons from the pandemic - From a single use case to true transformation Lessons from the pandemic - From a single use case to true transformation
Lessons from the pandemic - From a single use case to true transformation
 
Adding Liveliness to Banking Experiences
Adding Liveliness to Banking ExperiencesAdding Liveliness to Banking Experiences
Adding Liveliness to Banking Experiences
 
Building a Future-ready Bank
Building a Future-ready BankBuilding a Future-ready Bank
Building a Future-ready Bank
 
WSO2 API Manager Community Call - November 2021
WSO2 API Manager Community Call - November 2021WSO2 API Manager Community Call - November 2021
WSO2 API Manager Community Call - November 2021
 
[API World ] - Managing Asynchronous APIs
[API World ] - Managing Asynchronous APIs[API World ] - Managing Asynchronous APIs
[API World ] - Managing Asynchronous APIs
 
[API World 2021 ] - Understanding Cloud Native Deployment
[API World 2021 ] - Understanding Cloud Native Deployment[API World 2021 ] - Understanding Cloud Native Deployment
[API World 2021 ] - Understanding Cloud Native Deployment
 
[API Word 2021] - Quantum Duality of “API as a Business and a Technology”
[API Word 2021] - Quantum Duality of “API as a Business and a Technology”[API Word 2021] - Quantum Duality of “API as a Business and a Technology”
[API Word 2021] - Quantum Duality of “API as a Business and a Technology”
 

Recently uploaded

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 

Recently uploaded (20)

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 

Microservices Communication Patterns with gRPC

  • 1. Microservices Communication Patterns with gRPC Kasun Indrasiri Author “gRPC Up and Running”, Product Manager @WSO2
  • 2. About Me ● Author “gRPC Up & Running”, “Microservices for Enterprise” ● Product Manager/Senior Director at WSO2. ● Committer and PMC member at Apache Software Foundation. ● Founder “Bay area Microservices, APIs and Integration” meetup group.
  • 3. What is gRPC? ● Modern Inter-process communication technology. ● Invoking remote functions as easy as making a local function invocation. ● Contract-first. ● Binary messaging on the wire on top of HTTP2 ● Polyglot.
  • 4. ● Defines the business capabilities of your service. ● Protocol Buffers used as the IDL for define services. ● Protocol Buffers : ○ A language-agnostic, platform-neutral, extensible mechanism to serializing structured data. ● Defines service, remote methods, and data types. Fundamentals of gRPC - Service Definition syntax = "proto3"; package ecommerce; service ProductInfo { rpc addProduct(Product) returns (ProductID); rpc getProduct(ProductID) returns (Product); } message Product { string id = 1; string name = 2; string description = 3; float price = 4; } message ProductID { string value = 1; } ProductInfo.proto
  • 5. Fundamentals of gRPC - gRPC Service ● gRPC service implements the business logic. ● Generate server side skeleton from service definition. ● Implements business logic on top of the generated code. ● Run server application. // AddProduct implements ecommerce.AddProduct func (s *server) AddProduct(ctx context.Context, in *pb.Product) (*pb.ProductID, error) { // Business logic } // GetProduct implements ecommerce.GetProduct func (s *server) GetProduct(ctx context.Context, in *pb.ProductID) (*pb.Product, error) { // Business logic } // gRPC server func main() { lis, err := net.Listen( "tcp", port) ... s := grpc.NewServer() pb.RegisterProductInfoServer(s, &server{}) if err := s.Serve(lis); err != nil { log.Fatalf( "failed to serve: %v" , err) } }
  • 6. Fundamentals of gRPC - gRPC Client ● Connect to a gRPC service and invokes a remote method. ● Generate client-side code(client stub) from service definition and invoke the remote method. ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 50051) .usePlaintext() .build(); ProductInfoGrpc.ProductInfoBlockingStub stub = ProductInfoGrpc.newBlockingStub(channel); ProductInfoOuterClass.Product product = stub.getProduct(productID); logger.info("Product: " + product.toString());
  • 7. Why gRPC? ● Efficient. ● Strict specification and well-defined service contracts. ● Strongly Typed. ● Polyglot. ● Duplex Streaming. ● Native integration with cloud native ecosystem.
  • 8. gRPC in the Microservices Landscape ● Coexistence of gRPC with other communication protocols.
  • 9. gRPC vs OpenAPI/REST vs GraphQL REST/OAS Protocol HTTP 1.x, HTTP2 HTTP2 HTTP 1.x, HTTP2 Payload Text - JSON, XML (large, human readable) Binary - Protocol Buffers (small, binary) Text - JSON Service Definition OAS (optional) gRPC IDL/Protocol Buffer(required) GraphQL (required) Code generation Optional, via third party libs Required and natively supported. Optional Prescriptiveness Loose, (need to follow best practices) Strict Strict Streaming No first class support First class support No first class support Browser support Yes No (require grpc-web) Yes
  • 10. Unary/Simple RPC ● Client sends a single request to the server and gets a single response. service OrderManagement { rpc getOrder(google.protobuf.StringValue) returns (Order); } message Order { ... } order_mgt.proto c := pb.NewOrderManagementClient(conn) retrievedOrder , err := c.GetOrder(ctx, &wrapper.StringValue{Value: "106"}) gRPC Client (Go) func (s *server) GetOrder(ctx context.Context, orderId *wrapper.StringValue) (*pb.Order, error) { ord := orderMap[orderId.Value] return &ord, nil } Service Impl (Go)
  • 11. Server Streaming RPC ● Server sends back a sequence of responses(stream) after getting the client’s request message. ● After sending all the responses server marks the end of stream. service OrderManagement { rpc searchOrders(google.protobuf.StringValue) returns (stream Order); } message Order { ... } order_mgt.proto searchStream, _ := c.SearchOrders(ctx, &wrapper.StringValue{Value: "Google"}) searchOrder, err := searchStream.Recv() gRPC Client (Go) func (s *server) SearchOrders(searchQuery *wrappers.StringValue, stream pb.OrderManagement_SearchOrdersServer) error { // Business logic stream.Send(&order1) stream.Send(&order2) return nil } Service Impl (Go)
  • 12. Client Streaming RPC ● Client sends multiple messages to the server instead of a single request. ● Server sends back a single response to the client. service OrderManagement { rpc updateOrders(stream Order) returns (google.protobuf.StringValue); } order_mgt.proto updateStream, _ := c.UpdateOrders(ctx) _ = updateStream.Send(&updOrder1) _ = updateStream.Send(&updOrder2) _ = updateStream.Send(&updOrder3) updateRes, _ := updateStream.CloseAndRecv() gRPC Client (Go) func (s *server) UpdateOrders(stream pb.OrderManagement_UpdateOrdersServer) error { for { order, err := stream.Recv() if err == io.EOF { // Finished reading the order stream. return stream.SendAndClose(&wrapper.StringValue{ Value: "Orders processed " + ordersStr}) } ... Service Impl (Go)
  • 13. Bidirectional-Streaming RPC ● Client is sending a request to the server as a stream of messages. ● Server also responds with a stream of messages. ● Client has to initiated the RPC. rpc processOrders(stream google.protobuf.StringValue) returns (stream CombinedShipment); order_mgt.proto streamProcOrder, _ := c.ProcessOrders(ctx) _ = streamProcOrder.Send(&wrapper.StringValue{Value:"102"}) _ = streamProcOrder.Send(&wrapper.StringValue{Value:"103"}) ... channel := make(chan bool, 1) go asncClientBidirectionalRPC(streamProcOrder, channel) ... gRPC Client (Go) func (s *server) ProcessOrders(stream pb.OrderManagement_ProcessOrdersServer) error { ... for { orderId, err := stream.Recv() for _, comb := range combinedShipmentMap { stream.Send(&comb) } ... Service Impl (Go)
  • 14. gRPC Interceptors ● Mechanism to execute some common logic before or after the execution of the remote function for server or client application. ● Server Side and Client Side interceptors. ● Unary Interceptors ○ Phases : preprocessing, invoking the RPC method, and postprocessing ● Streaming interceptors ○ Intercepts any streaming RPC ● Useful for logging, authentication, metrics etc.
  • 15. Deadlines ● A deadline is expressed in absolute time from the beginning of a request and applied across multiple service invocations. ● gRPC client applications sets deadline when invoking remote functions. clientDeadline := time.Now().Add(time.Duration(2 * time.Second)) ctx, cancel := context.WithDeadline(context.Background(), clientDeadline) // Invoke RPC gRPC Client App
  • 16. Metadata ● Information directly related to the service’s business logic and consumer is part of the remote method invocation arguments. ● Use Metadata to share information about the RPC calls that are not related to the business context of the RPC (e.g. Security Headers) ● Structured as K-V pairs. ● Exchanged as gRPC headers.
  • 17. Multiplexing ● Running multiple gRPC services on the same gRPC server. grpcServer := grpc.NewServer() // Register Order Management service on gRPC orderMgtServer ordermgt_pb.RegisterOrderManagementServer(grpcServer, &orderMgtServer{}) // Register Greeter Service on gRPC orderMgtServer hello_pb.RegisterGreeterServer(grpcServer, &helloServer{}) gRPC Server App
  • 18. Cancellation ● When either the client or server application wants to terminate the RPC this can be done by Cancelling the RPC. ● No further RPCs can be done over that connection. ● When one party cancels the RPC, the other party can determine it by checking the context of the RPC. ○ E.g. stream.Context().Err() == context.Canceled.
  • 19. API Management with gRPC ● Managed gRPC services. ○ Management at Remote method level or service level. ○ Authentication ■ Authentication schemes are JWT, Basic Auth and API Key ○ Authorization ■ Granular authorization at method level. ○ Rate limiting ■ Applied for per-service or per-method basis. ● Versioning ○ Versioning at protocol buffer packages. E.g. ‘package product.v1;’ ● API definition ○ Extend protocol buffer definition to cater to API Management features.
  • 20. REST/Open API ←→ gRPC Bridge ● gRPC Gateway : REST/HTTP 1.1 -> gRPC Bridge. ● gRPC gateway plug-in enables the protocol buffer compiler to read the gRPC service definition and generate a reverse proxy server, which translates a RESTful JSON API into gRPC.
  • 21. Resources ● gRPC Up and Running Book. ○ Gives you a comprehensive understanding of gRPC. ○ gRPC communication patterns and advanced concepts. ○ Running gRPC in production. ○ Dozens of samples written in Go and Java. ● Use cases and source code in Java and Go - https://grpc-up-and-running.github.io/ ● gRPC.io ● Visit WSO2 booth!