SlideShare a Scribd company logo
1 of 36
Download to read offline
gRPC in Go
@AlmogBaku
Who are you?
@AlmogBaku on github
1. A serial entrepreneur
2. Developer for 12 years
3. GitHub addicted (kubernetes maintainer, etc.)
4. Consultant/freelancer
5. Blog about entrepreneurship and
development:
www.AlmogBaku.com
What are we GOing to talk about?
1. What is Protocol Buffer?
2. What is gRPC?
3. How does it work (high-level)
4. How to use it w/ Go?
5. Tips and tricks
Disclaimer
You wanna know more? Google it!
Google tip: use the keyword “golang”
Who heard about Go?
Who heard about Protocol Buffer?
What is Protocol Buffer (protobuff)
● Interface Definition Language (IDL)
● Serializing for structured data
● Binary form
● Compact
● Fast
{
"userName": "Martin",
"favouriteNumber": 1337,
"interests": ["daydreaming", "hacking"]
}
total: 82 bytes
message Person {
string user_name = 1;
int64 favourite_number = 2;
repeated string interests = 3;
}
Protocol Buffer definition:JSON:
Protocol Buffer message definition
syntax = "proto3";
package calculator;
message SumRequest {
int32 a = 1;
int32 b = 2;
}
message Result {
int32 result = 1;
}
Who heard about gRPC?
What is GRPC
● = gRPC Remote Procedure Calls
● Universal RPC framework
● Fast transportation over http2
● Messages encoded using Protocol Buffer
● Libraries in ~10 languages(native C, Go, Java)
● Layered & pluggable - bring your own monitoring, auth,
load-balancing etc.
gRPC
Protocol Buffer RPC definition
syntax = "proto3";
package calculator;
message SumRequest {
int32 a = 1;
int32 b = 2;
}
message Result {
int32 result = 1;
}
service Math {
rpc Sum (SumRequest) returns (Result);
}
Let’s try...
gRPC Server implementation
func main() {
//TCP Listener
grpcListener, _ := net.Listen("tcp", ":5897")
//Create a gRPC server
baseServer := grpc.NewServer()
//Bind implementation to the server
calculator.RegisterMathServer(baseServer, &server{})
fmt.Println("Server is running on " + grpcListener.Addr().String())
//Bind gRPC server to the TCP
baseServer.Serve(grpcListener)
}
type server struct{}
func (s *server) Sum(ctx context.Context, sumRequest *calculator.SumRequest) (*calculator.Result, error) {
spew.Dump(sumRequest)
return &calculator.Result{Result: sumRequest.A + sumRequest.B}, nil
}
gRPC Client implementation
func main() {
flag.Parse()
//create the connection
conn, _ := grpc.Dial(":5897", grpc.WithInsecure())
defer conn.Close()
//create a client
client := calculator.NewMathClient(conn)
//Create a request
a, _ := strconv.Atoi(flag.Arg(0))
b, _ := strconv.Atoi(flag.Arg(1))
resp, _ := client.Sum(context.Background(), &calculator.SumRequest{ int32(a), int32(b)})
spew.Dump(resp)
}
gRPC Client implementation
syntax = "proto3";
package calculator;
message SumRequest {
int32 a = 1;
int32 b = 2;
}
message Result {
int32 result = 1;
}
service Math {
rpc Sum (SumRequest) returns (Result);
}
Type of calls
● Simple RPC / Unary call
The client send a request and waits for a response. Like a normal function
● Server-side Streaming RPC
The client send a request and gets a stream to read a sequence of
messages back until it’s over
● Client-side Streaming RPC
The client send a stream with sequence of messages, once it’s over the
server respond with a single response
● Bidirectional Streaming RPC
Both the client and the server “chat” and stream data independently(not
necessary related to the other side, or responding to each other)
Streams definition
syntax = "proto3";
package calculator;
message SumNumberRequest {
int32 number = 1;
}
message Result {
int32 result = 1;
}
service Math {
rpc SumAll (stream SumNumberRequest) returns (Result); //client stream
rpc Rand (Rand Request) returns (stream Result); //server stream
rpc Chat (stream Msg) returns (stream Msg); //bi-dir streaming
}
gRPC Server read stream
func (s *server) SumAll(stream calculator.Math_SumAllServer) error {
var sum int32 = 0
for {
numReq, err := stream.Recv()
if err == io.EOF {
return stream.SendAndClose(&calculator.Result{Result: sum})
}
if err != nil {
return err
}
spew.Dump(numReq)
sum += numReq.Number
}
}
gRPC Client send stream
func main() {
flag.Parse()
//create the connection
conn, _ := grpc.Dial(":5897", grpc.WithInsecure())
defer conn.Close()
//create a client
client := calculator.NewMathClient(conn)
//Stream requests
stream, _ := client.SumAll(context.Background())
for _, num := range flag.Args() {
n, _ := strconv.Atoi(num)
stream.Send(&calculator.SumNumberRequest{Number: int32(n)})
}
resp, _ := stream.CloseAndRecv()
spew.Dump(resp)
}
Tips and Tricks
Real life is a bit more complicated...
API Design
Idempotency
It should be safe to retry an RPC, without knowing whether
it was processed.
message WireRequest {
string from = 1;
string to = 2;
float amount = 3;
}
message Response {
int64 confirmation = 1;
}
message WireRequest {
string from = 1;
string to = 2;
float amount = 3;
string UUID = 4;
}
message Response {
int64 confirmation = 1;
}
BAD GOOD
API Design
Avoid long-running operations
● The longer it takes, more likely you’ll have a retry
● Perform in background - send results async
Define default behavior
● Protobuf will “zeroize” null fields by default
● Prefer “UNKNOWN” as the default(0) option for enum
API Design
Avoid batch operations as unary
● Use stream or multiple calls instead
● Error handling become complex
Errors
Don’t panic!
● May crash the server…
● Return errors to the callers
Propagate
● Blindly return errors from libraries can be
difficult to debug
Deadlines (timeouts)
Always use deadlines
Deadlines allow both client and servers to abort
operations
ctx, cancel := context.WithTimeout(context.Background(), 10 * time.Second)
resp, _ := client.Sum(ctx, &req)
Deadlines (timeouts)
Always use deadlines
On the server side, you should also care about
the context
func (s *server) MyReqHandler(ctx context.Context, ...) (*Result, error) {
if ctx.Err() == context.Canceled {
return nil, status.New(codes.Canceled, "Client cancelled, abandoning.").Err()
}
...
}
Deadlines (timeouts)
Recycle deadlines
Sometimes, your server is also a client.
Reuse the context, which carries the deadline.
func (s *server) MyReqHandler(ctx context.Context, ...) (*Result, error) {
client.Call(ctx, ...)
...
}
Be aware: server can wait longer than necessary to fail, and not to retry!
Deadlines (timeouts)
Recycle deadlines
Define a new deadline based on the client’s.
func (s *server) MyReqHandler(ctx context.Context, ...) (*Result, error) {
ctx2, cancel := context.WithTimeout(ctx, 10 * time.Second)
client.Call(ctx2, ...)
...
}
Protocol Buffers with Go Gadgets
https://github.com/gogo/protobuf
1. fork of golang/protobuf
2. faster
3. generating extra helper code
4. Cool
Protocol Buffers with Go Gadgets
message Decision {
Rule rule = 1;
uint64 remain = 2; //kb
Action do = 3;
google.protobuf.Duration TTL = 5 [(gogoproto.stdduration) = true, (gogoproto.nullable) = false];
}
Go gRPC middleware
https://github.com/grpc-ecosystem/go-grpc-middleware
● Set of middlewares, helpers, interceptors for go gRPC
● Features such as:
○ retries
○ customizable auth
○ logging
○ monitoring
○ retries
○ etc
gokit
https://gokit.io
● Gokit is a great toolkit for go microservices
● Gokit offers a boilerplate and set of tools for creating
microservices
● Gokit ecosystem also handles multiple issues such as
logging/monitoring/load-balancing/rate-limit/etc.
Thanks.
@AlmogBaku

