SlideShare a Scribd company logo
Build microserviceBuild microservice
with gRPC in Golangwith gRPC in Golang
David Chou
We are UmboWe are Umbo
Computer VisionComputer Vision
We buildWe build
autonomous videoautonomous video
security systemsecurity system
CyberlinkCyberlink
TrendMicroTrendMicro
Umbo CVUmbo CV
Google I/O ExtendGoogle I/O Extend
Golang TaipeiGolang Taipei
  
A high performance, open source, general purpose
standards-based, feature-rich RPC framework.
O(10^10) RPCs per second at Google
gRPC: MotivationgRPC: Motivation
Google has its internal RPC called Stubby
All applications and systems built using RPCs
Over 10^10 RPCs per second
Tightly couple with internal infrastructure
Not suitable for open source community
gRPC: StatusgRPC: Status
A high performance, universal RPC framework
Google open sourced it in Feb 2015
Being 1.0 in Aug 2016
Latest version: v1.3.2
Already been adpoted in
CoreOS, Netflix, Square, Cisco, Juniper
gRPC: FeaturesgRPC: Features
Bi-directional streaming over HTTP/2
Support multi-language, multi-platform
Simple service definition framework
Bi-directional streaming over HTTP/2Bi-directional streaming over HTTP/2
Single TCP connection for each client-server pair
Support bi-directional streaming
Support multi-language,Support multi-language,
multi-platformmulti-platform
Use protoc as the code generator
Native implementations in C/C++, Java, and Go
C stack wrapped by C#, Node, ObjC, Python, Ruby, PHP
Platforms supported: Linux, MacOS, Windows, Android, iOS
Currently, no browser side support. #8682
gRPC gateway
gRPC-web
Simple service definition frameworkSimple service definition framework
Use Protocol Buffer IDL
Service definition
Generate server and client stub code
Message definition
Binary format
Much better performace than json
syntax = "proto3";
package pb;
message EchoMessage {
string msg = 1;
}
service EchoService {
rpc Echo(EchoMessage) returns (EchoMessage);
}
Protobuf IDL: EchoServiceProtobuf IDL: EchoService
BenchmarkToJSON_1000_Director-2 500 2512808 ns/op 560427 B/op 9682 allocs/op
BenchmarkToPB_1000_Director-2 2000 1338410 ns/op 196743 B/op 3052 allocs/op
BenchmarkToJSONUnmarshal_1000_Director-4 1000 1279297 ns/op 403746 B/op 5144 allocs/op
BenchmarkToPBUnmarshal_1000_Director-4 3000 489585 ns/op 202256 B/op 5522 allocs/op
Json vs Protobuf performanceJson vs Protobuf performance
Ref: Dgraph: JSON vs. Binary clients
Marshalling: 2x faster, 65% less memory
Unmarshalling: 2.6x faster, 50% less memory
Example: DemoServiceExample: DemoService
gRPC Service DefinitiongRPC Service Definition
message Demo {
string value = 1;
}
service DemoService {
rpc SimpleRPC(Demo) returns (Demo);
rpc ServerStream(Demo) returns (stream Demo);
rpc ClientStream(stream Demo) returns (Demo);
rpc Bidirectional(stream Demo) returns (stream Demo);
}
gRPC Service DefinitiongRPC Service Definition
gRPC supprots 4 kinds of service methods
Unary RPC
Server streaming RPC
Client streaming RPC
Bidirectional RPC
Generate client and server codeGenerate client and server code
Run protoc to generate client/server interfaces
$ protoc --go_out=plugins=grpc:. demo.proto
protoc will generate demo.pb.go
Install relevant tools
demo.pb.godemo.pb.go
type Demo struct {
Value string `protobuf:"bytes,1,opt,name=value" json:"value,omitempty"`
}
// Client API for DemoService service
type DemoServiceClient interface {
SimpleRPC(ctx context.Context, in *Demo, opts ...grpc.CallOption) (*Demo, error)
ServerStream(ctx context.Context, in *Demo, opts ...grpc.CallOption) (DemoService_ServerStreamClient,
ClientStream(ctx context.Context, opts ...grpc.CallOption) (DemoService_ClientStreamClient, error)
Bidirectional(ctx context.Context, opts ...grpc.CallOption) (DemoService_BidirectionalClient, error)
}
// Implementation of DemoService client
type demoServiceClient struct {
cc *grpc.ClientConn
}
func NewDemoServiceClient(cc *grpc.ClientConn) DemoServiceClient {
...
}
// Server API for DemoService service
type DemoServiceServer interface {
SimpleRPC(context.Context, *Demo) (*Demo, error)
ServerStream(*Demo, DemoService_ServerStreamServer) error
ClientStream(DemoService_ClientStreamServer) error
Bidirectional(DemoService_BidirectionalServer) error
}
Go ServerGo Server
type server struct{}
func (this *server) SimpleRPC(c context.Context, msg *Demo) (*Demo, error) {
msg.Value = "Hello" + msg.Value
return msg, nil
}
func (this *server) ServerStream(msg *Demo, stream DemoService_ServerStreamServer) error {
for i := 0; i < 10; i++ {
err := stream.Send(&Demo{value: "Hello"})
if err != nil {
fmt.Printf("err: %sn", err.Error())
}
time.Sleep(100 * time.Millisecond)
}
return nil
}
func main() {
lis, err := net.Listen("tcp", "localhost:12345")
if err != nil {
log.Fatalf("Failed to listen: %v", err)
}
grpcServer := grpc.NewServer()
RegisterDemoServiceServer(grpcServer, &server{})
grpcServer.Serve(lis)
}
Go Client: SimpleRPCGo Client: SimpleRPC
func main() {
grpcAddr := "localhost:12345"
conn, err := grpc.Dial(grpcAddr)
if err != nil {
log.Fatalf("Dial(%s) = %v", grpcAddr, err)
}
defer conn.Close()
client := NewDemoServiceClient(conn)
msg := &Demo{value: "World"}
reply, err := client.SimpleRPC(context.Background(), msg)
if err != nil {
log.Fatalf("SimpleRPC(%#v) failed with %v", msg, err)
}
println("received message " + reply.Value)
}
Go Client: ServerStreamGo Client: ServerStream
func main() {
grpcAddr := "localhost:12345"
conn, err := grpc.Dial(grpcAddr)
if err != nil {
log.Fatalf("Dial(%s) = %v", grpcAddr, err)
}
defer conn.Close()
client := NewDemoServiceClient(conn)
stream, err := client.ServerStream(context.TODO(), &Demo{
Value: "Hello",
})
for {
msg, err := stream.Recv()
if err == io.EOF {
break
}
fmt.Printf("%+vn", msg)
}
}
Let's go deeperLet's go deeper
gRPC build-in authenticationgRPC build-in authentication
Two types of Credentials objects
Channel credentials
Call credentials
Channel credentialsChannel credentials
Credentials are attached to a Channel
Ex: SSL credentials
tls := credentials.NewClientTLSFromCert(nil, "")
conn, err := grpc.Dial(serverAddr, grpc.WithTransportCredentials(tls))
creds, err := credentials.NewServerTLSFromFile(certFile, keyFile)
server := grpc.NewServer(grpc.Creds(creds))
server.Serve()
TLS on server side
TLS on client side
Call credentialsCall credentials
Credentials are attached to each RPC call
Token based authentication, ex: OAuth, JWT
func unaryInterceptor(ctx context.Context, req interface{}
if err := authorize(ctx); err != nil {
return err
}
return handler(ctx, req)
}
func authorize(ctx context.Context) error {
if md, ok := metadata.FromContext(ctx); ok {
if checkJWT(md["jwt"][0]) {
return nil
}
return AccessDeniedErr
}
return EmptyMetadataErr
}
grpc.NewServer(grpc.UnaryInterceptor(unaryInterceptor))
TLS on server side
type JWTCreds struct {
Token string
}
func (c *JWTCreds) GetRequestMetadata(context.Context, ..
return map[string]string{
"jwt": c.Token,
}, nil
}
grpc.Dial(target, grpc.WithPerRPCCredentials(&JWTCreds{
Token: "test-jwt-token",
}))
TLS on client side
Ref: grpc-go #106
gRPC load balancegRPC load balance
Approaches to Load Balancing
Server-side LB
Client-side LB
Load Balancing in gRPCLoad Balancing in gRPC
#gRPC load balancing proposal
Any Question?Any Question?

More Related Content

What's hot

고려대학교 컴퓨터학과 특강 - 대학생 때 알았더라면 좋았을 것들
고려대학교 컴퓨터학과 특강 - 대학생 때 알았더라면 좋았을 것들고려대학교 컴퓨터학과 특강 - 대학생 때 알았더라면 좋았을 것들
고려대학교 컴퓨터학과 특강 - 대학생 때 알았더라면 좋았을 것들
Chris Ohk
 
Spring IO 2023 - Dynamic OpenAPIs with Spring Cloud Gateway
Spring IO 2023 - Dynamic OpenAPIs with Spring Cloud GatewaySpring IO 2023 - Dynamic OpenAPIs with Spring Cloud Gateway
Spring IO 2023 - Dynamic OpenAPIs with Spring Cloud Gateway
Iván López Martín
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
Bo-Yi Wu
 
The top 3 challenges running multi-tenant Flink at scale
The top 3 challenges running multi-tenant Flink at scaleThe top 3 challenges running multi-tenant Flink at scale
The top 3 challenges running multi-tenant Flink at scale
Flink Forward
 
JIRA 업무 생산성 향상 및 프로젝트 관리
JIRA 업무 생산성 향상 및 프로젝트 관리JIRA 업무 생산성 향상 및 프로젝트 관리
JIRA 업무 생산성 향상 및 프로젝트 관리
KwangSeob Jeong
 
〈야생의 땅: 듀랑고〉 서버 아키텍처 Vol. 3
〈야생의 땅: 듀랑고〉 서버 아키텍처 Vol. 3〈야생의 땅: 듀랑고〉 서버 아키텍처 Vol. 3
〈야생의 땅: 듀랑고〉 서버 아키텍처 Vol. 3
Heungsub Lee
 
Git을 조금 더 알아보자!
Git을 조금 더 알아보자!Git을 조금 더 알아보자!
Git을 조금 더 알아보자!
Young Kim
 
ksqlDB로 실시간 데이터 변환 및 스트림 처리
ksqlDB로 실시간 데이터 변환 및 스트림 처리ksqlDB로 실시간 데이터 변환 및 스트림 처리
ksqlDB로 실시간 데이터 변환 및 스트림 처리
confluent
 
PHP で実行中のスクリプトの動作を下から覗き見る
PHP で実行中のスクリプトの動作を下から覗き見るPHP で実行中のスクリプトの動作を下から覗き見る
PHP で実行中のスクリプトの動作を下から覗き見る
shinjiigarashi
 
Microservice - Up to 500k CCU
Microservice - Up to 500k CCUMicroservice - Up to 500k CCU
Microservice - Up to 500k CCU
Viet Tran
 
gRPC
gRPCgRPC
웹서버 부하테스트 실전 노하우
웹서버 부하테스트 실전 노하우웹서버 부하테스트 실전 노하우
웹서버 부하테스트 실전 노하우
IMQA
 
실시간 게임 서버 최적화 전략
실시간 게임 서버 최적화 전략실시간 게임 서버 최적화 전략
실시간 게임 서버 최적화 전략
YEONG-CHEON YOU
 
Golang 101
Golang 101Golang 101
Golang 101
宇 傅
 
OpenStack Oslo Messaging RPC API Tutorial Demo Call, Cast and Fanout
OpenStack Oslo Messaging RPC API Tutorial Demo Call, Cast and FanoutOpenStack Oslo Messaging RPC API Tutorial Demo Call, Cast and Fanout
OpenStack Oslo Messaging RPC API Tutorial Demo Call, Cast and Fanout
Saju Madhavan
 
Building a scalable microservice architecture with envoy, kubernetes and istio
Building a scalable microservice architecture with envoy, kubernetes and istioBuilding a scalable microservice architecture with envoy, kubernetes and istio
Building a scalable microservice architecture with envoy, kubernetes and istio
SAMIR BEHARA
 
중앙 서버 없는 게임 로직
중앙 서버 없는 게임 로직중앙 서버 없는 게임 로직
중앙 서버 없는 게임 로직
Hoyoung Choi
 
promgen - prometheus managemnet tool / simpleclient_java hacks @ Prometheus c...
promgen - prometheus managemnet tool / simpleclient_java hacks @ Prometheus c...promgen - prometheus managemnet tool / simpleclient_java hacks @ Prometheus c...
promgen - prometheus managemnet tool / simpleclient_java hacks @ Prometheus c...
Tokuhiro Matsuno
 
Introduction to Spring WebFlux #jsug #sf_a1
Introduction to Spring WebFlux #jsug #sf_a1Introduction to Spring WebFlux #jsug #sf_a1
Introduction to Spring WebFlux #jsug #sf_a1
Toshiaki Maki
 
코드로 인프라 관리하기 - 자동화 툴 소개
코드로 인프라 관리하기 - 자동화 툴 소개코드로 인프라 관리하기 - 자동화 툴 소개
코드로 인프라 관리하기 - 자동화 툴 소개
태준 문
 

What's hot (20)

고려대학교 컴퓨터학과 특강 - 대학생 때 알았더라면 좋았을 것들
고려대학교 컴퓨터학과 특강 - 대학생 때 알았더라면 좋았을 것들고려대학교 컴퓨터학과 특강 - 대학생 때 알았더라면 좋았을 것들
고려대학교 컴퓨터학과 특강 - 대학생 때 알았더라면 좋았을 것들
 
Spring IO 2023 - Dynamic OpenAPIs with Spring Cloud Gateway
Spring IO 2023 - Dynamic OpenAPIs with Spring Cloud GatewaySpring IO 2023 - Dynamic OpenAPIs with Spring Cloud Gateway
Spring IO 2023 - Dynamic OpenAPIs with Spring Cloud Gateway
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
 
The top 3 challenges running multi-tenant Flink at scale
The top 3 challenges running multi-tenant Flink at scaleThe top 3 challenges running multi-tenant Flink at scale
The top 3 challenges running multi-tenant Flink at scale
 
JIRA 업무 생산성 향상 및 프로젝트 관리
JIRA 업무 생산성 향상 및 프로젝트 관리JIRA 업무 생산성 향상 및 프로젝트 관리
JIRA 업무 생산성 향상 및 프로젝트 관리
 
〈야생의 땅: 듀랑고〉 서버 아키텍처 Vol. 3
〈야생의 땅: 듀랑고〉 서버 아키텍처 Vol. 3〈야생의 땅: 듀랑고〉 서버 아키텍처 Vol. 3
〈야생의 땅: 듀랑고〉 서버 아키텍처 Vol. 3
 
Git을 조금 더 알아보자!
Git을 조금 더 알아보자!Git을 조금 더 알아보자!
Git을 조금 더 알아보자!
 
ksqlDB로 실시간 데이터 변환 및 스트림 처리
ksqlDB로 실시간 데이터 변환 및 스트림 처리ksqlDB로 실시간 데이터 변환 및 스트림 처리
ksqlDB로 실시간 데이터 변환 및 스트림 처리
 
PHP で実行中のスクリプトの動作を下から覗き見る
PHP で実行中のスクリプトの動作を下から覗き見るPHP で実行中のスクリプトの動作を下から覗き見る
PHP で実行中のスクリプトの動作を下から覗き見る
 
Microservice - Up to 500k CCU
Microservice - Up to 500k CCUMicroservice - Up to 500k CCU
Microservice - Up to 500k CCU
 
gRPC
gRPCgRPC
gRPC
 
웹서버 부하테스트 실전 노하우
웹서버 부하테스트 실전 노하우웹서버 부하테스트 실전 노하우
웹서버 부하테스트 실전 노하우
 
실시간 게임 서버 최적화 전략
실시간 게임 서버 최적화 전략실시간 게임 서버 최적화 전략
실시간 게임 서버 최적화 전략
 
Golang 101
Golang 101Golang 101
Golang 101
 
OpenStack Oslo Messaging RPC API Tutorial Demo Call, Cast and Fanout
OpenStack Oslo Messaging RPC API Tutorial Demo Call, Cast and FanoutOpenStack Oslo Messaging RPC API Tutorial Demo Call, Cast and Fanout
OpenStack Oslo Messaging RPC API Tutorial Demo Call, Cast and Fanout
 
Building a scalable microservice architecture with envoy, kubernetes and istio
Building a scalable microservice architecture with envoy, kubernetes and istioBuilding a scalable microservice architecture with envoy, kubernetes and istio
Building a scalable microservice architecture with envoy, kubernetes and istio
 
중앙 서버 없는 게임 로직
중앙 서버 없는 게임 로직중앙 서버 없는 게임 로직
중앙 서버 없는 게임 로직
 
promgen - prometheus managemnet tool / simpleclient_java hacks @ Prometheus c...
promgen - prometheus managemnet tool / simpleclient_java hacks @ Prometheus c...promgen - prometheus managemnet tool / simpleclient_java hacks @ Prometheus c...
promgen - prometheus managemnet tool / simpleclient_java hacks @ Prometheus c...
 
Introduction to Spring WebFlux #jsug #sf_a1
Introduction to Spring WebFlux #jsug #sf_a1Introduction to Spring WebFlux #jsug #sf_a1
Introduction to Spring WebFlux #jsug #sf_a1
 
코드로 인프라 관리하기 - 자동화 툴 소개
코드로 인프라 관리하기 - 자동화 툴 소개코드로 인프라 관리하기 - 자동화 툴 소개
코드로 인프라 관리하기 - 자동화 툴 소개
 

Similar to Build microservice with gRPC in golang

Managing gRPC Services using Kong KONNECT and the KONG API Gateway
Managing gRPC Services using Kong KONNECT and the KONG API GatewayManaging gRPC Services using Kong KONNECT and the KONG API Gateway
Managing gRPC Services using Kong KONNECT and the KONG API Gateway
João Esperancinha
 
Microservices Communication Patterns with gRPC
Microservices Communication Patterns with gRPCMicroservices Communication Patterns with gRPC
Microservices Communication Patterns with gRPC
WSO2
 
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
 
MessagePack Rakuten Technology Conference 2010
MessagePack Rakuten Technology Conference 2010MessagePack Rakuten Technology Conference 2010
MessagePack Rakuten Technology Conference 2010
Sadayuki Furuhashi
 
Apa itu gRPC_.pptx
Apa itu gRPC_.pptxApa itu gRPC_.pptx
Apa itu gRPC_.pptx
FransiskusBarus1
 
Driving containerd operations with gRPC
Driving containerd operations with gRPCDriving containerd operations with gRPC
Driving containerd operations with gRPC
Docker, Inc.
 
REST in Peace. Long live gRPC! @ Codineers
REST in Peace. Long live gRPC! @ CodineersREST in Peace. Long live gRPC! @ Codineers
REST in Peace. Long live gRPC! @ Codineers
QAware GmbH
 
Microservices summit talk 1/31
Microservices summit talk   1/31Microservices summit talk   1/31
Microservices summit talk 1/31
Varun Talwar
 
gRPC in Go
gRPC in GogRPC in Go
gRPC in Go
Almog Baku
 
Fast and Reliable Swift APIs with gRPC
Fast and Reliable Swift APIs with gRPCFast and Reliable Swift APIs with gRPC
Fast and Reliable Swift APIs with gRPC
Tim Burks
 
Usable APIs at Scale
Usable APIs at ScaleUsable APIs at Scale
Usable APIs at Scale
Tim Burks
 
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
 
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
Tim Burks
 
gRPC 프레임워크를 만들며 알아보는 파이썬 - 파이콘2020
gRPC 프레임워크를 만들며 알아보는 파이썬  - 파이콘2020gRPC 프레임워크를 만들며 알아보는 파이썬  - 파이콘2020
gRPC 프레임워크를 만들며 알아보는 파이썬 - 파이콘2020
재현 신
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
John Staveley
 
Cloud native IPC for Microservices Workshop @ Containerdays 2022
Cloud native IPC for Microservices Workshop @ Containerdays 2022Cloud native IPC for Microservices Workshop @ Containerdays 2022
Cloud native IPC for Microservices Workshop @ Containerdays 2022
QAware GmbH
 
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
Ambassador Labs
 
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
 
CRUD Operation With Dgraph
CRUD Operation With DgraphCRUD Operation With Dgraph
CRUD Operation With Dgraph
Knoldus Inc.
 
End-to-end Streaming Between gRPC Services Via Kafka with John Fallows
End-to-end Streaming Between gRPC Services Via Kafka with John FallowsEnd-to-end Streaming Between gRPC Services Via Kafka with John Fallows
End-to-end Streaming Between gRPC Services Via Kafka with John Fallows
HostedbyConfluent
 

Similar to Build microservice with gRPC in golang (20)

Managing gRPC Services using Kong KONNECT and the KONG API Gateway
Managing gRPC Services using Kong KONNECT and the KONG API GatewayManaging gRPC Services using Kong KONNECT and the KONG API Gateway
Managing gRPC Services using Kong KONNECT and the KONG API Gateway
 
Microservices Communication Patterns with gRPC
Microservices Communication Patterns with gRPCMicroservices Communication Patterns with gRPC
Microservices Communication Patterns with gRPC
 
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...
 
MessagePack Rakuten Technology Conference 2010
MessagePack Rakuten Technology Conference 2010MessagePack Rakuten Technology Conference 2010
MessagePack Rakuten Technology Conference 2010
 
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
 
REST in Peace. Long live gRPC! @ Codineers
REST in Peace. Long live gRPC! @ CodineersREST in Peace. Long live gRPC! @ Codineers
REST in Peace. Long live gRPC! @ Codineers
 
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
 
Fast and Reliable Swift APIs with gRPC
Fast and Reliable Swift APIs with gRPCFast and Reliable Swift APIs with gRPC
Fast and Reliable Swift APIs with gRPC
 
Usable APIs at Scale
Usable APIs at ScaleUsable APIs at Scale
Usable APIs at Scale
 
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}
 
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
 
