<?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 Barkhayot on Medium]]></title>
        <description><![CDATA[Stories by Barkhayot on Medium]]></description>
        <link>https://medium.com/@coderviewer?source=rss-fbf123eb43a0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*XV1bBdKG5TnAKkWF</url>
            <title>Stories by Barkhayot on Medium</title>
            <link>https://medium.com/@coderviewer?source=rss-fbf123eb43a0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 02:24:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@coderviewer/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[How to simply detect and fix memory leaks in Go with pprof?]]></title>
            <link>https://medium.com/@coderviewer/how-to-simply-detect-and-fix-memory-leaks-in-go-with-pprof-50db917b657b?source=rss-fbf123eb43a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/50db917b657b</guid>
            <category><![CDATA[memory-leak]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[pprof]]></category>
            <dc:creator><![CDATA[Barkhayot]]></dc:creator>
            <pubDate>Sun, 03 Nov 2024 04:17:55 GMT</pubDate>
            <atom:updated>2024-11-03T04:17:55.537Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZU80HIfG6GedftSXjo2kew.png" /></figure><p>Memory leaks can be challenging, even in languages like Go that have automatic garbage collection. If memory usage grows unchecked over time, your application may experience slowdowns or even crashes. This article will guide you through using pprof for detecting memory leaks in Go, along with the top and list commands for deeper analysis.</p><h4>Why Memory Leaks Happen in Go</h4><p>Although Go’s garbage collector handles memory management, memory leaks can still occur due to:</p><ul><li>Long-lived goroutines that aren’t terminated properly.</li><li>Accumulated objects that aren’t referenced but aren’t garbage-collected due to lingering references.</li><li>Mismanaged resources (e.g., opened files or network connections) that aren’t released.</li></ul><p>By profiling your application with pprof, you can identify memory leaks and ensure your application runs smoothly.</p><h4>Setting Up pprof in Your Go Application</h4><p>To start, add the pprof package to your Go application and expose it via an HTTP server:</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;net/http&quot;<br> _ &quot;net/http/pprof&quot;<br> &quot;time&quot;<br>)<br><br>func main() {<br> // Start pprof server<br> go func() {<br>  fmt.Println(&quot;Starting pprof server on :6060&quot;)<br>  http.ListenAndServe(&quot;localhost:6060&quot;, nil)<br> }()<br><br> // Simulate a memory leak<br> for i := 0; i &lt; 10; i++ {<br>  go leakyFunction()<br> }<br><br> // Keep the main goroutine running<br> select {}<br>}<br><br>func leakyFunction() {<br> // A goroutine that never exits, causing a memory leak<br> ticker := time.NewTicker(time.Second)<br> defer ticker.Stop()<br><br> for range ticker.C {<br>  fmt.Println(&quot;Running...&quot;)<br>  // This keeps the goroutine alive indefinitely<br> }<br>}</pre><p>In this code, leakyFunction is intentionally designed to leak memory by creating a ticker that never stops, leading to a goroutine leak. This example will help us see how to detect the issue using pprof.</p><h4>Detecting the Memory Leak with pprof</h4><p>Once the application is running, follow these steps to diagnose the memory leak:</p><ol><li><strong>Generate a Memory Profile:</strong> Open a terminal and run:</li></ol><pre>go tool pprof http://localhost:6060/debug/pprof/heap</pre><p>This command opens an interactive pprof shell where you can analyze memory usage.</p><p>2. <strong>Use the </strong><strong>top Command:</strong> In the pprof shell, type:</p><pre>(pprof) top</pre><p>This displays a list of functions sorted by memory consumption. In this case, you should see leakyFunction or similar consuming significant memory, indicating a problem.</p><p>3. <strong>Inspect with the </strong><strong>list Command:</strong> To narrow down the specific memory-consuming lines within leakyFunction, type:</p><pre>(pprof) list leakyFunctionbash</pre><p>This command shows line-by-line memory usage within leakyFunction, allowing you to pinpoint where the memory leak originates.</p><p>The output should highlight that leakyFunction is responsible for high memory usage due to the goroutine leak.</p><h4>Fixing the Memory Leak</h4><p>In this example, the leak occurs because the goroutine in leakyFunction never exits. To fix this, we’ll add an exit condition to ensure the goroutine stops after a certain time.</p><h4>Updated Code with a Fix</h4><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;net/http&quot;<br> _ &quot;net/http/pprof&quot;<br> &quot;time&quot;<br>)<br><br>func main() {<br> // Start pprof server<br> go func() {<br>  fmt.Println(&quot;Starting pprof server on :6060&quot;)<br>  http.ListenAndServe(&quot;localhost:6060&quot;, nil)<br> }()<br><br> // Run the fixed function<br> for i := 0; i &lt; 10; i++ {<br>  go fixedFunction()<br> }<br><br> // Keep the main goroutine running<br> select {}<br>}<br><br>func fixedFunction() {<br> // This function now has an exit condition<br> ticker := time.NewTicker(time.Second)<br> defer ticker.Stop()<br><br> timeout := time.After(5 * time.Second)<br><br> for {<br>  select {<br>  case &lt;-ticker.C:<br>   fmt.Println(&quot;Running...&quot;)<br>  case &lt;-timeout:<br>   fmt.Println(&quot;Exiting goroutine to prevent memory leak&quot;)<br>   return // Exit the goroutine after 5 seconds<br>  }<br> }<br>}</pre><p>Now, fixedFunction exits after 5 seconds, stopping the ticker and preventing the goroutine from consuming memory indefinitely.</p><h4>Verifying the Fix with pprof</h4><ol><li>Restart the application with the updated code.</li><li>Run go tool pprof http://localhost:6060/debug/pprof/heap again.</li><li>Use top and list to inspect memory usage.</li></ol><p>After applying the fix, the memory profile should show reduced memory usage, with fixedFunction no longer consuming excessive resources.</p><h4>Conclusion</h4><p>Detecting and fixing memory leaks is essential to maintaining a high-performance Go application. With tools like pprof, top, and list, you can pinpoint memory issues and resolve them efficiently. Remember to add exit conditions to your goroutines, release resources, and monitor memory profiles regularly to avoid common memory leak pitfalls in Go.</p><p>Happy coding! 🙌</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50db917b657b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing ClickHouse Connections in Go]]></title>
            <link>https://medium.com/@coderviewer/optimizing-clickhouse-connections-in-go-c045c51d20bb?source=rss-fbf123eb43a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c045c51d20bb</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[clickhouse]]></category>
            <category><![CDATA[connection]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Barkhayot]]></dc:creator>
            <pubDate>Wed, 26 Jun 2024 15:27:23 GMT</pubDate>
            <atom:updated>2024-06-26T15:27:23.935Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o0ZBRby89w7pFaJYt7cDmw.png" /></figure><p>ClickHouse is a powerful columnar database management system well-suited for real-time analytics. When using ClickHouse with Go, managing database connections efficiently is crucial for optimal performance. In this post, we’ll explore the difference between using WithReleaseConnection and not using it when handling ClickHouse connections in Go, specifically in the context of preparing batches.</p><h4>Understanding ClickHouse Connections in Go</h4><p>In Go, we often use the github.com/ClickHouse/clickhouse-go library to interact with ClickHouse. This library provides various ways to manage connections to the database. Two common methods include:</p><ol><li>Without<strong> </strong><strong>WithReleaseConnection</strong></li><li>With<strong> </strong><strong>WithReleaseConnection</strong></li></ol><p>Let’s delve into the details of each method.</p><p>When you establish a connection without WithReleaseConnection, you directly use the connection object to execute queries and prepare batches. Here’s a simple example:</p><pre>package main<br><br>import (<br>    &quot;context&quot;<br>    &quot;database/sql&quot;<br>    &quot;fmt&quot;<br>    &quot;github.com/ClickHouse/clickhouse-go/v2&quot;<br>    &quot;time&quot;<br>)<br><br>func main() {<br>    connect, err := clickhouse.Open(&amp;clickhouse.Options{<br>        Addr: []string{&quot;host:port&quot;},<br>        Auth: clickhouse.Auth{<br>            Database: &quot;db&quot;,<br>            Username: &quot;user&quot;,<br>            Password: &quot;pass&quot;,<br>        },<br>        DialTimeout: 5 * time.Second,<br>        ConnMaxLifetime: time.Hour,<br>        ConnOpenStrategy: clickhouse.ConnOpenRoundRobin,<br>    })<br>    if err != nil {<br>        fmt.Println(&quot;Error connecting:&quot;, err)<br>        return<br>    }<br><br>    ctx := context.Background()<br>    batch, err := connect.PrepareBatch(ctx, &quot;INSERT INTO table (column1, column2)&quot;)<br>    if err != nil {<br>        fmt.Println(&quot;Prepare batch error:&quot;, err)<br>        return<br>    }<br><br>    for i := 0; i &lt; 10; i++ {<br>        if err := batch.Append(i, fmt.Sprintf(&quot;value %d&quot;, i)); err != nil {<br>            fmt.Println(&quot;Append error:&quot;, err)<br>            return<br>        }<br>    }<br><br>    if err := batch.Send(); err != nil {<br>        fmt.Println(&quot;Send error:&quot;, err)<br>        return<br>    }<br><br>    defer connect.Close()<br>}</pre><p>Pros:</p><ul><li><strong>Simplicity:</strong> Easy to implement and understand.</li><li><strong>Direct Control:</strong> You have direct control over the connection and its lifecycle.</li></ul><p>Cons:</p><ul><li><strong>Resource Intensive:</strong> Each connection remains open until explicitly closed, which can lead to resource exhaustion if not managed properly.</li><li><strong>Scalability Issues:</strong> Not ideal for high-concurrency scenarios as each connection consumes resources.</li></ul><h4>With WithReleaseConnection</h4><p>WithReleaseConnection is an optional parameter for the PrepareBatch function. This parameter ensures that the connection is released back to the pool after the batch operation is completed, making it available for other operations.</p><p>Here’s how you can use WithReleaseConnection:</p><pre>package main<br><br>import (<br>    &quot;context&quot;<br>    &quot;database/sql&quot;<br>    &quot;fmt&quot;<br>    &quot;github.com/ClickHouse/clickhouse-go/v2&quot;<br>    &quot;github.com/ClickHouse/clickhouse-go/v2/lib/driver&quot;<br>    &quot;time&quot;<br>)<br><br>func main() {<br>    connect, err := clickhouse.Open(&amp;clickhouse.Options{<br>        Addr: []string{&quot;host:port&quot;},<br>        Auth: clickhouse.Auth{<br>            Database: &quot;db&quot;,<br>            Username: &quot;user&quot;,<br>            Password: &quot;pass&quot;,<br>        },<br>        DialTimeout: 5 * time.Second,<br>        ConnMaxLifetime: time.Hour,<br>        ConnOpenStrategy: clickhouse.ConnOpenRoundRobin,<br>    })<br>    if err != nil {<br>        fmt.Println(&quot;Error connecting:&quot;, err)<br>        return<br>    }<br><br>    ctx := context.Background()<br>    batch, err := connect.PrepareBatch(ctx, &quot;INSERT INTO table (column1, column2)&quot;, clickhouse.WithReleaseConnection())<br>    if err != nil {<br>        fmt.Println(&quot;Prepare batch error:&quot;, err)<br>        return<br>    }<br><br>    for i := 0; i &lt; 10; i++ {<br>        if err := batch.Append(i, fmt.Sprintf(&quot;value %d&quot;, i)); err != nil {<br>            fmt.Println(&quot;Append error:&quot;, err)<br>            return<br>        }<br>    }<br><br>    if err := batch.Send(); err != nil {<br>        fmt.Println(&quot;Send error:&quot;, err)<br>        return<br>    }<br><br>    // Connection is released back to the pool after batch.Send()<br>}</pre><p>Pros:</p><ul><li><strong>Efficient Resource Usage:</strong> Connections are promptly released back to the pool after use, ensuring they are reused efficiently.</li><li><strong>Scalability:</strong> Better suited for high-concurrency environments as it allows for more efficient connection reuse.</li></ul><p>Cons:</p><ul><li><strong>Complexity:</strong> Slightly more complex to implement, as it requires managing the connection lifecycle more explicitly.</li><li><strong>Potential Latency:</strong> There might be a slight overhead in releasing and re-acquiring connections.</li></ul><h4>When to Use Each Method</h4><ul><li><strong>High-Concurrency Applications:</strong> If your application requires handling many concurrent requests, using WithReleaseConnection is highly recommended to avoid resource exhaustion and ensure better scalability.</li><li><strong>Simple or Low-Load Applications:</strong> For simpler applications with low concurrency, managing connections without WithReleaseConnection might suffice and keep your code simpler.</li></ul><h4>Conclusion</h4><p>Choosing the right method to manage ClickHouse connections in Go can have a significant impact on your application’s performance and scalability. WithReleaseConnection offers efficient resource utilization and better scalability for high-concurrency environments, while managing connections without it can be simpler for low-load scenarios. Assess your application&#39;s needs and choose the method that best aligns with your performance and complexity requirements.</p><p>Happy coding! 🙌</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c045c51d20bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Flask API Gateway for gRPC Microservices: A Practical Guide]]></title>
            <link>https://medium.com/@coderviewer/building-a-flask-api-gateway-for-grpc-microservices-a-practical-guide-f912aed73b94?source=rss-fbf123eb43a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f912aed73b94</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Barkhayot]]></dc:creator>
            <pubDate>Thu, 11 Jan 2024 05:43:25 GMT</pubDate>
            <atom:updated>2024-01-11T05:43:25.794Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A5yq3qYmGLb49QEZ9LIfmw.png" /></figure><p>In this post, we’ll explore the process of creating a simple Flask API Gateway to interact with gRPC microservices. Our goal is to build a basic RESTful API using Flask, serving as a client to a gRPC service responsible for fetching book data.</p><h3>Why Use an API Gateway?</h3><p>An API Gateway acts as an intermediary between frontend applications (in this case, a React app) and backend microservices. It simplifies communication, handles common concerns like authentication, and provides a unified interface to the client.</p><h3>Setting Up the gRPC Service</h3><h4>1. Define the gRPC Service</h4><p>We start by defining a gRPC service using Protocol Buffers in a file called books.proto. This service, named BookService, has a single method GetBooks for fetching a list of books.</p><pre># books.proto<br><br>syntax = &quot;proto3&quot;;<br><br>package bookstore;<br><br>service BookService {<br>  rpc GetBooks (GetBooksRequest) returns (GetBooksResponse);<br>}<br><br>message GetBooksRequest {<br>}<br><br>message GetBooksResponse {<br>  repeated Book books = 1;<br>}<br><br>message Book {<br>  string id = 1;<br>  string title = 2;<br>  string author = 3;<br>}</pre><h4>2. Generate gRPC Code</h4><p>Use the grpc_tools.protoc command to generate the Python code from the books.proto file.</p><pre>python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. books.proto</pre><h4>3. Implement the gRPC Service</h4><p>Create a Python file, books_server.py, to implement the gRPC service. We simulate fetching books from a database or external service.</p><pre># books_server.py<br><br>import grpc<br>from concurrent import futures<br>import books_pb2<br>import books_pb2_grpc<br><br>class BookService(books_pb2_grpc.BookServiceServicer):<br>    def GetBooks(self, request, context):<br>        # Simulate fetching books from a database or external service<br>        books = [<br>            books_pb2.Book(id=&quot;1&quot;, title=&quot;Book 1&quot;, author=&quot;Author 1&quot;),<br>            books_pb2.Book(id=&quot;2&quot;, title=&quot;Book 2&quot;, author=&quot;Author 2&quot;),<br>            # Add more books as needed<br>        ]<br><br>        return books_pb2.GetBooksResponse(books=books)<br><br>def serve():<br>    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))<br>    books_pb2_grpc.add_BookServiceServicer_to_server(BookService(), server)<br>    server.add_insecure_port(&#39;[::]:50051&#39;)<br>    server.start()<br>    print(&quot;gRPC Server started. Listening on port 50051...&quot;)<br>    try:<br>        while True:<br>            pass<br>    except KeyboardInterrupt:<br>        server.stop(0)<br><br>if __name__ == &#39;__main__&#39;:<br>    serve()</pre><h3>Building the Flask API Gateway</h3><h4>1. Implement the Flask App</h4><p>Now, let’s create a Flask app, app.py, that serves as an API Gateway. This app exposes a /api/books endpoint, making a gRPC call to fetch books.</p><pre># app.py<br><br>from flask import Flask, jsonify<br>import grpc<br>import books_pb2<br>import books_pb2_grpc<br><br>app = Flask(__name__)<br><br>@app.route(&#39;/api/books&#39;, methods=[&#39;GET&#39;])<br>def get_books():<br>    try:<br>        # Make gRPC call to the BookService<br>        with grpc.insecure_channel(&#39;localhost:50051&#39;) as channel:<br>            stub = books_pb2_grpc.BookServiceStub(channel)<br>            grpc_request = books_pb2.GetBooksRequest()<br>            grpc_response = stub.GetBooks(grpc_request)<br><br>        # Process gRPC response and return to the Flask app<br>        books_data = [{&#39;id&#39;: book.id, &#39;title&#39;: book.title, &#39;author&#39;: book.author} for book in grpc_response.books]<br>        return jsonify({&#39;books&#39;: books_data})<br>    except Exception as e:<br>        return jsonify({&#39;message&#39;: f&quot;Error: {e}&quot;})<br>if __name__ == &#39;__main__&#39;:<br>    app.run(debug=True)</pre><h4>2. Run the Servers</h4><p>Run both the gRPC server and the Flask app in separate terminals.</p><pre># Terminal 1<br>python books_server.py</pre><pre># Terminal 2<br>python app.py</pre><h3>Conclusion</h3><p>In this post, we’ve built a simple Flask API Gateway that serves as a client to a gRPC microservice responsible for fetching book data. This architecture provides flexibility, allowing for future expansion of microservices while presenting a consistent API to the client.</p><p>Source code : <a href="https://github.com/barkhayot/flask-grpc">https://github.com/barkhayot/flask-grpc</a></p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f912aed73b94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Usage of gRPC with Python]]></title>
            <link>https://medium.com/@coderviewer/simple-usage-of-grpc-with-python-f714d9f69daa?source=rss-fbf123eb43a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f714d9f69daa</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Barkhayot]]></dc:creator>
            <pubDate>Fri, 29 Dec 2023 07:56:12 GMT</pubDate>
            <atom:updated>2023-12-29T07:56:12.294Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tC-hsHfPitxZyuL_ilpKzQ.png" /></figure><h3>Introduction</h3><p>gRPC (gRPC Remote Procedure Calls) is an open-source framework developed by Google that facilitates communication between distributed systems by defining and implementing efficient and extensible RPC (Remote Procedure Call) APIs. In this blog post, we’ll explore a simple example of using gRPC with Python to create a basic client-server application.</p><h3>Setting Up</h3><p>Before we dive into the code, make sure you have the necessary tools installed</p><pre>pip install grpcio grpcio-tools</pre><h3>Defining the Service</h3><p>The first step is to define the service using Protocol Buffers (protobuf). Create a file named calculator.proto with the following content:</p><pre>syntax = &quot;proto3&quot;;<br><br>package calculator;<br><br>service Calculator {<br>  rpc Add (AddRequest) returns (AddResponse);<br>}<br><br>message AddRequest {<br>  int32 num1 = 1;<br>  int32 num2 = 2;<br>}<br><br>message AddResponse {<br>  int32 result = 1;<br>}</pre><h3>Generating gRPC Files</h3><p>Run the following commands to generate the gRPC files:</p><pre>python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. calculator.proto</pre><p>This will generate calculator_pb2.py and calculator_pb2_grpc.py.</p><h3>Implementing the Server</h3><p>Create a file named server.py:</p><pre>import grpc<br>from concurrent import futures<br>import calculator_pb2<br>import calculator_pb2_grpc<br><br>class CalculatorServicer(calculator_pb2_grpc.CalculatorServicer):<br>    def Add(self, request, context):<br>        result = request.num1 + request.num2<br>        return calculator_pb2.AddResponse(result=result)<br><br>def serve():<br>    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))<br>    calculator_pb2_grpc.add_CalculatorServicer_to_server(CalculatorServicer(), server)<br>    server.add_insecure_port(&#39;[::]:50051&#39;)<br>    server.start()<br>    server.wait_for_termination()<br><br>if __name__ == &#39;__main__&#39;:<br>    serve()</pre><h3>Implementing the Client</h3><p>Create a file named client.py:</p><pre>import grpc<br>import calculator_pb2<br>import calculator_pb2_grpc<br><br>def run(num1, num2):<br>    with grpc.insecure_channel(&#39;localhost:50051&#39;) as channel:<br>        stub = calculator_pb2_grpc.CalculatorStub(channel)<br>        response = stub.Add(calculator_pb2.AddRequest(num1=num1, num2=num2))<br>    print(f&quot;Result: {response.result}&quot;)<br><br>if __name__ == &#39;__main__&#39;:<br>    # Get user Input <br>    num1 = int(input(&quot;Please input num1: &quot;))<br>    num2 = int(input(&quot;Please input num2: &quot;))<br>    run(num1, num2)</pre><h3>Running the Server and Client</h3><p>In one terminal, run the server:</p><pre>python server.py</pre><p>In another terminal, run the client:</p><pre>python client.py</pre><p>You should see the result of adding 10 and 20 printed by the client.</p><h3>Conclusion</h3><p>This example demonstrates a basic usage of gRPC with Python for building a simple client-server application. gRPC provides a powerful and efficient way to define and implement APIs for communication between distributed systems. Explore further to discover more features and use cases for gRPC in your projects.</p><p>Feel free to experiment with additional gRPC features, error handling, and security options to enhance your understanding of this versatile framework. The official gRPC documentation is an excellent resource for diving deeper into advanced topics and best practices.</p><p>Source code : <a href="https://github.com/barkhayot/grpc-python-example">https://github.com/barkhayot/grpc-python-example</a></p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f714d9f69daa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying gRPC: A Comprehensive Guide to High-Performance APIs]]></title>
            <link>https://medium.com/@coderviewer/demystifying-grpc-a-comprehensive-guide-to-high-performance-apis-30929fdbddcc?source=rss-fbf123eb43a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/30929fdbddcc</guid>
            <category><![CDATA[rpc]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[grpc]]></category>
            <dc:creator><![CDATA[Barkhayot]]></dc:creator>
            <pubDate>Wed, 27 Dec 2023 14:01:37 GMT</pubDate>
            <atom:updated>2023-12-27T14:01:37.172Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*eRPtudjPTApDPk9GocN4Bw.png" /><figcaption>Image from Medium</figcaption></figure><p>In the realm of modern software development, the quest for efficient and scalable communication between services has led to the rise of various technologies. Among them, gRPC (gRPC Remote Procedure Call) has emerged as a powerful framework for building high-performance APIs. In this blog post, we’ll delve into the world of gRPC, exploring its core concepts, features, and advantages.</p><h3>What is gRPC?</h3><p>gRPC is an open-source RPC (Remote Procedure Call) framework developed by Google. Unlike traditional HTTP-based APIs, gRPC enables communication between services using a protocol called Protocol Buffers (protobuf) for serialization. This binary serialization offers advantages in terms of efficiency, making gRPC a compelling choice for scenarios where low latency and high performance are critical.</p><h3>Core Concepts</h3><h4>1. Protocol Buffers (protobuf):</h4><p>At the heart of gRPC is Protocol Buffers, a language-agnostic binary serialization format. With protobuf, you define the structure of your data using a simple language, and gRPC takes care of the serialization and deserialization process. This results in a more compact and efficient representation of data compared to traditional text-based formats like JSON.</p><h4>2. Service Definition:</h4><p>gRPC uses a service definition language to define the methods that can be called remotely, along with their parameters and return types. These definitions are specified in a .proto file using Protocol Buffers syntax.</p><h4>3. IDL (Interface Definition Language):</h4><p>The Interface Definition Language in gRPC allows developers to define the methods and data structures that will be used in the API. This ensures a clear and agreed-upon contract between the client and server.</p><h3>Key Features of gRPC</h3><h4>1. HTTP/2 Protocol:</h4><p>gRPC utilizes the HTTP/2 protocol, bringing several advantages such as multiplexing, header compression, and support for bidirectional streaming. This results in reduced latency and improved efficiency, especially in scenarios where multiple requests need to be handled concurrently.</p><h4>2. Bidirectional Streaming:</h4><p>Unlike traditional REST APIs, gRPC supports bidirectional streaming, allowing both the client and server to send a stream of messages. This is particularly useful for real-time applications, where updates need to flow seamlessly between the client and server.</p><h4>3. Code Generation:</h4><p>gRPC offers automatic code generation based on the service definition. This results in the creation of client and server code in various programming languages, simplifying the development process and ensuring consistency between services.</p><h3>When to Choose gRPC?</h3><h4>1. Microservices Architecture:</h4><p>gRPC is well-suited for microservices architectures, where efficient communication between services is crucial. Its support for bidirectional streaming and binary serialization makes it a natural choice for building responsive and scalable microservices.</p><h4>2. Real-time Applications:</h4><p>In applications requiring real-time updates or interactive communication, gRPC’s bidirectional streaming capabilities shine. This makes it ideal for scenarios like chat applications, live dashboards, and collaborative tools.</p><h4>3. Efficiency and Performance:</h4><p>If your project demands low latency, reduced bandwidth usage, and high performance, gRPC is a strong contender. Its use of binary serialization and the HTTP/2 protocol contributes to a more efficient communication process compared to traditional REST APIs.</p><h3>Getting Started with gRPC</h3><h4>1. Installation:</h4><p>To get started with gRPC, you’ll need to install the necessary tools and libraries. The official gRPC documentation provides comprehensive guides for different programming languages.</p><h4>2. Define Your Service:</h4><p>Create a .proto file to define your service and data structures using Protocol Buffers syntax. This file serves as the contract between the client and server.</p><h4>3. Generate Code:</h4><p>Use the gRPC tools to generate client and server code based on your .proto file. This step automates much of the boilerplate code required for communication.</p><h4>4. Implement Your Service:</h4><p>Write the actual implementation of your gRPC service, both on the client and server sides. Use the generated code as a starting point and focus on the business logic of your application.</p><h4>5. Run and Test:</h4><p>Run your gRPC service and test the communication between the client and server. Use tools like grpcurl for manual testing and debugging.</p><h3>Conclusion</h3><p>gRPC stands as a robust solution for building high-performance APIs, offering advantages in terms of efficiency, scalability, and real-time communication. As you embark on your journey with gRPC, consider the specific requirements of your project and weigh the benefits of binary serialization, bidirectional streaming, and automatic code generation.</p><p>Whether you’re diving into microservices architecture, developing real-time applications, or simply seeking improved performance, gRPC has the potential to elevate your API communication to new heights. Explore the vast capabilities of gRPC and empower your applications with seamless and efficient service-to-service communication.</p><p>Happy coding with gRPC!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30929fdbddcc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking Efficiency: Why gRPC Might Be Your Next API Choice Over REST]]></title>
            <link>https://medium.com/@coderviewer/unlocking-efficiency-why-grpc-might-be-your-next-api-choice-over-rest-4a3b2ad06390?source=rss-fbf123eb43a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a3b2ad06390</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Barkhayot]]></dc:creator>
            <pubDate>Mon, 25 Dec 2023 04:37:13 GMT</pubDate>
            <atom:updated>2023-12-25T04:37:13.289Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WLI4W_Xf8TwCJ93m_fePBw.jpeg" /><figcaption>Image from Postman</figcaption></figure><p>In the ever-evolving landscape of software development, choosing the right communication protocol for your APIs is crucial. Among the contenders, REST (Representational State Transfer) has long been the go-to choice. However, a formidable challenger has emerged in recent years — gRPC (gRPC Remote Procedure Call). In this blog post, we’ll delve into the reasons why gRPC might be a superior choice compared to REST.</p><h3>Understanding REST APIs</h3><p>REST, with its principles of statelessness, resources, and a uniform interface, has become a cornerstone of web development. Its simplicity and scalability have made it widely adopted across industries, fostering interoperability between various systems. RESTful APIs communicate over standard HTTP methods, typically using JSON for data serialization.</p><h3>Introducing gRPC</h3><p>On the other side of the spectrum is gRPC, a high-performance, open-source RPC framework. gRPC stands out by leveraging Protocol Buffers as its interface definition language (IDL), providing efficient binary serialization for communication. Unlike REST, which relies on text-based serialization like JSON, gRPC uses the HTTP/2 protocol to offer features such as multiplexing, header compression, and asynchronous communication.</p><h3>Key Differences Between gRPC and REST</h3><h4>Serialization</h4><p>One of the primary distinctions lies in serialization. While REST APIs commonly use JSON for data interchange, gRPC opts for Protocol Buffers. This binary serialization not only reduces payload size but also enhances parsing speed, contributing to overall performance gains.</p><h4>HTTP/2 Protocol</h4><p>gRPC’s use of the HTTP/2 protocol introduces advanced features like multiplexing, allowing multiple messages to be sent concurrently over a single connection. This results in reduced latency and improved bandwidth efficiency compared to the traditional request-response model of REST over HTTP/1.1.</p><h4>Bidirectional Streaming</h4><p>gRPC supports bidirectional streaming, a feature not inherently present in REST. This allows for a more dynamic and interactive communication pattern, where both the client and server can send a stream of messages. This capability proves valuable in scenarios such as real-time updates and chat applications.</p><h4>Strong Typing</h4><p>With gRPC, strong typing is enforced through Protocol Buffers. This not only leads to more predictable and maintainable code but also reduces the likelihood of runtime errors, a common concern in dynamically typed languages often associated with REST APIs.</p><h3>Performance Considerations</h3><p>In the realm of performance, gRPC excels in multiple aspects.</p><h4>Latency and Bandwidth Efficiency</h4><p>The combination of binary serialization and the HTTP/2 protocol makes gRPC inherently more efficient in terms of both latency and bandwidth. This is particularly advantageous in scenarios where minimizing data transfer time is critical.</p><h4>Code Generation</h4><p>gRPC’s use of Protocol Buffers extends beyond just serialization; it enables code generation. This feature simplifies the development process by automatically creating client and server code, reducing boilerplate and ensuring a consistent interface between services.</p><h3>Use Cases for gRPC</h3><h4>Microservices Architecture</h4><p>For projects embracing a microservices architecture, gRPC’s efficiency and support for bidirectional streaming make it a natural fit. The ability to establish real-time, dynamic communication between microservices enhances the overall responsiveness of the system.</p><h4>Real-time Applications</h4><p>In applications requiring real-time updates, such as collaborative tools or live dashboards, gRPC’s bidirectional streaming capabilities shine. REST, with its request-response model, may introduce additional latency, making gRPC a preferred choice for such use cases.</p><h3>Challenges and Considerations</h3><p>While gRPC presents compelling advantages, it’s essential to acknowledge potential challenges.</p><h4>Learning Curve</h4><p>Adopting gRPC may entail a learning curve, especially for teams accustomed to the simplicity of REST. However, the benefits in terms of performance and maintainability can outweigh the initial challenges.</p><h4>Tooling and Ecosystem</h4><p>REST boasts a mature and well-established ecosystem, whereas gRPC’s ecosystem is still evolving. Teams considering the transition should evaluate the available tooling and community support to ensure a smooth integration.</p><h3>Conclusion</h3><p>In conclusion, the choice between gRPC and REST hinges on the specific requirements of your project. REST, with its simplicity and widespread adoption, remains a robust choice for many scenarios. However, as the need for efficiency and real-time communication grows, gRPC emerges as a powerful alternative. By understanding the strengths and considerations of each approach, you can make an informed decision that aligns with your project’s goals.</p><p>Remember, there’s no one-size-fits-all solution. Whether you stick with the familiarity of REST or venture into the efficiency of gRPC, the key is to choose the right tool for the job.</p><p>Happy Coding !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a3b2ad06390" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Crucial Role of Planning in Software Development]]></title>
            <link>https://medium.com/@coderviewer/the-crucial-role-of-planning-in-software-development-2027f0f9d3f8?source=rss-fbf123eb43a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2027f0f9d3f8</guid>
            <category><![CDATA[planning]]></category>
            <category><![CDATA[time-management]]></category>
            <category><![CDATA[management]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Barkhayot]]></dc:creator>
            <pubDate>Tue, 19 Sep 2023 12:55:31 GMT</pubDate>
            <atom:updated>2023-09-19T12:55:31.097Z</atom:updated>
            <content:encoded><![CDATA[<p>In the fast-paced world of software development, the adage “fail to plan, plan to fail” holds truer than ever. As a project manager navigating the intricacies of a new team, you’ve likely felt the impact of poor planning firsthand. It’s no secret that efficient and well-thought-out planning is the cornerstone of successful software development. Let’s delve into why planning is paramount and how it can make or break your development journey.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*ntWvZwDXlSA_p1CIbJSymA.jpeg" /></figure><h3>The Need for a Clear Software Strategy</h3><p>Building a Minimum Viable Product (MVP) that is not only functional but also clean and efficient requires a well-defined software strategy. This strategy serves as the guiding light for your development team, ensuring that every step is aligned with the overarching goal.</p><p>As a project manager, your responsibility is to meticulously craft this strategy. It’s not just about outlining the features and functionalities; it’s about articulating the vision, setting clear objectives, and defining the scope. The frontend and backend teams must have a crystal-clear understanding of what they are building and why.</p><h3>Bridging the Gap Between Business Logic and Digital Logic</h3><p>The heart of any software project lies in the translation of business logic into digital logic. Here, the role of the project manager becomes crucial. You are the bridge between the business stakeholders and the technical teams. Your ability to convey clean, well-structured business logic to your development teams is paramount.</p><p>Without a solid grasp of the business logic, the backend team might falter in creating efficient digital solutions. When the translation is muddled, it can lead to confusion, misdirection, and, ultimately, inefficient code. This not only hampers productivity but also jeopardizes the quality of the final product.</p><h3>The Cost of Mistakes in Planning</h3><p>Mistakes during the planning phase can be costly in more ways than one. Each misstep can lead to a chain reaction of problems down the line, resulting in lost time, increased frustration, and, of course, financial implications. Here’s why getting planning right the first time matters:</p><p>1. <strong>Time</strong>: Poor planning often results in frequent changes and revisions during development, leading to project delays.</p><p>2. <strong>Frustration</strong>: Team morale can suffer when the team has to constantly adapt to shifting requirements or unclear objectives.</p><p>3. <strong>Patience</strong>: In an environment marked by continuous changes and confusion, patience can wear thin, affecting both team dynamics and the quality of work.</p><p>4. <strong>Money</strong>: Ultimately, ineffective planning can result in budget overruns, as the project takes longer to complete than originally anticipated.</p><h3>The Path Forward</h3><p>To overcome these challenges, project managers must prioritize meticulous planning. Here are some key steps to ensure a successful planning process:</p><ul><li><strong>Clear Communication: </strong><em>Ensure open and transparent communication between business stakeholders and development teams to avoid misunderstandings.</em></li><li><strong>Thorough Requirements: </strong><em>Invest time in gathering and documenting detailed project requirements, leaving no room for ambiguity.</em></li><li><strong>Alignment: </strong><em>Regularly assess the project’s progress to ensure it aligns with the initial strategy and objectives.</em></li><li><strong>Flexibility: </strong><em>While planning is vital, be prepared to adapt when necessary. Agile methodologies can help manage change effectively.</em></li><li><strong>Continuous Improvement: </strong><em>Learn from past projects and continuously refine your planning processes to avoid repeating mistakes.</em></li></ul><p>In conclusion, the importance of planning in software development cannot be overstated. It is the foundation upon which successful projects are built. As a project manager, your role in crafting a clear, efficient, and productive plan is pivotal. By avoiding common mistakes and embracing best practices in planning, you can mitigate risks, save time, maintain team morale, and ultimately deliver a high-quality software product.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2027f0f9d3f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>