More Related Content

What's hot

What is gRPC introduction gRPC Explained
What is gRPC introduction gRPC ExplainedWhat is gRPC introduction gRPC Explained
What is gRPC introduction gRPC Explainedjeetendra mandal
 
Coding with golang
Coding with golangCoding with golang
Coding with golangHannahMoss14
 
Go Programming language, golang
Go Programming language, golangGo Programming language, golang
Go Programming language, golangBasil N G
 
Introduction to gRPC
Introduction to gRPCIntroduction to gRPC
Introduction to gRPCPrakash Divy
 
What is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | EdurekaWhat is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | EdurekaEdureka!
 
Building Microservices with gRPC and NATS
Building Microservices with gRPC and NATSBuilding Microservices with gRPC and NATS
Building Microservices with gRPC and NATSShiju Varghese
 
Go language presentation
Go language presentationGo language presentation
Go language presentationparamisoft
 
Concurrency in Golang
Concurrency in GolangConcurrency in Golang
Concurrency in GolangOliver N
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUDPrem Sanil
 
Introduction to GoLang
Introduction to GoLangIntroduction to GoLang
Introduction to GoLangNVISIA
 
OpenAPI and gRPC Side by-Side
OpenAPI and gRPC Side by-SideOpenAPI and gRPC Side by-Side
OpenAPI and gRPC Side by-SideTim Burks
 