gRPC 프레임워크를 만들며 알아보는 파이썬 - 파이콘2020
gRPC 프레임워크를 만들며 알아보는 파이썬  - 파이콘2020gRPC 프레임워크를 만들며 알아보는 파이썬  - 파이콘2020
gRPC 프레임워크를 만들며 알아보는 파이썬 - 파이콘2020
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
Cloud native IPC for Microservices Workshop @ Containerdays 2022
Cloud native IPC for Microservices Workshop @ Containerdays 2022Cloud native IPC for Microservices Workshop @ Containerdays 2022
Cloud native IPC for Microservices Workshop @ Containerdays 2022
 
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
 
gRPC or Rest, why not both?
gRPC or Rest, why not both?gRPC or Rest, why not both?
gRPC or Rest, why not both?
 
CRUD Operation With Dgraph
CRUD Operation With DgraphCRUD Operation With Dgraph
CRUD Operation With Dgraph
 
End-to-end Streaming Between gRPC Services Via Kafka with John Fallows
End-to-end Streaming Between gRPC Services Via Kafka with John FallowsEnd-to-end Streaming Between gRPC Services Via Kafka with John Fallows
End-to-end Streaming Between gRPC Services Via Kafka with John Fallows
 

Recently uploaded

Wearable antenna for antenna applications
Wearable antenna for antenna applicationsWearable antenna for antenna applications
Wearable antenna for antenna applications
Madhumitha Jayaram
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
SUTEJAS
 
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
awadeshbabu
 
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdfIron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
RadiNasr
 
