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

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
Introduction to gRPCIntroduction to gRPC
Introduction to gRPCPrakash Divy
 
What is gRPC introduction gRPC Explained
What is gRPC introduction gRPC ExplainedWhat is gRPC introduction gRPC Explained
What is gRPC introduction gRPC Explainedjeetendra mandal
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Mario Fusco
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web APIhabib_786
 
Robert Kubis - gRPC - boilerplate to high-performance scalable APIs - code.t...
 Robert Kubis - gRPC - boilerplate to high-performance scalable APIs - code.t... Robert Kubis - gRPC - boilerplate to high-performance scalable APIs - code.t...
Robert Kubis - gRPC - boilerplate to high-performance scalable APIs - code.t...AboutYouGmbH
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsSolution4Future
 
Building your First gRPC Service
Building your First gRPC ServiceBuilding your First gRPC Service
Building your First gRPC ServiceJessie Barnett
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJSDavid Parsons
 
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 FallowsHostedbyConfluent
 
Building REST APIs using gRPC and Go
Building REST APIs using gRPC and GoBuilding REST APIs using gRPC and Go
Building REST APIs using gRPC and GoAlvaro Viebrantz
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with ExamplesGabriele Lana
 
Inter-Process Communication in Microservices using gRPC
Inter-Process Communication in Microservices using gRPCInter-Process Communication in Microservices using gRPC
Inter-Process Communication in Microservices using gRPCShiju Varghese
 
Understanding REST
Understanding RESTUnderstanding REST
Understanding RESTNitin Pande
 

What's hot (20)

gRPC with java
gRPC with javagRPC with java
gRPC with java
 
OpenAPI and gRPC Side by-Side
OpenAPI and gRPC Side by-SideOpenAPI and gRPC Side by-Side
OpenAPI and gRPC Side by-Side
 
Introduction to gRPC
Introduction to gRPCIntroduction to gRPC
Introduction to gRPC
 
gRPC
gRPCgRPC
gRPC
 
gRPC - RPC rebirth?
gRPC - RPC rebirth?gRPC - RPC rebirth?
gRPC - RPC rebirth?
 
What is gRPC introduction gRPC Explained
What is gRPC introduction gRPC ExplainedWhat is gRPC introduction gRPC Explained
What is gRPC introduction gRPC Explained
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...
 
The basics of fluentd
The basics of fluentdThe basics of fluentd
The basics of fluentd
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
Robert Kubis - gRPC - boilerplate to high-performance scalable APIs - code.t...
 Robert Kubis - gRPC - boilerplate to high-performance scalable APIs - code.t... Robert Kubis - gRPC - boilerplate to high-performance scalable APIs - code.t...
Robert Kubis - gRPC - boilerplate to high-performance scalable APIs - code.t...
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutions
 
Building your First gRPC Service
Building your First gRPC ServiceBuilding your First gRPC Service
Building your First gRPC Service
 
REST & RESTful Web Services
REST & RESTful Web ServicesREST & RESTful Web Services
REST & RESTful Web Services
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
Angular
AngularAngular
Angular
 
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
 
Building REST APIs using gRPC and Go
Building REST APIs using gRPC and GoBuilding REST APIs using gRPC and Go
Building REST APIs using gRPC and Go
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
Inter-Process Communication in Microservices using gRPC
Inter-Process Communication in Microservices using gRPCInter-Process Communication in Microservices using gRPC
Inter-Process Communication in Microservices using gRPC
 
Understanding REST
Understanding RESTUnderstanding REST
Understanding REST
 

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
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in GolangBo-Yi Wu
 
Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sksureshkarthick37
 

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
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
 
Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sk
 
CGI.ppt
CGI.pptCGI.ppt
CGI.ppt
 

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

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
 
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 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
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
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
 
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
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
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
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
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
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
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
 
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
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 

Recently uploaded (20)

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...
 
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 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
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
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...
 
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
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
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
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
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
 
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
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 

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.