Introduction to gRPC: A general RPC framework that puts mobile and HTTP/2 fir...
Introduction to gRPC: A general RPC framework that puts mobile and HTTP/2 fir...Introduction to gRPC: A general RPC framework that puts mobile and HTTP/2 fir...
Introduction to gRPC: A general RPC framework that puts mobile and HTTP/2 fir...Codemotion
 
Introduction to Go programming language
Introduction to Go programming languageIntroduction to Go programming language
Introduction to Go programming languageSlawomir Dorzak
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in GolangBo-Yi Wu
 
Goroutines and Channels in practice
Goroutines and Channels in practiceGoroutines and Channels in practice
Goroutines and Channels in practiceGuilherme Garnier
 
Introduction to Grafana Loki
Introduction to Grafana LokiIntroduction to Grafana Loki
Introduction to Grafana LokiJulien Pivotto
 

What's hot (20)

What is gRPC introduction gRPC Explained
What is gRPC introduction gRPC ExplainedWhat is gRPC introduction gRPC Explained
What is gRPC introduction gRPC Explained
 
Building microservices with grpc
Building microservices with grpcBuilding microservices with grpc
Building microservices with grpc
 
gRPC with java
gRPC with javagRPC with java
gRPC with java
 
gRPC Overview
gRPC OverviewgRPC Overview
gRPC Overview
 
Coding with golang
Coding with golangCoding with golang
Coding with golang
 
Go Programming language, golang
Go Programming language, golangGo Programming language, golang
Go Programming language, golang
 
Introduction to gRPC
Introduction to gRPCIntroduction to gRPC
Introduction to gRPC
 
What is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | EdurekaWhat is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | Edureka
 
Building Microservices with gRPC and NATS
Building Microservices with gRPC and NATSBuilding Microservices with gRPC and NATS
Building Microservices with gRPC and NATS
 
Go language presentation
Go language presentationGo language presentation
Go language presentation
 
Concurrency in Golang
Concurrency in GolangConcurrency in Golang
Concurrency in Golang
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUD
 
Introduction to GoLang
Introduction to GoLangIntroduction to GoLang
Introduction to GoLang
 
