<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Aman Saraiya on Medium]]></title>
        <description><![CDATA[Stories by Aman Saraiya on Medium]]></description>
        <link>https://medium.com/@aman-saraiya?source=rss-b01a5a9a6b24------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lQo4Ays8h9xo7yoLNidmyQ.jpeg</url>
            <title>Stories by Aman Saraiya on Medium</title>
            <link>https://medium.com/@aman-saraiya?source=rss-b01a5a9a6b24------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 04:44:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aman-saraiya/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A Deep Dive into gRPC: Service Definitions, Protobufs, and Hands-On Implementation]]></title>
            <link>https://medium.com/@aman-saraiya/a-deep-dive-into-grpc-service-definitions-protobufs-and-hands-on-implementation-777946d733ca?source=rss-b01a5a9a6b24------2</link>
            <guid isPermaLink="false">https://medium.com/p/777946d733ca</guid>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[remote-procedure-calls]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Aman Saraiya]]></dc:creator>
            <pubDate>Tue, 26 Nov 2024 09:49:43 GMT</pubDate>
            <atom:updated>2024-11-26T09:49:43.742Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JWCtDWiG-5561BWeCXIS9A.jpeg" /></figure><p><em>To gain a more holistic understanding of Remote Procedure Calls (RPC), the need for a framework like gRPC, and the design choices behind it, it’s recommended to first review </em><a href="https://medium.com/@aman-saraiya/grpc-is-not-the-only-rpc-framework-exploring-remote-procedure-calls-1ba90f9adb0c"><em>this previous article</em></a><em>, which explores the fundamentals of RPC and provides an RPC implementation example using Go’s net/rpc package.</em></p><p>In this article, we explore the fundamentals of gRPC, starting with its reliance on an Interface Definition Language (IDL) for service definitions. We delve into Protocol Buffers, the default serialization mechanism in gRPC, and examine their role in defining and structuring data. Through a hands-on implementation in Go, we demonstrate how to build gRPC services using Protocol Buffers. Finally, we discuss the flexibility of gRPC to support alternative serialization mechanisms. Let’s dive right in.</p><h3>Interface Definition language</h3><p>When we develop a gRPC application the first thing that we do is define a service interface. The service interface definition contains information on how the service can be consumed by consumers, what methods the consumers are allowed to call remotely, what method parameters and message formats to use when invoking those methods, and so on. The language that we use to specify the service definition is known as an interface definition language (IDL).</p><p>Using that service definition, we generate the server-side code known as a server skeleton, which simplifies the server-side logic by providing low-level communication abstractions. Also, it generates the client-side code, known as a client stub, which simplifies the client-side communication with abstractions to hide low-level communication for different programming languages. The methods that you specify in the service interface definition can be remotely invoked by the client side as easily as making a local function invocation. The underlying gRPC framework handles all the complexities that are normally associated with enforcing strict service contracts, data serialization, network communication, authentication, access control, observability, and so on.</p><h3>What are Protocol Buffers?</h3><p>Protocol Buffers, often abbreviated as Protobuf, are Google’s language-neutral and platform-neutral system for serializing structured data. At the core of Protobuf is the <em>.proto</em> file, which defines the structure of your data. Once this structure is specified, the Protobuf compiler (<a href="https://grpc.io/docs/protoc-installation/"><em>protoc</em></a>) is used generate code for a variety of supported programming languages. This generated code enables seamless reading and writing of structured data across platforms and data streams, making Protobuf an efficient tool for data serialization in distributed systems.</p><h4>Protocol Buffers in gRPC</h4><p>In gRPC, Protocol Buffers play a dual role. First, they serve as the default Interface Definition Language (IDL) for defining service interfaces. Second, they provide an efficient serialization mechanism for structuring and transmitting data. We define service interfaces in <em>.proto</em> files, specifying RPC methods, parameters, and return types using Protocol Buffer message formats. These .<em>proto</em> files are used to generate client stubs and server skeletons using the gRPC-specific plugin with the Protocol Buffer compiler. The generated components are used in your code to abstract away low-level details such as data serialization and network communication, simplifying interactions between clients and servers.</p><p>Let’s dive into the hands-on implementation of gRPC services using Protocol Buffers in Go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*MGAqsNPQnimqTjEUIujHpQ.png" /><figcaption>gRPC Request Response Flow</figcaption></figure><h3>Building gRPC Services with Protocol Buffers in Go</h3><p>In this section we will implement two gRPC services. The first service, UserService, will be similar to the one we implemented in the previous article using Go’s net/rpc package. It will include two Unary RPC methods: AddUser (to add a new user) and GetUser (to retrieve user details).</p><p>The second service, StatsService, will introduce a more advanced concept by including both Unary and Streaming RPCs. It will have two methods: GetStats, a Unary RPC to fetch statistics, and RunningStats, a Streaming RPC that continuously sends data, such as real-time statistics, to the client.</p><p><strong>Aside</strong>: In gRPC, Streaming RPCs allow for the continuous flow of data between the client and server. Unlike Unary RPCs, where a single request is sent and a single response is received, Streaming RPCs enable the exchange of multiple messages over the same connection.</p><p>Through this hands-on implementation, we will explore how to define gRPC services, generate code from Protocol Buffers, and implement both server and client-side logic in Go.</p><h4>Defining the Service Interface</h4><p><strong>Defining the UserService gRPC Service Interface</strong></p><pre>syntax = &quot;proto3&quot;;<br><br>package userservice;<br>option go_package = &quot;generated/userservice&quot;;<br><br>// User represents a user with an id, name, and email<br>message User {<br>  int32 id = 1;      <br>  string email = 2;   <br>  string name = 3;<br>}<br><br>// Request argument for AddUser RPC<br>message AddUserArg {<br>  string email = 1;<br>  string name = 2;<br>}<br><br>// Response returned by AddUser RPC<br>message AddUserRet {<br>  int32 id = 1;<br>}<br><br>// Request argument for GetUser RPC<br>message GetUserArg {<br>  int32 id = 1;<br>}<br><br>// Response returned by GetUser RPC<br>message GetUserRet {<br>  User user = 1;<br>}<br><br>// RPC service definition<br>service UserService {<br>  // AddUser RPC definition<br>  rpc AddUser (AddUserArg) returns (AddUserRet);<br><br>  // GetUser RPC definition<br>  rpc GetUser (GetUserArg) returns (GetUserRet);<br>}</pre><p>GitHub: <a href="https://github.com/aman-saraiya/remote-procedure-calls/blob/main/grpc-protobuf/client/protos/userservice.proto">userserivce.proto</a></p><p><strong>Defining the StatsService gRPC Service Interface</strong></p><pre>syntax = &quot;proto3&quot;;<br><br>package statsservice;<br>option go_package=&quot;generated/statsservice&quot;;<br><br>// Request argument for GetStats RPC<br>message GetStatsArg {<br>  repeated double numbers = 1;<br>}<br><br>// Response returned by GetStats RPC<br>message GetStatsRet {<br>  double mean = 1;<br>  double median = 2;<br>}<br><br>// Request argument for RunningStats RPC.<br>// NOTE: RunningStats is a bi-directional streaming RPC.<br>// Multiple RunningStatsArg can be sent as part of a <br>// single RPC request. (Client Side Streaming)<br>message RunningStatsArg {<br>  // A single number, sent during the bidirectional stream<br>  double number = 1;<br>}<br><br><br>// Response returned for RunningStats RPC<br>// Multiple RunningStatsRet could be returned by the<br>// server as part of a single RPC request. (Server Side Streaming)<br>message RunningStatsRet {<br>  // Running mean of the numbers received so far<br>  double mean = 1;<br><br>  // Running median of the numbers received so far<br>  double median = 2;  <br>}<br><br>// The StatsService defines the two RPCs<br>service StatsService {<br>  // Unary RPC to get statistics (mean, median) for a list of numbers<br>  rpc GetStats(GetStatsArg) returns (GetStatsRet);<br><br>  // Bidirectional Streaming RPC to get a stream of numbers <br>  // and return running statistics back<br>  rpc RunningStats(stream RunningStatsArg) returns (stream RunningStatsRet);<br>}</pre><p>GitHub: <a href="https://github.com/aman-saraiya/remote-procedure-calls/blob/main/grpc-protobuf/client/protos/statsservice.proto">statsservice.proto</a></p><p>We now use the Protocol Buffer compiler to generate the message structures, client stubs, and server skeletons in Go.</p><pre># To be run from grpc-protobuf/client/protos directory<br><br>protoc --go_out=../  --go-grpc_out=../ statsservice.proto<br>protoc --go_out=../  --go-grpc_out=../ userservice.proto</pre><h4>Exploring the Generated Code</h4><p>The Protocol Buffer compiler generates two files for each service: <em>&lt;proto_filename&gt;.pb.go </em>and <em>&lt;proto_filename&gt;_grpc.pb.go</em>. These files form the backbone of the gRPC implementation in Go.</p><p>The <em>.pb.go</em> file contains the Go structs corresponding to the protobuf messages defined in the <em>.proto</em> file. For example, in the <a href="https://github.com/aman-saraiya/remote-procedure-calls/blob/main/grpc-protobuf/client/generated/userservice/userservice.pb.go"><em>userservice.pb.go</em></a> file, you’ll find the generated structures for <em>User</em> and <em>AddUserArg</em> messages as specified in the <em>userservice.proto</em> file. Additionally, this file includes metadata necessary for serializing and deserializing these protobuf messages to and from their binary format, ensuring efficient data transmission.</p><pre>// User represents a user with an id, name, and email<br>type User struct {<br> state         protoimpl.MessageState<br> sizeCache     protoimpl.SizeCache<br> unknownFields protoimpl.UnknownFields<br><br> Id    int32  `protobuf:&quot;varint,1,opt,name=id,proto3&quot; json:&quot;id,omitempty&quot;`<br> Email string `protobuf:&quot;bytes,2,opt,name=email,proto3&quot; json:&quot;email,omitempty&quot;`<br> Name  string `protobuf:&quot;bytes,3,opt,name=name,proto3&quot; json:&quot;name,omitempty&quot;`<br>}<br><br>// Request argument for AddUser RPC<br>type AddUserArg struct {<br> state         protoimpl.MessageState<br> sizeCache     protoimpl.SizeCache<br> unknownFields protoimpl.UnknownFields<br><br> Email string `protobuf:&quot;bytes,1,opt,name=email,proto3&quot; json:&quot;email,omitempty&quot;`<br> Name  string `protobuf:&quot;bytes,2,opt,name=name,proto3&quot; json:&quot;name,omitempty&quot;`<br>}</pre><p>GitHub: <a href="https://github.com/aman-saraiya/remote-procedure-calls/blob/main/grpc-protobuf/client/generated/userservice/userservice.pb.go">userservice.pb.go</a></p><p>The file ending with <em>_grpc.pb.go</em> contains the service description, server skeleton, and client stubs generated by the Protocol Buffer compiler’s gRPC-specific plugin. These components are crucial for building the gRPC service and client, as they abstract away the complexities of network communication and serialization/deserialization. This file references the structures defined in the <em>.pb.go</em> file to handle data representation seamlessly.</p><p>Below, we examine the key sections of the generated file, including the client stub, server skeleton, and service description, which form the foundation for implementing and consuming the UserService.</p><pre>// UserServiceClient is the client API for UserService service.<br>//<br>// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.<br>//<br>// RPC service definition<br>type UserServiceClient interface {<br> // AddUser RPC definition<br> AddUser(ctx context.Context, in *AddUserArg, opts ...grpc.CallOption) (*AddUserRet, error)<br> // GetUser RPC definition<br> GetUser(ctx context.Context, in *GetUserArg, opts ...grpc.CallOption) (*GetUserRet, error)<br>}<br><br><br>type userServiceClient struct {<br> cc grpc.ClientConnInterface<br>}<br><br>func NewUserServiceClient(cc grpc.ClientConnInterface) UserServiceClient {<br> return &amp;userServiceClient{cc}<br>}<br><br>// UserServiceServer is the server API for UserService service.<br>// All implementations must embed UnimplementedUserServiceServer<br>// for forward compatibility.<br>//<br>// RPC service definition<br>type UserServiceServer interface {<br> // AddUser RPC definition<br> AddUser(context.Context, *AddUserArg) (*AddUserRet, error)<br> // GetUser RPC definition<br> GetUser(context.Context, *GetUserArg) (*GetUserRet, error)<br> mustEmbedUnimplementedUserServiceServer()<br>}<br><br>// UnimplementedUserServiceServer must be embedded to have<br>// forward compatible implementations.<br>//<br>// NOTE: this should be embedded by value instead of pointer to avoid a nil<br>// pointer dereference when methods are called.<br>type UnimplementedUserServiceServer struct{}<br><br><br><br>// UserService_ServiceDesc is the grpc.ServiceDesc for UserService service.<br>// It&#39;s only intended for direct use with grpc.RegisterService,<br>// and not to be introspected or modified (even as a copy)<br>var UserService_ServiceDesc = grpc.ServiceDesc{<br> ServiceName: &quot;userservice.UserService&quot;,<br> HandlerType: (*UserServiceServer)(nil),<br> Methods: []grpc.MethodDesc{<br>  {<br>   MethodName: &quot;AddUser&quot;,<br>   Handler:    _UserService_AddUser_Handler,<br>  },<br>  {<br>   MethodName: &quot;GetUser&quot;,<br>   Handler:    _UserService_GetUser_Handler,<br>  },<br> },<br> Streams:  []grpc.StreamDesc{},<br> Metadata: &quot;userservice.proto&quot;,<br>}</pre><p>GitHub: <a href="https://github.com/aman-saraiya/remote-procedure-calls/blob/main/grpc-protobuf/client/generated/userservice/userservice_grpc.pb.go">userservice_grpc.pb.go</a></p><h4>Implementing the gRPC Server</h4><p>We implement the handlers for UserService’s gRPC methods, over the sever skeleton generated using the proto file.</p><pre><br>package userservice<br><br>import (<br> &quot;context&quot;<br> &quot;fmt&quot;<br> &quot;log&quot;<br><br> gen_usersvc &quot;github.com/aman-saraiya/remote-procedure-calls/grpc-protobuf/client/generated/userservice&quot;<br>)<br><br>// Define the UserService gRPC service struct<br>type UserServiceServer struct {<br> gen_usersvc.UnimplementedUserServiceServer<br> Users map[int32]*gen_usersvc.User // Simple in-memory store for users<br>}<br><br>// Function to create UserServiceServer instance<br>func NewUserServiceServer() *UserServiceServer {<br> return &amp;UserServiceServer{<br>  Users: make(map[int32]*gen_usersvc.User),<br> }<br>}<br><br>// Handler for AddUser RPC<br>func (s *UserServiceServer) AddUser(ctx context.Context, req *gen_usersvc.AddUserArg) (*gen_usersvc.AddUserRet, error) {<br> log.Println(&quot;Handling AddUser RPC with argument &quot;, req)<br> userID := int32(len(s.Users)+1)<br><br> // Create a new user<br> user := &amp;gen_usersvc.User{<br>  Id:    userID,<br>  Email: req.GetEmail(),<br>  Name:  req.GetName(),<br> }<br><br> s.Users[userID] = user<br><br> return &amp;gen_usersvc.AddUserRet{<br>  Id: userID,<br> }, nil<br>}<br><br>// Handler for GetUser RPC<br>func (s *UserServiceServer) GetUser(ctx context.Context, req *gen_usersvc.GetUserArg) (*gen_usersvc.GetUserRet, error) {<br> log.Println(&quot;Handling GetUser RPC with argument &quot;, req)<br> userID := req.GetId()<br><br> user, exists := s.Users[userID]<br> if !exists {<br>  return nil, fmt.Errorf(&quot;User with ID %d not found&quot;, userID)<br> }<br><br> return &amp;gen_usersvc.GetUserRet{<br>  User: user,<br> }, nil<br>}</pre><p>GitHub: <a href="https://github.com/aman-saraiya/remote-procedure-calls/blob/main/grpc-protobuf/server/userservice/userservice.go">userservice.go</a></p><p>Next, we implement the handlers for StatsService’s gRPC methods, over the sever skeleton generated using the proto file.</p><pre>package statsservice<br><br>import (<br> &quot;context&quot;<br> &quot;fmt&quot;<br> &quot;log&quot;<br> &quot;sort&quot;<br><br> &quot;github.com/aman-saraiya/remote-procedure-calls/grpc-protobuf/client/generated/statsservice&quot;<br>)<br><br>// Define the StatsService gRPC service struct<br>type StatsServiceServer struct {<br> statsservice.UnimplementedStatsServiceServer<br> numbers []float64<br>}<br><br>// Function to create StatsServiceServer instance<br>func NewStatsServiceServer() *StatsServiceServer{<br> statsSvcServer := &amp;StatsServiceServer{}<br> return statsSvcServer<br>}<br><br>// Handler for GetStats gRPC<br>func (s *StatsServiceServer) GetStats(ctx context.Context, req *statsservice.GetStatsArg) (*statsservice.GetStatsRet, error) {<br> log.Println(&quot;Handling GetStats RPC with argument &quot;, req)<br> numbers := req.Numbers<br> // Calculate mean<br> mean := calculateMean(numbers)<br><br> // Calculate median<br> median := calculateMedian(numbers)<br><br> return &amp;statsservice.GetStatsRet{<br>  Mean:   mean,<br>  Median: median,<br> }, nil<br>}<br><br>// Handler for RunningStats gRPC<br>func (s *StatsServiceServer) RunningStats(stream statsservice.StatsService_RunningStatsServer) error {<br> log.Println(&quot;Handling RunningStats RPC&quot;)<br> var runningNumbers []float64<br><br> for {<br>  // Receiving the stream of numbers sent by the client<br>  req, err := stream.Recv()<br>  <br>  if err != nil {<br>   // EOF or other error. EOF indicates the client has closed the stream<br>   if err.Error() == &quot;EOF&quot; {<br>    fmt.Println(&quot;Client has closed the stream&quot;)<br>    break<br>   }<br>   fmt.Printf(&quot;Error receiving message: %v&quot;, err)<br>   return err<br>  }<br>  log.Println(&quot;Data received over stream &quot;, req)<br><br>  runningNumbers = append(runningNumbers, req.Number)<br>  log.Println(&quot;Calculating mean and median for &quot;, runningNumbers)<br><br>  // Calculate running mean<br>  runningMean := calculateMean(runningNumbers)<br><br>  // Calculate running median<br>  runningMedian := calculateMedian(runningNumbers)<br><br>  // Send the running stats back<br>  if err := stream.Send(&amp;statsservice.RunningStatsRet{<br>   Mean:   runningMean,<br>   Median: runningMedian,<br>  }); err != nil {<br>   return err<br>  }<br> }<br> return nil<br>}<br><br>// Calculate the mean of a list of numbers<br>func calculateMean(numbers []float64) float64 {<br> var sum float64<br> for _, num := range numbers {<br>  sum += num<br> }<br> return sum / float64(len(numbers))<br>}<br><br>// Calculate the median of a list of numbers<br>func calculateMedian(numbers []float64) float64 {<br> sort.Float64s(numbers)<br> n := len(numbers)<br> if n%2 == 0 {<br>  return (numbers[n/2-1] + numbers[n/2]) / 2<br> }<br> return numbers[n/2]<br>}<br></pre><p>GitHub: <a href="https://github.com/aman-saraiya/remote-procedure-calls/blob/main/grpc-protobuf/server/statsservice/statsservice.go">statsservice.go</a></p><p>To set up the gRPC server, we begin by creating a listener using <em>net.Listen()</em> on the desired port, in this case, <em>localhost:50051</em>. Then, we initialize the gRPC server using <em>grpc.NewServer()</em>, which is provided by the gRPC framework. After that, we register the gRPC services by binding the generated service implementations to the server instance. Finally, we start listening for incoming connections by passing the listener to <em>grpcServer.Server(listen)</em>, which links the server to the listener and manages client requests.</p><pre>package main<br><br>import (<br> &quot;log&quot;<br> &quot;net&quot;<br><br> gen_statssvc &quot;github.com/aman-saraiya/remote-procedure-calls/grpc-protobuf/client/generated/statsservice&quot;<br> gen_usersvc &quot;github.com/aman-saraiya/remote-procedure-calls/grpc-protobuf/client/generated/userservice&quot;<br> &quot;github.com/aman-saraiya/remote-procedure-calls/grpc-protobuf/server/statsservice&quot;<br> &quot;github.com/aman-saraiya/remote-procedure-calls/grpc-protobuf/server/userservice&quot;<br> &quot;google.golang.org/grpc&quot;<br>)<br><br>func main() {<br> grpcServer := grpc.NewServer()<br><br> userSvcServer := userservice.NewUserServiceServer()<br> statsSvcServer := statsservice.NewStatsServiceServer()<br><br> gen_usersvc.RegisterUserServiceServer(grpcServer, userSvcServer)<br> gen_statssvc.RegisterStatsServiceServer(grpcServer, statsSvcServer)<br><br> listen, err := net.Listen(&quot;tcp&quot;, &quot;localhost:50051&quot;)<br> if err != nil {<br>  log.Fatalf(&quot;Failed to listen: %v&quot;, err)<br> }<br><br> log.Println(&quot;Server is listening on port 50051...&quot;)<br> if err := grpcServer.Serve(listen); err != nil {<br>  log.Fatalf(&quot;failed to serve: %v&quot;, err)<br> }<br>}</pre><p>GitHub: <a href="https://github.com/aman-saraiya/remote-procedure-calls/blob/main/grpc-protobuf/server/server.go">server.go</a></p><h4>Implementing the gRPC client</h4><p>In the client code, we begin by establishing a connection to the gRPC server using <em>grpc.Dial()</em>. Once the connection is established, we initialize the gRPC service clients for <em>UserService</em> and <em>StatsService</em>. Notice here that both clients share the same underlying connection, which allows them to send requests over a single TCP connection. This is done by calling the respective service constructors, <em>NewUserServiceClient()</em> and <em>NewStatsServiceClient()</em>, passing the connection object.</p><p>Next, several gRPC calls are made. The <em>AddUser</em> gRPC creates a new user, followed by <em>GetUser</em> to retrieve the user by their ID. The <em>GetStats</em> RPC calculates the mean and median for a list of numbers. Finally, the client demonstrates the <em>RunningStats</em> bidirectional streaming RPC, where numbers are streamed to the server, and running statistics are received in return.</p><p>The client code illustrates how both unary and streaming RPCs interact with the gRPC server. In this example, all the RPC calls are made serially, with each request waiting for the previous one to complete. However, we could also make multiple RPC calls in parallel, as gRPC is built on top of <a href="https://en.wikipedia.org/wiki/HTTP/2">HTTP/2</a>, which supports multiplexing.</p><blockquote><strong>Aside: Multiplexing in gRPC</strong><br>gRPC leverages multiplexing over HTTP/2, which allows multiple streams of data to be sent simultaneously over a single TCP connection. This means that a client can make several RPC calls at the same time without needing to open multiple connections, reducing overhead and improving performance. Each RPC call is handled in a separate stream within the connection, making it more efficient and responsive, especially in environments with high concurrency.</blockquote><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;fmt&quot;<br> &quot;time&quot;<br><br> &quot;google.golang.org/grpc&quot;<br> gen_usersvc &quot;github.com/aman-saraiya/remote-procedure-calls/grpc-protobuf/client/generated/userservice&quot;<br> gen_statssvc &quot;github.com/aman-saraiya/remote-procedure-calls/grpc-protobuf/client/generated/statsservice&quot;<br>)<br><br>func invokeAddUserGRPC(userSvcClient gen_usersvc.UserServiceClient, name, email string) int32 {<br> // Initialize the AddUser RPC request argument<br> addUserArg := &amp;gen_usersvc.AddUserArg{<br>  Email: email,<br>  Name:  name,<br> }<br><br> // Declaring the RPC response variable to store the return value<br> var addUserRet *gen_usersvc.AddUserRet<br><br> // Calling the User Service&#39;s AddUser RPC<br> addUserRet, err := userSvcClient.AddUser(context.Background(), addUserArg)<br> if err != nil {<br>  fmt.Errorf(&quot;Error calling AddUser: %v\n&quot;, err)<br> }<br> fmt.Printf(&quot;Added user with ID: %d\n\n&quot;, addUserRet.GetId())<br> <br> return addUserRet.GetId()<br>}<br><br>func invokeGetUserGRPC(userSvcClient gen_usersvc.UserServiceClient, id int32){<br> // Initialize the RPC request argument<br> getUserArg := &amp;gen_usersvc.GetUserArg{Id: id}<br><br> // Declaring the RPC response variable to store the return value <br> var getUserRet *gen_usersvc.GetUserRet<br> <br> // Calling the UserService&#39;s GetUser RPC<br> getUserRet, err := userSvcClient.GetUser(context.Background(), getUserArg)<br> if err != nil {<br>  fmt.Errorf(&quot;Error calling GetUser: %v&quot;, err)<br> }<br> retrievedUser := getUserRet.GetUser()<br><br> fmt.Printf(&quot;Retrieved user: Id = %d, Name = %s, Email = %s\n\n&quot;,<br>  retrievedUser.GetId(), retrievedUser.GetName(), retrievedUser.GetEmail())<br>}<br><br>func invokeGetStatsGRPC(client gen_statssvc.StatsServiceClient, numbers []float64) {<br> //Initialize the RPC request argument<br> getStatsArg := &amp;gen_statssvc.GetStatsArg{Numbers: numbers}<br><br> // Declaring the RPC response variable to store the response<br> var getStatsRet *gen_statssvc.GetStatsRet<br><br> // Calling the StatsService&#39;s GetStats RPC<br> getStatsRet, err := client.GetStats(context.Background(), getStatsArg)<br> if err != nil {<br>  fmt.Errorf(&quot;Error calling GetStats: %v&quot;, err)<br> }<br> fmt.Printf(&quot;Mean: %.2f, Median: %.2f\n&quot;, getStatsRet.Mean, getStatsRet.Median)<br>}<br><br>func invokeRunningStatsGRPC(client gen_statssvc.StatsServiceClient, numbers []float64) {<br> // Calling the RunningStats RPC to start the stream<br> stream, err := client.RunningStats(context.Background())<br> if err != nil {<br>  fmt.Errorf(&quot;Could not start RunningStats stream: %v&quot;, err)<br> }<br><br> // Starting a separate go routine to send the numbers over the stream<br> go func() {<br>  for idx, num := range numbers {<br>   // Initializing RunningStatsArg<br>   runningStatsArg := &amp;gen_statssvc.RunningStatsArg{Number: num}<br>   fmt.Println(&quot;Sending &quot;, runningStatsArg, &quot; to server over stream.&quot;)<br>   fmt.Println(&quot;Overall Data Streamed &quot;, numbers[:idx+1])<br>   if err := stream.Send(runningStatsArg); err != nil {<br>    fmt.Errorf(&quot;Could not send number: %v&quot;, err)<br>   }<br>   time.Sleep(2 * time.Second)<br>  }<br>  stream.CloseSend()<br> }()<br><br> // Receive the running mean and median from the server<br> for {<br>  resp, err := stream.Recv()<br>  if err != nil {<br>   if err.Error() == &quot;EOF&quot; {<br>    fmt.Println(&quot;Server has closed the stream&quot;)<br>    break<br>   }<br>   fmt.Errorf(&quot;Could not receive running stats: %v&quot;, err)<br>  }<br>  fmt.Printf(&quot;Running Mean: %.2f, Running Median: %.2f\n\n&quot;, resp.Mean, resp.Median)<br> }<br>}<br><br>func main() {<br> // Connect to the server<br> conn, err := grpc.Dial(&quot;localhost:50051&quot;, grpc.WithInsecure(), grpc.WithBlock())<br> if err != nil {<br>  fmt.Errorf(&quot;could not connect: %v&quot;, err)<br> }<br> defer conn.Close()<br><br> // Initializing clients for UserService and StatsService<br> // Notice here that both the service clients use the same<br> // underlying connection to send the requests.<br> userSvcClient := gen_usersvc.NewUserServiceClient(conn)<br> statsSvcClient := gen_statssvc.NewStatsServiceClient(conn)<br><br> fmt.Println(&quot;UserService RPC Calls\n&quot;)<br> // Adding new User<br> fmt.Println(&quot;Calling AddUser RPC&quot;)<br> idOfCreatedUser := invokeAddUserGRPC(userSvcClient, &quot;Aman Saraiya&quot;, &quot;amansaraiya937@gmail.com&quot;)<br><br> fmt.Println(&quot;Retrieving the newly created User&quot;)<br> // Retrieving the newly created User<br> invokeGetUserGRPC(userSvcClient, idOfCreatedUser)<br> <br> fmt.Println(&quot;\nStatsService RPC Calls\n&quot;)<br> // Get Mean and Median for numbers<br> numbers := []float64{6.5, 4.0, 0.5, 4.5, 9.5}<br> fmt.Println(&quot;Calling GetStats RPC with numbers: &quot;, numbers)<br> invokeGetStatsGRPC(statsSvcClient, numbers)<br><br> // Demonstrating the RunningStats bidirectional streaming RPC<br> fmt.Println(&quot;\nCalling RunningStats RPC&quot;)<br> invokeRunningStatsGRPC(statsSvcClient, numbers)<br>}</pre><p>GitHub: <a href="https://github.com/aman-saraiya/remote-procedure-calls/blob/main/grpc-protobuf/client/client.go">client.go</a></p><h4>Execution Results</h4><p>Server Logs:</p><pre>2024/11/24 17:09:45 Server is listening on port 50051...<br>2024/11/24 17:09:53 Handling AddUser RPC with argument  email:&quot;amansaraiya937@gmail.com&quot;  name:&quot;Aman Saraiya&quot;<br>2024/11/24 17:09:53 Handling GetUser RPC with argument  id:1<br>2024/11/24 17:09:53 Handling GetStats RPC with argument  numbers:6.5  numbers:4  numbers:0.5  numbers:4.5  numbers:9.5<br>2024/11/24 17:09:53 Handling RunningStats RPC<br>2024/11/24 17:09:53 Data received over stream  number:6.5<br>2024/11/24 17:09:53 Calculating mean and median for  [6.5]<br>2024/11/24 17:09:55 Data received over stream  number:4<br>2024/11/24 17:09:55 Calculating mean and median for  [6.5 4]<br>2024/11/24 17:09:57 Data received over stream  number:0.5<br>2024/11/24 17:09:57 Calculating mean and median for  [4 6.5 0.5]<br>2024/11/24 17:09:59 Data received over stream  number:4.5<br>2024/11/24 17:09:59 Calculating mean and median for  [0.5 4 6.5 4.5]<br>2024/11/24 17:10:01 Data received over stream  number:9.5<br>2024/11/24 17:10:01 Calculating mean and median for  [0.5 4 4.5 6.5 9.5]<br>Client has closed the stream</pre><p>Client Output:</p><pre>UserService RPC Calls<br><br>Calling AddUser RPC<br>Added user with ID: 1<br><br>Retrieving the newly created User<br>Retrieved user: Id = 1, Name = Aman Saraiya, Email = amansaraiya937@gmail.com<br><br><br>StatsService RPC Calls<br><br>Calling GetStats RPC with numbers:  [6.5 4 0.5 4.5 9.5]<br>Mean: 5.00, Median: 4.50<br><br>Calling RunningStats RPC<br>Sending  number:6.5  to server over stream.<br>Overall Data Streamed  [6.5]<br>Running Mean: 6.50, Running Median: 6.50<br><br>Sending  number:4  to server over stream.<br>Overall Data Streamed  [6.5 4]<br>Running Mean: 5.25, Running Median: 5.25<br><br>Sending  number:0.5  to server over stream.<br>Overall Data Streamed  [6.5 4 0.5]<br>Running Mean: 3.67, Running Median: 4.00<br><br>Sending  number:4.5  to server over stream.<br>Overall Data Streamed  [6.5 4 0.5 4.5]<br>Running Mean: 3.88, Running Median: 4.25<br><br>Sending  number:9.5  to server over stream.<br>Overall Data Streamed  [6.5 4 0.5 4.5 9.5]<br>Running Mean: 5.00, Running Median: 4.50<br><br>Server has closed the stream</pre><p>Get the entire source code at: <a href="https://github.com/aman-saraiya/remote-procedure-calls/tree/main/grpc-protobuf">https://github.com/aman-saraiya/remote-procedure-calls/tree/main/grpc-protobuf</a></p><h3>Beyond Protocol Buffers: Exploring Alternative Serialization Mechanisms</h3><p>While Protocol Buffers serve as the default Interface Definition Language (IDL) and serialization mechanism in gRPC, they are not the only option. gRPC is flexible enough to support other serialization mechanisms, allowing developers to choose one that best suits their use case. For example, FlatBuffers, an efficient serialization library by Google, is a popular alternative that eliminates the need for deserialization, providing a faster and more memory-efficient solution.</p><p>In the next article, we will explore how to implement gRPC services using FlatBuffers as the underlying serialization mechanism. This will showcase the adaptability of gRPC and provide insights into how different serialization methods can impact the performance and design of distributed systems.</p><p>If you found this article helpful, have questions, or would like to share your insights, please feel free to leave your comments below. For more updates, articles, and discussions on software development, follow <a href="https://medium.com/u/b01a5a9a6b24?source=post_page---user_mention--1d6bcacd3340--------------------------------">Aman Saraiya</a> and connect with me on <a href="https://www.linkedin.com/in/amansaraiya/">LinkedIn</a>.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=777946d733ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[gRPC is Not the Only RPC framework: Exploring Remote Procedure Calls]]></title>
            <link>https://medium.com/@aman-saraiya/grpc-is-not-the-only-rpc-framework-exploring-remote-procedure-calls-1ba90f9adb0c?source=rss-b01a5a9a6b24------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ba90f9adb0c</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[hands-on-learning]]></category>
            <category><![CDATA[remote-procedure-calls]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Aman Saraiya]]></dc:creator>
            <pubDate>Tue, 26 Nov 2024 09:23:18 GMT</pubDate>
            <atom:updated>2024-11-26T11:17:47.971Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bznUtVjl78QZM6Sp9GPKuw.jpeg" /></figure><p>This article explores the fundamentals of Remote Procedure Calls (RPC). We begin by discussing the importance of Inter-Process Communication (IPC) and the limitations of using REST. Then, we dive into RPC, showing how to build a simple RPC service in Go with the net/rpc package. Finally, we cover the evolution of RPCs and the need for advanced RPC frameworks in modern distributed systems.</p><h3>Why is Inter-Process Communication Crucial in Modern Systems?</h3><p>In today’s software landscape, applications rarely function in isolation. Instead, they are interconnected through networks and exchange messages to collaborate and perform complex tasks. This interconnectedness is foundational to modern architectures like microservices, where individual services, each responsible for a specific piece of functionality, must communicate seamlessly to deliver a cohesive application. The need for reliable, efficient, and secure communication between these distributed components is where Inter-Process Communication (IPC) becomes essential. IPC allows different processes — whether running on the same machine or across a network — to exchange data, trigger actions, and synchronize tasks without direct access to each other’s memory space.</p><h3>What are the key issues with using REST for inter-process communication?</h3><p>While REST (Representational State Transfer) has traditionally been the go-to approach for inter-process communication, it has several limitations as modern systems grow more complex. Some of the key issues include:</p><ul><li><strong>Inefficient text-based message protocols:</strong> RESTful services rely on text-based transport protocols like HTTP 1.x and human-readable formats like JSON. This introduces unnecessary overhead, as data must be converted from binary to text and back, making it less efficient than using a direct binary format.</li><li><strong>Lack of strong typing</strong>: REST does not enforce a formal service or message definition, which can result in inconsistencies and errors, particularly when different services are built using diverse technologies. This can lead to runtime issues and compatibility challenges.</li><li><strong>Scalability concerns</strong>: With the proliferation of microservices in modern architectures, RESTful services can become a bottleneck, especially when handling large volumes of data or frequent requests.</li><li><strong>Inconsistent implementation</strong>: While REST defines a set of principles, there is no strict enforcement of these guidelines. As a result, many so-called RESTful services don’t fully adhere to the core principles of REST, leading to inconsistencies in service design and implementation.</li></ul><p>These challenges have driven the need for more efficient and strongly-typed alternatives, such as Remote Procedure Calls (RPC), which offer a better solution for modern distributed systems.</p><h3>What is a Remote Procedure Call?</h3><p>A <strong>Remote Procedure Call (RPC)</strong> is a communication method that allows a client to execute a procedure (or function) on a remote server as if it were a local call, abstracting the complexity of network communication. It enables different systems to interact by invoking functions on a remote machine without needing to manage the details of the network.</p><p>Unlike REST, which typically uses text-based formats like JSON for request-response communication, RPC directly invokes methods, passing arguments and receiving results. It often uses more efficient binary protocols, making RPC a faster and more streamlined choice for inter-process communication, especially when high performance and low latency are required.</p><p>RPC is an approach for inter-process communication that is independent of any specific programming language. For the purpose of this article, we will use Go as the language of choice to implement the example code.</p><h3>Building a Simple RPC Service with net/rpc in Go</h3><p>The <a href="https://pkg.go.dev/net/rpc">net/rpc</a> package in Go provides the ability to access the exported methods of an object across a network or other I/O connection. A server registers an object, making it visible as a service with the name of the type of the object. After registration, exported methods of the object will be accessible remotely.</p><p>By default, the net/rpc package in Go uses <strong>encoding/gob</strong>, a binary format, for <a href="https://en.wikipedia.org/wiki/Marshalling_(computer_science)">marshalling</a> and un-marshalling data. This avoids the overhead of converting binary data to text and back, as is the case with formats like JSON. While gob is the default, a custom codec can be used with net/rpc if needed for specific use cases.</p><p>For this example, we will implement a simple UserService RPC service with two methods: AddUser and GetUser. Both the server and client code are available on GitHub at <a href="https://github.com/aman-saraiya/remote-procedure-calls/tree/main/rpc-go-standard">https://github.com/aman-saraiya/remote-procedure-calls/tree/main/rpc-go-standard</a>.</p><p>Let’s start by defining the shared data structures.</p><p><strong>Defining Shared Structures</strong></p><p>One of the limitations of REST is that it lacks a formal mechanism for defining the structure of requests and responses. In case of RPCs, the contract is typically enforced through predefined service and message definitions, ensuring strong typing and reducing the risk of errors.</p><p>In the case of net/rpc, typically these shared types are defined as Go structs itself, which both the client and server can use to ensure consistency in the data they send and receive.</p><pre>package sharedstructs<br><br>// User represents a user with an ID, Name, and Email.<br>type User struct {<br> ID int<br> Name string<br> Email string<br>}<br><br>// Request argument for AddUser RPC<br>type AddUserArg struct {<br> Name  string<br> Email string<br>}<br><br>// Response returned by AddUser RPC<br>type AddUserRet struct {<br> ID int<br>}<br><br>// Request argument for GetUser RPC<br>type GetUserArg struct {<br> ID int<br>}<br><br>// Response returned by GetUser RPC<br>type GetUserRet struct {<br> User User<br>}</pre><p>Github: <a href="https://github.com/aman-saraiya/remote-procedure-calls/blob/main/rpc-go-standard/client/sharedstructs/userservice_structs.go">userservice_structs.go</a></p><p><strong>Implementing the RPC Server</strong></p><p>Defining the RPC service and implement the handlers for the server methods.</p><pre>package userservice<br><br>import (<br> &quot;fmt&quot;<br> &quot;log&quot;<br><br> ss &quot;github.com/aman-saraiya/remote-procedure-calls/rpc-go-standard/client/sharedstructs&quot;<br>)<br><br>// Defining the RPC Service struct<br>type UserService struct {<br> Users map[int]ss.User <br>}<br><br>// Function to create RPC service instance<br>func NewUserService() *UserService {<br> return &amp;UserService{<br>  Users: make(map[int]ss.User),<br> }<br>}<br><br>// Handler for AddUser RPC<br>func (svc *UserService) AddUser(arg *ss.AddUserArg, ret *ss.AddUserRet) error {<br> log.Println(&quot;Handling AddUser RPC with argument &quot;, arg)<br>id := len(svc.Users) + 1<br> newUser := ss.User{<br>  ID:    id,<br>  Email: arg.Email,<br>  Name:  arg.Name,<br> }<br> svc.Users[id] = newUser<br> ret.ID = id<br> return nil<br>}<br><br>// Handler for GetUser RPC<br>func (svc *UserService) GetUser(arg *ss.GetUserArg, ret *ss.GetUserRet) error {<br> log.Println(&quot;Handling GetUser RPC with argument &quot;, arg)<br> user, exists := svc.Users[arg.ID]<br> if !exists {<br>  return fmt.Errorf(&quot;User with ID %d not found&quot;, arg.ID)<br> }<br> ret.User = user<br> return nil<br>}</pre><p>Github: <a href="https://github.com/aman-saraiya/remote-procedure-calls/blob/main/rpc-go-standard/server/userservice/userservice.go">userservice.go</a></p><p>Registering the service with the server and starting the RPC server.</p><pre>package main<br><br>import (<br> &quot;log&quot;<br> &quot;net&quot;<br> &quot;net/rpc&quot;<br><br> &quot;github.com/aman-saraiya/remote-procedure-calls/rpc-go-standard/server/userservice&quot;<br>)<br><br>func main() {<br> <br> // Declaring and Initializing the UserService<br> userSvc := userservice.NewUserService()<br><br> // Registering the UserService service to the RPC server<br> err := rpc.Register(userSvc)<br> if err != nil {<br>  log.Fatalf(&quot;Error registering UserService: %v&quot;, err)<br> }<br><br> // Starting a TCP listener at port 2024<br> listener, err := net.Listen(&quot;tcp&quot;, &quot;localhost:2024&quot;)<br> if err != nil {<br>  log.Fatalf(&quot;Error starting server: %v&quot;, err)<br> }<br> log.Println(&quot;Server is listening on port 2024&quot;)<br> defer listener.Close()<br><br> for {<br>  // Accept incoming connection requests from clients<br>  conn, err := listener.Accept()<br>  if err != nil {<br>   log.Println(&quot;Error accepting connection:&quot;, err)<br>   continue<br>  }<br><br>  // Serve RPC over the accepted client connection <br>  go rpc.ServeConn(conn)<br> }<br>}</pre><p>Github: <a href="https://github.com/aman-saraiya/remote-procedure-calls/blob/main/rpc-go-standard/server/server.go">server.go</a></p><p><strong>Implementing the RPC client</strong></p><p>Using the RPC client to connect to the server and invoke remote procedures.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;log&quot;<br> &quot;net/rpc&quot;<br><br> ss &quot;github.com/aman-saraiya/remote-procedure-calls/rpc-go-standard/client/sharedstructs&quot;<br>)<br><br>func invokeAddUserRPC(client *rpc.Client, email, name string) int {<br> // Initialize the AddUser RPC request argument<br> addUserArg := &amp;ss.AddUserArg{<br>  Email: email,<br>  Name:  name,<br> }<br><br> // Declare the RPC response variable to store the return value<br> var addUserRet ss.AddUserRet<br> <br> // Calling the UserService&#39;s AddUser RPC<br> err := client.Call(&quot;UserService.AddUser&quot;, addUserArg, &amp;addUserRet)<br> if err != nil {<br>  fmt.Errorf(&quot;Error calling AddUser: %v\n&quot;, err)<br> }<br> fmt.Printf(&quot;Added user with ID: %d\n&quot;, addUserRet.ID)<br> <br> return addUserRet.ID <br>}<br><br>func invokeGetUserRPC(client *rpc.Client, id int) {<br> // Initialize the RPC request argument<br> getUserArgs := &amp;ss.GetUserArg{ID: id}<br><br> // Declaring the RPC response variable to store the return value <br> var getUserRet ss.GetUserRet<br> <br> // Calling the UserService&#39;s GetUser RPC<br> err := client.Call(&quot;UserService.GetUser&quot;, getUserArgs, &amp;getUserRet)<br> if err != nil {<br>  log.Fatalf(&quot;Error calling GetUser: %v&quot;, err)<br> }<br> fmt.Printf(&quot;Retrieved user: ID = %d, Name = %s, Email = %s\n&quot;,<br>  getUserRet.User.ID, getUserRet.User.Name, getUserRet.User.Email)<br>}<br><br>func main() {<br> // Attempts to connect to the RPC server<br> client, err := rpc.Dial(&quot;tcp&quot;, &quot;localhost:2024&quot;)<br> if err != nil {<br>  fmt.Errorf(&quot;Error connecting to server: %v&quot;, err)<br>  return<br> }<br> defer client.Close()<br><br> // Adding new User<br> idOfCreatedUser := invokeAddUserRPC(client, &quot;amansaraiya937@gmail.com&quot;, &quot;Aman Saraiya&quot;)<br><br> // Retrieving the newly created User<br> invokeGetUserRPC(client, idOfCreatedUser)<br>}</pre><p>GitHub: <a href="https://github.com/aman-saraiya/remote-procedure-calls/blob/main/rpc-go-standard/client/client.go">client.go</a></p><p><strong>Execution Results</strong></p><p>Server Logs:</p><pre>2024/11/24 13:00:56 Server is listening on port 2024<br>2024/11/24 13:01:06 Handling AddUser RPC with argument  &amp;{Aman Saraiya amansaraiya937@gmail.com}<br>2024/11/24 13:01:06 Handling GetUser RPC with argument  &amp;{1}</pre><p>Output:</p><pre>Added user with ID: 1<br>Retrieved user: ID = 1, Name = Aman Saraiya, Email = amansaraiya937@gmail.com</pre><h3>Evolution of Remote Procedure Calls</h3><p>Remote Procedure Calls (RPC) have been a key technology for distributed systems, enabling clients to invoke methods on remote servers as if they were local. Early RPC implementations like CORBA (Common Object Request Broker Architecture) and Java RMI (Remote Method Invocation) offered fundamental RPC functionality but were often complex and lacked interoperability. CORBA, in particular, required extensive configuration and was difficult to implement across multiple languages and platforms.</p><p>SOAP (Simple Object Access Protocol) was introduced to address some of these challenges. It provided a standardized way to exchange data in XML over various transport protocols, typically HTTP. While SOAP was widely adopted in enterprise environments, its reliance on complex<strong> </strong>XML<strong> </strong>schemas and bloated specifications made it cumbersome and slow to evolve.</p><h3>The Need for Modern RPC Frameworks</h3><p>Despite the evolution of RPC technologies, frameworks like <strong>net/rpc</strong> in Go still have several limitations that hinder their use in modern, large-scale distributed systems. Some of these include:</p><ul><li><strong>Limited Language Support</strong>: net/rpc is Go-specific, making it difficult to use in environments that involve multiple programming languages. Cross-language communication is not natively supported.</li><li><strong>No Built-in Service and Message Definitions</strong>: net/rpc lacks a formal contract for services, which can lead to compatibility issues between client and server. In the next article, we’ll explore the role of interface definition languages (IDLs) in solving this problem.</li><li><strong>No Native Support for Streaming</strong>: net/rpc does not support continuous data streams, limiting its use for real-time applications and large-scale data transfers.</li><li><strong>Limited Security Features</strong>: net/rpc does not include built-in mechanisms for authentication, authorization, or encryption (e.g., TLS), requiring manual implementation of these critical security features.</li></ul><p>Given these limitations, there is a clear need for more feature-rich and flexible RPC frameworks. To address this, many companies turn to widely adopted open-source frameworks like <strong>gRPC</strong> (developed by Google) or <strong>Apache Thrift</strong> (originally developed by Facebook). Some organizations also develop their own custom RPC frameworks; for example, at Nutanix, we have <strong>nRPC</strong> (Nutanix RPC) as our own solution.</p><p>Among the available open-source RPC frameworks, gRPC has emerged as one of the most popular and widely used due to its efficiency, cross-language support, and rich feature set. It is particularly well-suited for modern microservices architectures and cloud-native applications.</p><p>If you found this article helpful, have questions, or would like to share your insights, please feel free to leave your comments below. For more updates, articles, and discussions on software development, follow <a href="https://medium.com/u/b01a5a9a6b24?source=post_page---user_mention--1d6bcacd3340--------------------------------">Aman Saraiya</a> and connect with me on <a href="https://www.linkedin.com/in/amansaraiya/">LinkedIn</a>.</p><p>In the next article, we dive deeper into gRPC, explore its architecture, and demonstrate how to implement simple services using gRPC. Review here: <a href="https://medium.com/@aman-saraiya/a-deep-dive-into-grpc-service-definitions-protobufs-and-hands-on-implementation-777946d733ca">A Deep Dive into gRPC: Service Definitions, Protobufs, and Hands-On Implementation.</a></p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ba90f9adb0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Foundations of Security Testing: Terminology, Approaches and Tools]]></title>
            <link>https://medium.com/@aman-saraiya/foundations-of-security-testing-terminology-approaches-and-tools-1d6bcacd3340?source=rss-b01a5a9a6b24------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d6bcacd3340</guid>
            <category><![CDATA[vulnerability-scanning]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[application-security]]></category>
            <dc:creator><![CDATA[Aman Saraiya]]></dc:creator>
            <pubDate>Wed, 10 Jan 2024 09:10:29 GMT</pubDate>
            <atom:updated>2024-01-10T09:10:29.314Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building a Strong Foundation in Security Assessment</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LWt0BsbKJxSdWYD0" /></figure><p>Building the next big thing in software, right? You’re deep in the zone, crafting that much-anticipated feature. But wait — the security squad’s at the door, reminding you that you can’t just roll it out to customers. You need to scrutinize your creation for security gaps before releasing it. A bit of a challenge? Perhaps. But let’s dive into why it’s more than a mere hurdle.</p><p>In the real world, neglecting this critical step has hefty consequences. Have you heard of a data leak at Meta in 2021? It exposed the details of over <a href="https://www.theverge.com/2022/11/28/23481786/meta-fine-facebook-data-leak-ireland-dpc-gdpr">533 million</a> Facebook users and resulted in a substantial fine of <a href="https://www.theverge.com/2022/11/28/23481786/meta-fine-facebook-data-leak-ireland-dpc-gdpr">276 million USD</a> for the organization. This isn’t a one-off event; predictions indicate a concerning trajectory for global cybercrime costs; with an expected annual growth of 15 percent, it is estimated to reach a staggering <a href="https://cybersecurityventures.com/cybercrime-damage-costs-10-trillion-by-2025/">10.5 trillion</a> USD by 2025. So, in today’s digital landscape, securing your creations isn’t just a best practice; it’s a mandate. And guess where that journey begins? Spotting and understanding those security gaps.</p><p>This article delves into Foundational CyberSecurity Terminology, Standard Security Testing Approaches, and Tools. It breaks down the meaning behind each term, why it’s crucial in the realm of cybersecurity, and how it functions. Think of it as your guide, offering insights to grasp the essence of these foundational concepts. Ready to embark on this knowledge voyage? Let’s dive in!</p><h3>Foundational CyberSecurity Terminology</h3><p>This section delves into the specifics of four pivotal terms: CVE (Common Vulnerabilities and Exposures), CWE (Common Weakness Enumerations), CVSS (Common Vulnerability Scoring System), and SA (Security Advisories).</p><h4>Common Vulnerabilities and Exposures (CVE)</h4><p><a href="https://cve.mitre.org/">CVE</a> is a database of publicly disclosed <strong>vulnerabilities</strong> in existing software and hardware systems. Each vulnerability is assigned a globally unique CVE ID in the database.</p><p><strong>Why is it required? <br></strong>It provides a standardized naming convention for vulnerabilities, making it easier to share information and coordinate efforts among cybersecurity professionals, researchers, and organizations.</p><p><strong>How does it work? <br></strong>The database is managed by the <a href="https://www.mitre.org/">MITRE Corporation</a>, a non-profit organization, in collaboration with various stakeholders in the cybersecurity community. <a href="https://www.cve.org/ProgramOrganization/CNAs">CVE Numbering Authorities (CNAs)</a> are authorized by the CVE Program to assign CVE IDs to vulnerabilities and publish CVE records.</p><p>Here’s an example of a vulnerability found in Pivotal Concourse (a CI tool) in 2019. <a href="https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-3792">CVE-2019–3792</a> is the CVE ID assigned to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3E2Q8gTnuetmQfe6" /><figcaption>Example: CVE-2019–3792 &lt;<a href="https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-3792">source</a>&gt;</figcaption></figure><h4>Common Weakness Enumerations (CWE)</h4><p><a href="https://cwe.mitre.org/">CWE</a> is a community-developed list of common software and hardware <strong>weaknesses.</strong> It includes weaknesses, such as programming errors, design flaws, configuration issues, architectural vulnerabilities, etc.</p><p><strong>Why is it required? <br></strong>It provides a standardized way of categorizing and describing weaknesses. This makes it easier for organizations and security professionals to understand and address them.</p><p><strong>How does it work? <br></strong>CWE is also maintained by the <a href="https://www.mitre.org/">MITRE Corporation</a>. It is continuously updated and expanded through collaboration with the cybersecurity community (researchers, vendors, organizations). No CNA involvement is required to maintain the CWE list.</p><p><strong>How is it different from CVE?</strong> <strong>Vulnerability</strong> vs <strong>Weakness<br></strong>A <strong>vulnerability </strong>is a specific flaw detected in a particular system’s design, implementation, or configuration that could be exploited to violate that system’s security. A <strong>weakness </strong>is a more general term referring to a characteristic or property of a system that can be exploited for a malicious purpose. It is a broader concept and may encompass many vulnerabilities.</p><p>Here’s an example of a weakness (<a href="https://cwe.mitre.org/data/definitions/89.html">CWE-89</a>, SQL Injection). This weakness can be present in any system. When identified in a particular system, it makes that system vulnerable, thus becoming a vulnerability for that system. So, the <a href="https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-3792">CVE-2019–3792</a> that we saw earlier in Pivotal Concourse software was due to the underlying SQL Injection weakness. You may find vulnerabilities linked to any weakness on the <a href="https://cwe.mitre.org/">CWE website</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZnA4wKLhdx-eIlAEIn3-pQ.png" /><figcaption>Example: CWE-89 &lt;<a href="https://cwe.mitre.org/data/definitions/89.html">source</a>&gt;</figcaption></figure><h4>Common Vulnerability Scoring System (CVSS)</h4><p>CVSS is an open framework for communicating the characteristics and severity of software vulnerabilities. It outputs a numerical score representing the risk level and impact of a vulnerability on a scale from 0 to 10.</p><p><strong>Why is it required? <br></strong>CVSS provides a common language to communicate vulnerability severity consistently. It helps prioritize vulnerability remediation efforts by assisting security teams and stakeholders in making informed decisions about risk mitigation and resource allocation.</p><p><strong>How does it work? <br></strong>The <a href="https://www.first.org/cvss/v4.0/specification-document">CVSS specifications</a> are owned and managed by <a href="https://www.first.org/">FIRST</a>, a US-based non-profit organization. This scoring system comprises four crucial metric groups:</p><p>Base Group: Captures the intrinsic qualities of a vulnerability. This group provides a constant severity score from 0 to 10. It remains consistent over time and across user environments.</p><p>Threat Group:<em> </em>Reflects the evolving characteristics of a vulnerability. This group contributes to the overall severity score. It allows for further refinement based on applicable threat intelligence.</p><p>Environmental Group:<em> </em>The uniqueness of a user’s environment characterizes this group. It tailors the severity score to specific conditions in an individual or organizational setup.</p><p>Supplemental Metrics: While not altering the final score, Supplemental Metrics offer additional insights into the characteristics of a vulnerability.</p><p>A standardized format, the CVSS vector string, compresses the textual representation of the values used to derive the overall score.</p><p>It’s crucial to note that the overall CVSS score for a given vulnerability may differ across systems and organizations. Only the base score remains constant, and centralized vulnerability databases like <a href="https://nvd.nist.gov/">NVD</a> generally display the base score, offering a standardized reference point. To determine the overall CVSS score for a given vulnerability, organizations need to contextualize CVSS metrics within their specific environments and circumstances.</p><p>Here’s an example of the CVSS base score and vector string, for the CVE-2019–3972 that we reviewed above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eh75mLWtWNHOWy4Hlh49Xw.png" /><figcaption>Example CVSS Score — CVE 2019–3792 &lt;<a href="https://nvd.nist.gov/vuln/detail/CVE-2019-3792">source</a>&gt;</figcaption></figure><h4>Security Advisories (SA)</h4><p>Security Advisory is a formal communication or notice issued by a vendor, organization, or security team. It provides information about a security vulnerability or issue in a specific software, hardware, or system.</p><p><strong>Why is it required? <br></strong>Security advisories aim to raise awareness among users about vulnerabilities in the products. It provides guidance on how to address the identified security concern.</p><p><strong>How does it work? <br></strong>The vendor or organization discovers a security vulnerability in the product. Often, a security patch or update is developed to address the issue. Security Advisory is then published to officially notify the users about the vulnerability, available security updates, and guidance on how to proceed to protect their systems.</p><p>Here’s an example of a Security Advisory, released by Pivotal (vendor of Concourse CI) for the CVE-2019–3792 that we reviewed above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UEq3A8uYxMYs8bRq3SArfQ.png" /><figcaption>Example: Security Advisory &lt;<a href="https://pivotal.io/security/cve-2019-3792">source</a>&gt;</figcaption></figure><p>For additional examples, you may review security Advisories published by <a href="https://sec.cloudapps.cisco.com/security/center/publicationListing.x">Cisco</a> and <a href="https://access.redhat.com/security/security-updates/">RedHat</a> for their products.</p><h3>Security Testing Approaches</h3><p>In this section, we unpack key security testing approaches, from Static Application Security Testing (SAST) for early code vulnerability detection to real-world simulations of Dynamic Application Security Testing (DAST) and strategic cyber assaults via Penetration Testing. We’ll explore Software Composition Analysis (SCA) for assessing third-party vulnerabilities, emphasizing the need for a comprehensive approach in the ever-evolving landscape of cybersecurity.</p><h4>Static Application Security Testing (SAST)</h4><p>SAST examines the source code of an application or software without executing it. It aims to identify potential security vulnerabilities, weaknesses, and coding errors early in the development lifecycle.</p><p><strong>Why is it required? <br></strong>Fixing vulnerabilities during development is more cost-effective than dealing with security breaches in production. SAST aids in meeting security standards, regulations, and industry best practices. By finding and fixing vulnerabilities, it helps minimize the risk of cyber threats.</p><p><strong>How does it work? <br></strong>SAST tools use predefined rules to check for known vulnerability patterns, such as SQL injection, Cross-Site Scripting (XSS), and more. It follows the flow of data and control within the code to identify potential data leaks and insecure code paths.</p><p><strong>Is it sufficient? <br></strong>It may miss runtime-related issues. And no real-world simulation is performed in SAST.</p><h4>Dynamic Application Security Testing (DAST)</h4><p>It is a security testing approach that evaluates the security of an application while it’s running. DAST operates as “Black-box” testing, with no access to the application’s internal code and logic.</p><p><strong>Why is it required? <br></strong>DAST simulates real-world attack scenarios, providing insights into how an application might respond to actual exploits. It helps uncover vulnerabilities that may not be apparent from static analysis. It enables testing of web applications / APIs by assessing their security from an external perspective.</p><p><strong>How does it work? <br></strong>DAST involves injection of various inputs, including malicious payloads, into the application to observe how it responds to different scenarios. It analyses responses to identify anomalies, error messages, and potential indications of vulnerabilities.</p><p><strong>Is it sufficient? <br></strong>DAST mainly focuses on testing externally exposed parts of the application and may miss vulnerabilities if test cases don’t adequately cover all possible attacks.</p><h4>Penetration Testing</h4><p>It is a simulated cyber attack conducted by ethical hackers to assess the security of a system, application, or network.</p><p><strong>Why is it required?<br></strong>Penetration Testing is instrumental in discovering vulnerabilities that might go undetected through automated scans. It helps gain insights into the potential impact of successful attacks and their consequences. Penetration testing also aids in evaluating the effectiveness of security controls and measures implemented. It is often mandated by industry regulations and security standards.</p><p><strong>How it works?<br></strong>To begin with, the scope and objectives of the tests (specific targets, permissible actions, etc.) are finalized. The tester then gathers information about the target through publicly available data. Automated tools are used to identify known vulnerabilities in the target. Following that, attempts are made to exploit identified vulnerabilities to gain control over the target. If successful, the tester may attempt to maintain access, escalate privileges, or access sensitive information. In the end, testers compile a detailed report of their findings and mitigation recommendations.</p><p><strong>Is it sufficient?</strong> No standalone approach is sufficient!</p><h4>Software Composition Analysis</h4><p>Identifies and assesses third-party and open-source components used in an application.</p><p><strong>Why is it required? <br></strong>Modern applications heavily rely on third-party libraries and components. These components may contain known vulnerabilities that can be exploited if not patched or updated. Thus it is required to analyse them for vulnerabilities. SCA also helps organizations comply with licensing obligations and legal requirements related to the use of third-party software.</p><p><strong>How does it work? <br></strong>SCA analyses dependencies and creates an inventory of all third-party components used. It then checks the component inventory against known vulnerability databases to identify any security flaws or weaknesses. Assess the licenses of third-party components to ensure compliance with agreements.</p><p><strong>Is it sufficient?<br></strong>The identification is limited to known vulnerabilities. SCA does not analyze the actual source code of third-party components.</p><h4>Other Approaches</h4><p>Some other security testing approaches are as follows,</p><ul><li>Threat Modelling</li><li>Interactive Application Security Testing (IAST)</li><li>Cloud Security Posture Management (CSPM)</li><li>Database Security Scanning</li><li>Fuzz Testing (Fuzzing)</li></ul><p>Feel free to delve deeper into these for an extended understanding of diverse security testing strategies.</p><p>Comprehensive security coverage demands using a combination of various testing approaches tailored to company or product requirements. It strengthens the overall security posture and addresses unique security challenges.</p><h3>Security Testing Tools</h3><p>Embarking on the journey of secure software development requires not only theoretical understanding but also practical implementation. This section delves into the arsenal of security testing tools essential for fortifying your innovative creations.</p><h4>Vulnerability Scanners</h4><p>Vulnerability Scanners are automation tools designed to identify and assess security weaknesses and vulnerabilities in software applications, networks, or systems. They use either a specific testing approach or a combination of approaches (SAST, DAST, etc.) to perform vulnerability scans.</p><p>Some popular vulnerability scanners: <a href="https://www.tenable.com/products/nessus">Tenable Nessus</a>, <a href="https://www.openvas.org/">OpenVAS</a>, <a href="https://www.qualys.com/apps/vulnerability-management-detection-response/">Qualys Vulnerability Management</a></p><figure><img alt="Nessus Scan Results Example" src="https://cdn-images-1.medium.com/max/1024/1*mGkeeqPrGacUjST6AK0ARQ.png" /><figcaption>Nessus Scan Results: Featuring CVE and SA, terms you learned in the article.</figcaption></figure><p>Tools that leverage the <strong>Software Composition Analysis (SCA)</strong> approach to identify vulnerable third-party components also fall in the category of vulnerability scanners.</p><p>Popular SCA-based vulnerability scanners: <a href="https://snyk.io/series/open-source-security/software-composition-analysis-sca/">Synk</a>, <a href="https://www.synopsys.com/software-integrity/software-composition-analysis-tools/black-duck-sca.html">Blackduck</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QU9z5o84hYw1t5FFmndK6w.png" /><figcaption>Synk Software Composition Analysis Report</figcaption></figure><p>With the proliferation of containerized applications, the need to secure these entities becomes paramount. <strong>Container vulnerability scanners</strong> specialize in conducting security assessments focused on identifying known vulnerabilities within the container’s operating system packages, libraries, and dependencies. Scanners analyze the container image’s content without executing it and compare package versions against a vulnerability database to detect potential security risks.</p><p>Popular container vulnerability scanners: <a href="https://trivy.dev/">Trivy</a>, <a href="https://github.com/quay/clair">Clair</a></p><h4>Code Analysers</h4><p>Code review tools analyze source code to identify potential security vulnerabilities, coding flaws, or insecure practices. They are based on the SAST scanning approach.</p><p>Popular Code Analysers: <a href="https://www.sonarsource.com/products/sonarqube/">SonarQube</a>, <a href="https://www.veracode.com/products/binary-static-analysis-sast">Veracode</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6-1j9jvNxpEzTs54W2_3dA.png" /><figcaption>SonarQube Code Analysis: &lt;<a href="https://www.cprime.com/resources/blog/static-analysis-with-sonarqube/">source</a>&gt;</figcaption></figure><h4>Web Application Scanner (WAS)</h4><p>Web Application Vulnerability Scanners are automated tools that scan web applications, generally from the outside, to look for security vulnerabilities such as Cross-site scripting, SQL Injection, Command Injection, Path Traversal, and insecure server configuration. These tools typically use the DAST testing approach.</p><p>Popular Web Application Scanners: <a href="https://www.acunetix.com/">Acunetix</a>, <a href="https://www.rapid7.com/products/insightappsec/">insightAppSec by Rapid7</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tSemBErUXERu_H2C" /><figcaption>insightAppSec Web Application Scan Report</figcaption></figure><h4>Network Scanner</h4><p>Network Scanning tools examine the network infrastructure, including routers, switches, and firewalls, to identify open ports, service vulnerabilities, or potential entry points for attackers.</p><p>Popular Network Scanners: <a href="https://www.openvas.org/">OpenVAS</a>, <a href="https://nmap.org/">Nmap</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VhJW_EmX2rkxr5kiLJwNdQ.png" /><figcaption>Network Vulnerability Scan Sample Report &lt;<a href="https://rhyno.io/wp-content/uploads/2020/01/network-sample-report.pdf">source</a>&gt;</figcaption></figure><h4>Log Analysers</h4><p>These tools monitor and analyze system logs to detect suspicious activities or signs of compromise. They do not directly perform scanning in the traditional sense but rather analyze log data to identify potential security incidents or anomalies. Log Analyzers play a crucial in monitoring and incident response.</p><p>Popular log analysis tools: <a href="https://www.splunk.com/en_us/solutions/security-monitoring.html">Splunk</a>, <a href="https://www.datadoghq.com/monitoring/security-monitoring-tools/#:~:text=Datadog%20Security%20Monitoring%20gives%20visibility,identify%20threats%20and%20reduce%20risks.">Datadog</a></p><p>This brings us to the conclusion of our journey through the intricacies of security testing foundations.</p><p>I extend my heartfelt gratitude for your time and engagement in this exploration. I hope that the knowledge gained here serves as a robust foundation for your endeavors in crafting and maintaining secure software systems.</p><p>If you found this article helpful, have questions, or would like to share your insights, please feel free to leave your comments below. For more updates, articles, and discussions on software development, follow <a href="https://medium.com/u/b01a5a9a6b24">Aman Saraiya</a> and connect with me on <a href="https://www.linkedin.com/in/amansaraiya/">LinkedIn</a>.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d6bcacd3340" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>