Low power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniquesLow power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniques
nooriasukmaningtyas
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
Dr Ramhari Poudyal
 
Exception Handling notes in java exception
Exception Handling notes in java exceptionException Handling notes in java exception
Exception Handling notes in java exception
Ratnakar Mikkili
 
Swimming pool mechanical components design.pptx
Swimming pool  mechanical components design.pptxSwimming pool  mechanical components design.pptx
Swimming pool mechanical components design.pptx
yokeleetan1
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
jpsjournal1
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
gestioneergodomus
 
A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...
nooriasukmaningtyas
 
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
Mukeshwaran Balu
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
KrishnaveniKrishnara1
 
Series of visio cisco devices Cisco_Icons.ppt
Series of visio cisco devices Cisco_Icons.pptSeries of visio cisco devices Cisco_Icons.ppt
Series of visio cisco devices Cisco_Icons.ppt
PauloRodrigues104553
 
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdfBPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
MIGUELANGEL966976
 
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMSA SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
IJNSA Journal
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
Madan Karki
 
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
ihlasbinance2003
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
digital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdfdigital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdf
drwaing
 

Recently uploaded (20)

Wearable antenna for antenna applications
Wearable antenna for antenna applicationsWearable antenna for antenna applications
Wearable antenna for antenna applications
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
 
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
 
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdfIron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
 