OpenAPI and gRPC Side by-Side
OpenAPI and gRPC Side by-SideOpenAPI and gRPC Side by-Side
OpenAPI and gRPC Side by-Side
 
Go lang
Go langGo lang
Go lang
 
Introduction to gRPC: A general RPC framework that puts mobile and HTTP/2 fir...
Introduction to gRPC: A general RPC framework that puts mobile and HTTP/2 fir...Introduction to gRPC: A general RPC framework that puts mobile and HTTP/2 fir...
Introduction to gRPC: A general RPC framework that puts mobile and HTTP/2 fir...
 
Introduction to Go programming language
Introduction to Go programming languageIntroduction to Go programming language
Introduction to Go programming language
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
 
Goroutines and Channels in practice
Goroutines and Channels in practiceGoroutines and Channels in practice
Goroutines and Channels in practice
 
Introduction to Grafana Loki
Introduction to Grafana LokiIntroduction to Grafana Loki
Introduction to Grafana Loki
 

Similar to gRPC in Go

GDG Devfest 2019 - Build go kit microservices at kubernetes with ease
GDG Devfest 2019 - Build go kit microservices at kubernetes with easeGDG Devfest 2019 - Build go kit microservices at kubernetes with ease
GDG Devfest 2019 - Build go kit microservices at kubernetes with easeKAI CHU CHUNG
 
Finagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestFinagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestPavan Chitumalla
 
用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構Bo-Yi Wu
 
Microservices Communication Patterns with gRPC
Microservices Communication Patterns with gRPCMicroservices Communication Patterns with gRPC
Microservices Communication Patterns with gRPCWSO2
 
Protobuf & Code Generation + Go-Kit
Protobuf & Code Generation + Go-KitProtobuf & Code Generation + Go-Kit
Protobuf & Code Generation + Go-KitManfred Touron
 
[231] the simplicity of cluster apps with circuit
[231] the simplicity of cluster apps with circuit[231] the simplicity of cluster apps with circuit
[231] the simplicity of cluster apps with circuitNAVER D2
 
How to Leverage Go for Your Networking Needs
How to Leverage Go for Your Networking NeedsHow to Leverage Go for Your Networking Needs
How to Leverage Go for Your Networking NeedsDigitalOcean
 
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
 
服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScriptQiangning Hong
 
Performance measurement and tuning
Performance measurement and tuningPerformance measurement and tuning
Performance measurement and tuningAOE
 
Joe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand DwrJoe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand Dwrdeimos
 
Driving containerd operations with gRPC
Driving containerd operations with gRPCDriving containerd operations with gRPC
Driving containerd operations with gRPCDocker, Inc.
 
CODE FOR echo_client.c A simple echo client using TCP #inc.pdf
CODE FOR echo_client.c A simple echo client using TCP  #inc.pdfCODE FOR echo_client.c A simple echo client using TCP  #inc.pdf
CODE FOR echo_client.c A simple echo client using TCP #inc.pdfsecunderbadtirumalgi
 
Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sksureshkarthick37
 
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 gRPCTim Burks
 

Similar to gRPC in Go (20)

GDG Devfest 2019 - Build go kit microservices at kubernetes with ease
GDG Devfest 2019 - Build go kit microservices at kubernetes with easeGDG Devfest 2019 - Build go kit microservices at kubernetes with ease
GDG Devfest 2019 - Build go kit microservices at kubernetes with ease
 
Finagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestFinagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at Pinterest
 
Npc08
Npc08Npc08
Npc08
 
用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構
 
Microservices Communication Patterns with gRPC
Microservices Communication Patterns with gRPCMicroservices Communication Patterns with gRPC
Microservices Communication Patterns with gRPC
 
TensorFlow XLA RPC
TensorFlow XLA RPCTensorFlow XLA RPC
TensorFlow XLA RPC
 
Protobuf & Code Generation + Go-Kit
Protobuf & Code Generation + Go-KitProtobuf & Code Generation + Go-Kit
Protobuf & Code Generation + Go-Kit
 
[231] the simplicity of cluster apps with circuit
[231] the simplicity of cluster apps with circuit[231] the simplicity of cluster apps with circuit
[231] the simplicity of cluster apps with circuit
 
How to Leverage Go for Your Networking Needs
How to Leverage Go for Your Networking NeedsHow to Leverage Go for Your Networking Needs
How to Leverage Go for Your Networking Needs
 
Build microservice with gRPC in golang
Build microservice with gRPC in golangBuild microservice with gRPC in golang
Build microservice with gRPC in golang
 
服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript
 
PPT
PPTPPT
PPT
 
Performance measurement and tuning
Performance measurement and tuningPerformance measurement and tuning
Performance measurement and tuning
 
Joe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand DwrJoe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand Dwr
 
Driving containerd operations with gRPC
Driving containerd operations with gRPCDriving containerd operations with gRPC
Driving containerd operations with gRPC
 
CODE FOR echo_client.c A simple echo client using TCP #inc.pdf
CODE FOR echo_client.c A simple echo client using TCP  #inc.pdfCODE FOR echo_client.c A simple echo client using TCP  #inc.pdf
CODE FOR echo_client.c A simple echo client using TCP #inc.pdf
 
Node js lecture
Node js lectureNode js lecture
Node js lecture
 
Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sk
 
CGI.ppt
CGI.pptCGI.ppt
CGI.ppt
 
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
 

More from Almog Baku

Android is going to Go! Android and Golang
Android is going to Go! Android and GolangAndroid is going to Go! Android and Golang
Android is going to Go! Android and GolangAlmog Baku
 
Symfony2 form type
Symfony2 form typeSymfony2 form type
Symfony2 form typeAlmog Baku
 
Build REST APIs like a Jedi with Symfony2
Build REST APIs like a Jedi with Symfony2Build REST APIs like a Jedi with Symfony2
Build REST APIs like a Jedi with Symfony2Almog Baku
 
Build REST API clients for AngularJS
Build REST API clients for AngularJSBuild REST API clients for AngularJS
Build REST API clients for AngularJSAlmog Baku
 
Turbo theming: Introduction to Sass & Compass
Turbo theming: Introduction to Sass & CompassTurbo theming: Introduction to Sass & Compass
Turbo theming: Introduction to Sass & CompassAlmog Baku
 
Wordpress optimization
Wordpress optimizationWordpress optimization
Wordpress optimizationAlmog Baku
 
Drupal & javascript
Drupal & javascriptDrupal & javascript
Drupal & javascriptAlmog Baku
 

More from Almog Baku (7)

Android is going to Go! Android and Golang
Android is going to Go! Android and GolangAndroid is going to Go! Android and Golang
Android is going to Go! Android and Golang
 
Symfony2 form type
Symfony2 form typeSymfony2 form type
Symfony2 form type
 
Build REST APIs like a Jedi with Symfony2
Build REST APIs like a Jedi with Symfony2Build REST APIs like a Jedi with Symfony2
Build REST APIs like a Jedi with Symfony2
 
Build REST API clients for AngularJS
Build REST API clients for AngularJSBuild REST API clients for AngularJS
Build REST API clients for AngularJS
 
Turbo theming: Introduction to Sass & Compass
Turbo theming: Introduction to Sass & CompassTurbo theming: Introduction to Sass & Compass
Turbo theming: Introduction to Sass & Compass
 
Wordpress optimization
Wordpress optimizationWordpress optimization
Wordpress optimization
 
Drupal & javascript
Drupal & javascriptDrupal & javascript
Drupal & javascript
 

Recently uploaded

Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
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
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
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
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 

Recently uploaded (20)

Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
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
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
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
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 