Low power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniquesLow power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniques
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
 
Exception Handling notes in java exception
Exception Handling notes in java exceptionException Handling notes in java exception
Exception Handling notes in java exception
 
Swimming pool mechanical components design.pptx
Swimming pool  mechanical components design.pptxSwimming pool  mechanical components design.pptx
Swimming pool mechanical components design.pptx
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
 
A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...
 
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
 
Series of visio cisco devices Cisco_Icons.ppt
Series of visio cisco devices Cisco_Icons.pptSeries of visio cisco devices Cisco_Icons.ppt
Series of visio cisco devices Cisco_Icons.ppt
 
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdfBPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
 
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMSA SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
 
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
digital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdfdigital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdf
 

Build microservice with gRPC in golang

  • 1. Build microserviceBuild microservice with gRPC in Golangwith gRPC in Golang David Chou
  • 2. We are UmboWe are Umbo Computer VisionComputer Vision We buildWe build autonomous videoautonomous video security systemsecurity system
  • 3. CyberlinkCyberlink TrendMicroTrendMicro Umbo CVUmbo CV Google I/O ExtendGoogle I/O Extend Golang TaipeiGolang Taipei   
  • 4. A high performance, open source, general purpose standards-based, feature-rich RPC framework.
  • 5. O(10^10) RPCs per second at Google
  • 6. gRPC: MotivationgRPC: Motivation Google has its internal RPC called Stubby All applications and systems built using RPCs Over 10^10 RPCs per second Tightly couple with internal infrastructure Not suitable for open source community
  • 7. gRPC: StatusgRPC: Status A high performance, universal RPC framework Google open sourced it in Feb 2015 Being 1.0 in Aug 2016 Latest version: v1.3.2 Already been adpoted in CoreOS, Netflix, Square, Cisco, Juniper
  • 8. gRPC: FeaturesgRPC: Features Bi-directional streaming over HTTP/2 Support multi-language, multi-platform Simple service definition framework
  • 9. Bi-directional streaming over HTTP/2Bi-directional streaming over HTTP/2 Single TCP connection for each client-server pair Support bi-directional streaming
  • 10. Support multi-language,Support multi-language, multi-platformmulti-platform Use protoc as the code generator Native implementations in C/C++, Java, and Go C stack wrapped by C#, Node, ObjC, Python, Ruby, PHP Platforms supported: Linux, MacOS, Windows, Android, iOS Currently, no browser side support. #8682 gRPC gateway gRPC-web
  • 11. Simple service definition frameworkSimple service definition framework Use Protocol Buffer IDL Service definition Generate server and client stub code Message definition Binary format Much better performace than json
  • 12. syntax = "proto3"; package pb; message EchoMessage { string msg = 1; } service EchoService { rpc Echo(EchoMessage) returns (EchoMessage); } Protobuf IDL: EchoServiceProtobuf IDL: EchoService
  • 13. BenchmarkToJSON_1000_Director-2 500 2512808 ns/op 560427 B/op 9682 allocs/op BenchmarkToPB_1000_Director-2 2000 1338410 ns/op 196743 B/op 3052 allocs/op BenchmarkToJSONUnmarshal_1000_Director-4 1000 1279297 ns/op 403746 B/op 5144 allocs/op BenchmarkToPBUnmarshal_1000_Director-4 3000 489585 ns/op 202256 B/op 5522 allocs/op Json vs Protobuf performanceJson vs Protobuf performance Ref: Dgraph: JSON vs. Binary clients Marshalling: 2x faster, 65% less memory Unmarshalling: 2.6x faster, 50% less memory
  • 14.
  • 16. gRPC Service DefinitiongRPC Service Definition message Demo { string value = 1; } service DemoService { rpc SimpleRPC(Demo) returns (Demo); rpc ServerStream(Demo) returns (stream Demo); rpc ClientStream(stream Demo) returns (Demo); rpc Bidirectional(stream Demo) returns (stream Demo); }
  • 17. gRPC Service DefinitiongRPC Service Definition gRPC supprots 4 kinds of service methods Unary RPC Server streaming RPC Client streaming RPC Bidirectional RPC
  • 18. Generate client and server codeGenerate client and server code Run protoc to generate client/server interfaces $ protoc --go_out=plugins=grpc:. demo.proto protoc will generate demo.pb.go Install relevant tools
  • 19. demo.pb.godemo.pb.go type Demo struct { Value string `protobuf:"bytes,1,opt,name=value" json:"value,omitempty"` } // Client API for DemoService service type DemoServiceClient interface { SimpleRPC(ctx context.Context, in *Demo, opts ...grpc.CallOption) (*Demo, error) ServerStream(ctx context.Context, in *Demo, opts ...grpc.CallOption) (DemoService_ServerStreamClient, ClientStream(ctx context.Context, opts ...grpc.CallOption) (DemoService_ClientStreamClient, error) Bidirectional(ctx context.Context, opts ...grpc.CallOption) (DemoService_BidirectionalClient, error) } // Implementation of DemoService client type demoServiceClient struct { cc *grpc.ClientConn } func NewDemoServiceClient(cc *grpc.ClientConn) DemoServiceClient { ... } // Server API for DemoService service type DemoServiceServer interface { SimpleRPC(context.Context, *Demo) (*Demo, error) ServerStream(*Demo, DemoService_ServerStreamServer) error ClientStream(DemoService_ClientStreamServer) error Bidirectional(DemoService_BidirectionalServer) error }
  • 20. Go ServerGo Server type server struct{} func (this *server) SimpleRPC(c context.Context, msg *Demo) (*Demo, error) { msg.Value = "Hello" + msg.Value return msg, nil } func (this *server) ServerStream(msg *Demo, stream DemoService_ServerStreamServer) error { for i := 0; i < 10; i++ { err := stream.Send(&Demo{value: "Hello"}) if err != nil { fmt.Printf("err: %sn", err.Error()) } time.Sleep(100 * time.Millisecond) } return nil } func main() { lis, err := net.Listen("tcp", "localhost:12345") if err != nil { log.Fatalf("Failed to listen: %v", err) } grpcServer := grpc.NewServer() RegisterDemoServiceServer(grpcServer, &server{}) grpcServer.Serve(lis) }
  • 21. Go Client: SimpleRPCGo Client: SimpleRPC func main() { grpcAddr := "localhost:12345" conn, err := grpc.Dial(grpcAddr) if err != nil { log.Fatalf("Dial(%s) = %v", grpcAddr, err) } defer conn.Close() client := NewDemoServiceClient(conn) msg := &Demo{value: "World"} reply, err := client.SimpleRPC(context.Background(), msg) if err != nil { log.Fatalf("SimpleRPC(%#v) failed with %v", msg, err) } println("received message " + reply.Value) }
  • 22. Go Client: ServerStreamGo Client: ServerStream func main() { grpcAddr := "localhost:12345" conn, err := grpc.Dial(grpcAddr) if err != nil { log.Fatalf("Dial(%s) = %v", grpcAddr, err) } defer conn.Close() client := NewDemoServiceClient(conn) stream, err := client.ServerStream(context.TODO(), &Demo{ Value: "Hello", }) for { msg, err := stream.Recv() if err == io.EOF { break } fmt.Printf("%+vn", msg) } }
  • 23. Let's go deeperLet's go deeper
  • 24. gRPC build-in authenticationgRPC build-in authentication Two types of Credentials objects Channel credentials Call credentials
  • 25. Channel credentialsChannel credentials Credentials are attached to a Channel Ex: SSL credentials tls := credentials.NewClientTLSFromCert(nil, "") conn, err := grpc.Dial(serverAddr, grpc.WithTransportCredentials(tls)) creds, err := credentials.NewServerTLSFromFile(certFile, keyFile) server := grpc.NewServer(grpc.Creds(creds)) server.Serve() TLS on server side TLS on client side
  • 26. Call credentialsCall credentials Credentials are attached to each RPC call Token based authentication, ex: OAuth, JWT
  • 27. func unaryInterceptor(ctx context.Context, req interface{} if err := authorize(ctx); err != nil { return err } return handler(ctx, req) } func authorize(ctx context.Context) error { if md, ok := metadata.FromContext(ctx); ok { if checkJWT(md["jwt"][0]) { return nil } return AccessDeniedErr } return EmptyMetadataErr } grpc.NewServer(grpc.UnaryInterceptor(unaryInterceptor)) TLS on server side type JWTCreds struct { Token string } func (c *JWTCreds) GetRequestMetadata(context.Context, .. return map[string]string{ "jwt": c.Token, }, nil } grpc.Dial(target, grpc.WithPerRPCCredentials(&JWTCreds{ Token: "test-jwt-token", })) TLS on client side Ref: grpc-go #106
  • 28. gRPC load balancegRPC load balance Approaches to Load Balancing Server-side LB Client-side LB
  • 29.
  • 30.
  • 31. Load Balancing in gRPCLoad Balancing in gRPC #gRPC load balancing proposal