gRPC in Go

  • 2. Who are you? @AlmogBaku on github 1. A serial entrepreneur 2. Developer for 12 years 3. GitHub addicted (kubernetes maintainer, etc.) 4. Consultant/freelancer 5. Blog about entrepreneurship and development: www.AlmogBaku.com
  • 3. What are we GOing to talk about? 1. What is Protocol Buffer? 2. What is gRPC? 3. How does it work (high-level) 4. How to use it w/ Go? 5. Tips and tricks
  • 4. Disclaimer You wanna know more? Google it! Google tip: use the keyword “golang”
  • 6. Who heard about Protocol Buffer?
  • 7. What is Protocol Buffer (protobuff) ● Interface Definition Language (IDL) ● Serializing for structured data ● Binary form ● Compact ● Fast
  • 8. { "userName": "Martin", "favouriteNumber": 1337, "interests": ["daydreaming", "hacking"] } total: 82 bytes message Person { string user_name = 1; int64 favourite_number = 2; repeated string interests = 3; } Protocol Buffer definition:JSON:
  • 9.
  • 10. Protocol Buffer message definition syntax = "proto3"; package calculator; message SumRequest { int32 a = 1; int32 b = 2; } message Result { int32 result = 1; }
  • 12. What is GRPC ● = gRPC Remote Procedure Calls ● Universal RPC framework ● Fast transportation over http2 ● Messages encoded using Protocol Buffer ● Libraries in ~10 languages(native C, Go, Java) ● Layered & pluggable - bring your own monitoring, auth, load-balancing etc.
  • 13. gRPC
  • 14. Protocol Buffer RPC definition syntax = "proto3"; package calculator; message SumRequest { int32 a = 1; int32 b = 2; } message Result { int32 result = 1; } service Math { rpc Sum (SumRequest) returns (Result); }
  • 16. gRPC Server implementation func main() { //TCP Listener grpcListener, _ := net.Listen("tcp", ":5897") //Create a gRPC server baseServer := grpc.NewServer() //Bind implementation to the server calculator.RegisterMathServer(baseServer, &server{}) fmt.Println("Server is running on " + grpcListener.Addr().String()) //Bind gRPC server to the TCP baseServer.Serve(grpcListener) } type server struct{} func (s *server) Sum(ctx context.Context, sumRequest *calculator.SumRequest) (*calculator.Result, error) { spew.Dump(sumRequest) return &calculator.Result{Result: sumRequest.A + sumRequest.B}, nil }
  • 17. gRPC Client implementation func main() { flag.Parse() //create the connection conn, _ := grpc.Dial(":5897", grpc.WithInsecure()) defer conn.Close() //create a client client := calculator.NewMathClient(conn) //Create a request a, _ := strconv.Atoi(flag.Arg(0)) b, _ := strconv.Atoi(flag.Arg(1)) resp, _ := client.Sum(context.Background(), &calculator.SumRequest{ int32(a), int32(b)}) spew.Dump(resp) }
  • 18. gRPC Client implementation syntax = "proto3"; package calculator; message SumRequest { int32 a = 1; int32 b = 2; } message Result { int32 result = 1; } service Math { rpc Sum (SumRequest) returns (Result); }
  • 19. Type of calls ● Simple RPC / Unary call The client send a request and waits for a response. Like a normal function ● Server-side Streaming RPC The client send a request and gets a stream to read a sequence of messages back until it’s over ● Client-side Streaming RPC The client send a stream with sequence of messages, once it’s over the server respond with a single response ● Bidirectional Streaming RPC Both the client and the server “chat” and stream data independently(not necessary related to the other side, or responding to each other)
  • 20. Streams definition syntax = "proto3"; package calculator; message SumNumberRequest { int32 number = 1; } message Result { int32 result = 1; } service Math { rpc SumAll (stream SumNumberRequest) returns (Result); //client stream rpc Rand (Rand Request) returns (stream Result); //server stream rpc Chat (stream Msg) returns (stream Msg); //bi-dir streaming }
  • 21. gRPC Server read stream func (s *server) SumAll(stream calculator.Math_SumAllServer) error { var sum int32 = 0 for { numReq, err := stream.Recv() if err == io.EOF { return stream.SendAndClose(&calculator.Result{Result: sum}) } if err != nil { return err } spew.Dump(numReq) sum += numReq.Number } }
  • 22. gRPC Client send stream func main() { flag.Parse() //create the connection conn, _ := grpc.Dial(":5897", grpc.WithInsecure()) defer conn.Close() //create a client client := calculator.NewMathClient(conn) //Stream requests stream, _ := client.SumAll(context.Background()) for _, num := range flag.Args() { n, _ := strconv.Atoi(num) stream.Send(&calculator.SumNumberRequest{Number: int32(n)}) } resp, _ := stream.CloseAndRecv() spew.Dump(resp) }
  • 23. Tips and Tricks Real life is a bit more complicated...
  • 24. API Design Idempotency It should be safe to retry an RPC, without knowing whether it was processed. message WireRequest { string from = 1; string to = 2; float amount = 3; } message Response { int64 confirmation = 1; } message WireRequest { string from = 1; string to = 2; float amount = 3; string UUID = 4; } message Response { int64 confirmation = 1; } BAD GOOD
  • 25. API Design Avoid long-running operations ● The longer it takes, more likely you’ll have a retry ● Perform in background - send results async Define default behavior ● Protobuf will “zeroize” null fields by default ● Prefer “UNKNOWN” as the default(0) option for enum
  • 26. API Design Avoid batch operations as unary ● Use stream or multiple calls instead ● Error handling become complex
  • 27. Errors Don’t panic! ● May crash the server… ● Return errors to the callers Propagate ● Blindly return errors from libraries can be difficult to debug
  • 28. Deadlines (timeouts) Always use deadlines Deadlines allow both client and servers to abort operations ctx, cancel := context.WithTimeout(context.Background(), 10 * time.Second) resp, _ := client.Sum(ctx, &req)
  • 29. Deadlines (timeouts) Always use deadlines On the server side, you should also care about the context func (s *server) MyReqHandler(ctx context.Context, ...) (*Result, error) { if ctx.Err() == context.Canceled { return nil, status.New(codes.Canceled, "Client cancelled, abandoning.").Err() } ... }
  • 30. Deadlines (timeouts) Recycle deadlines Sometimes, your server is also a client. Reuse the context, which carries the deadline. func (s *server) MyReqHandler(ctx context.Context, ...) (*Result, error) { client.Call(ctx, ...) ... } Be aware: server can wait longer than necessary to fail, and not to retry!
  • 31. Deadlines (timeouts) Recycle deadlines Define a new deadline based on the client’s. func (s *server) MyReqHandler(ctx context.Context, ...) (*Result, error) { ctx2, cancel := context.WithTimeout(ctx, 10 * time.Second) client.Call(ctx2, ...) ... }
  • 32. Protocol Buffers with Go Gadgets https://github.com/gogo/protobuf 1. fork of golang/protobuf 2. faster 3. generating extra helper code 4. Cool
  • 33. Protocol Buffers with Go Gadgets message Decision { Rule rule = 1; uint64 remain = 2; //kb Action do = 3; google.protobuf.Duration TTL = 5 [(gogoproto.stdduration) = true, (gogoproto.nullable) = false]; }
  • 34. Go gRPC middleware https://github.com/grpc-ecosystem/go-grpc-middleware ● Set of middlewares, helpers, interceptors for go gRPC ● Features such as: ○ retries ○ customizable auth ○ logging ○ monitoring ○ retries ○ etc
  • 35. gokit https://gokit.io ● Gokit is a great toolkit for go microservices ● Gokit offers a boilerplate and set of tools for creating microservices ● Gokit ecosystem also handles multiple issues such as logging/monitoring/load-balancing/rate-limit/etc.