<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ gRPC - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ gRPC - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Thu, 23 Jul 2026 04:01:26 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/grpc/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ From RPC to gRPC: Understanding Remote Procedure Calls, Protocol Buffers, and Modern Distributed Systems Communication  ]]>
                </title>
                <description>
                    <![CDATA[ Every application, at some point, needs to talk to another system. A mobile app talks to a backend. A backend service talks to a payment gateway. An authentication service talks to a user service. A d ]]>
                </description>
                <link>https://www.freecodecamp.org/news/remote-procedure-calls-protocol-buffers-and-modern-distributed-systems-communication/</link>
                <guid isPermaLink="false">6a6145d945466c5d8ca2a549</guid>
                
                    <category>
                        <![CDATA[ gRPC ]]>
                    </category>
                
                    <category>
                        <![CDATA[ RPC ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Dart ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Flutter ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Google ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oluwaseyi Fatunmole ]]>
                </dc:creator>
                <pubDate>Wed, 22 Jul 2026 22:36:09 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/1205581e-5729-44fa-837e-0f30981ea059.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Every application, at some point, needs to talk to another system. A mobile app talks to a backend. A backend service talks to a payment gateway. An authentication service talks to a user service. A data pipeline talks to a storage layer.</p>
<p>The question is never whether systems need to communicate. The question is always how.</p>
<p>For years, REST over HTTP with JSON was the default answer. It works, it's simple, and the tooling is everywhere. But as systems grow in scale (in the number of services talking to each other, the volume of data being exchanged, and the need for real-time communication), REST starts to show its limits.</p>
<p>This is where Remote Procedure Calls, Protocol Buffers, and gRPC enter the picture.</p>
<p>In this handbook, you'll learn what RPC is and the problem it was designed to solve. You'll also understand Protocol Buffers: what they are, why they exist, and how they work.</p>
<p>You'll then see how Google combined these ideas into gRPC, one of the most powerful communication frameworks in modern distributed systems. You'll learn all four gRPC communication patterns, see code generated across multiple languages from a single contract file, and walk through a complete end-to-end Flutter implementation with production-grade concerns including authentication, error handling, and timeouts.</p>
<p>By the end, you won't just know what gRPC is. You'll understand when to use it, when not to, and how to think about service communication as a systems engineer.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a href="#heading-what-is-a-remote-procedure-call">What is a Remote Procedure Call</a>?</p>
</li>
<li><p><a href="#heading-the-problem-rpc-solves">The Problem RPC Solves</a></p>
</li>
<li><p><a href="#heading-why-grpc-over-rest-the-real-case">Why gRPC Over REST: The Real Case</a></p>
</li>
<li><p><a href="#heading-protocol-buffers-a-new-language-for-data">Protocol Buffers: A New Language for Data</a></p>
</li>
<li><p><a href="#heading-the-proto-file">The Proto File</a></p>
</li>
<li><p><a href="#heading-json-vs-protocol-buffers">JSON vs Protocol Buffers</a></p>
</li>
<li><p><a href="#heading-the-protoc-compiler-and-code-generation">The Protoc Compiler and Code Generation</a></p>
</li>
<li><p><a href="#heading-what-is-grpc">What is gRPC</a>?</p>
</li>
<li><p><a href="#heading-why-http2-matters-for-grpc">Why HTTP/2 Matters for gRPC</a></p>
</li>
<li><p><a href="#heading-the-four-grpc-communication-patterns">The Four gRPC Communication Patterns</a></p>
</li>
<li><p><a href="#heading-the-protobuf-repository-organizational-best-practice">The Protobuf Repository: Organizational Best Practice</a></p>
</li>
<li><p><a href="#heading-building-a-complete-grpc-system-with-dart-and-flutter">Building a Complete gRPC System with Dart and Flutter</a></p>
</li>
<li><p><a href="#heading-production-concerns">Production Concerns</a></p>
</li>
<li><p><a href="#heading-grpc-vs-rest-vs-websockets-when-to-use-what">gRPC vs REST vs WebSockets: When to Use What</a></p>
</li>
<li><p><a href="#heading-the-hybrid-architecture">The Hybrid Architecture</a></p>
</li>
<li><p><a href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-what-is-a-remote-procedure-call">What is a Remote Procedure Call?</h2>
<p>To understand RPCs, you first need to understand what a procedure call is.</p>
<p>A procedure call means invoking a procedure or function so that its code executes. For example, in Dart:</p>
<pre><code class="language-dart">double calculateTax(double amount) {
  return amount * 0.075;
}

final tax = calculateTax(50000); // local procedure call
</code></pre>
<p>You call <code>calculateTax</code>, pass an argument, and get a result back. The function lives on the same machine, in the same process, in the same memory space. This is a local procedure call.</p>
<p>A Remote Procedure Call takes this same idea and stretches it across a network. The function you're calling lives on a different machine, in a different process, and potentially in a different country. But from the caller's perspective, it feels exactly like calling a local function.</p>
<pre><code class="language-dart">// This looks like a local function call
final tax = await taxService.calculateTax(amount: 50000);

// But under the hood, this:
// 1. Serializes the argument into a binary format
// 2. Sends it over a network connection to a remote server
// 3. The server executes calculateTax with your argument
// 4. Serializes the result
// 5. Sends it back over the network
// 6. Deserializes it into a Dart object
// 7. Returns it to you as if it were local
</code></pre>
<p>The network complexity is completely hidden. You call a function. You get a result. Everything in between is handled by the RPC framework.</p>
<p>This is the fundamental idea behind RPC: make calling a remote function feel as natural as calling a local one.</p>
<h2 id="heading-the-problem-rpc-solves">The Problem RPC Solves</h2>
<p>To appreciate why RPC matters, you need to understand what the alternative looks like.</p>
<p>Without RPC, calling a remote service looks like this:</p>
<pre><code class="language-dart">Future&lt;double&gt; calculateTax(double amount) async {
  final response = await http.post(
    Uri.parse('https://tax-service.internal/api/v1/calculate'),
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer $token',
    },
    body: jsonEncode({'amount': amount}),
  );

  if (response.statusCode != 200) {
    throw Exception('Tax calculation failed: ${response.statusCode}');
  }

  final data = jsonDecode(response.body);
  return (data['tax'] as num).toDouble();
}
</code></pre>
<p>Every service call requires you to:</p>
<ul>
<li><p>Know and hardcode the endpoint URL</p>
</li>
<li><p>Know the correct HTTP method</p>
</li>
<li><p>Manually serialize your request to JSON</p>
</li>
<li><p>Handle HTTP status codes yourself</p>
</li>
<li><p>Manually deserialize the response from JSON</p>
</li>
<li><p>Cast dynamic types to the types you actually expect</p>
</li>
<li><p>Hope the field names in the response match what you think they are</p>
</li>
</ul>
<p>Now multiply this by every single service call in your application. An authentication service, a user service, a payment service, a notification service, a transaction service. Every one of them requires the same manual boilerplate. Every one of them introduces the possibility of a typo in a field name, a wrong status code assumption, or a JSON deserialization failure that only surfaces at runtime.</p>
<p>With RPC:</p>
<pre><code class="language-dart">// Feels like a local function call
final tax = await taxService.calculateTax(
  TaxRequest(amount: 50000),
);
// tax is already a strongly typed TaxResponse object
// No URLs. No HTTP methods. No JSON parsing. No casting.
</code></pre>
<p>The framework handles everything. The function signature is defined in a contract file that both the client and server use. The types are enforced at compile time. If the server changes the response shape, the client fails to compile before anything reaches production.</p>
<p>This is what RPC solves: it removes the accidental complexity of network communication and lets you focus on what you're actually trying to do.</p>
<h2 id="heading-why-grpc-over-rest-the-real-case">Why gRPC Over REST: The Real Case</h2>
<p>Before going into the technical details of Protocol Buffers and gRPC, it's important to make a solid case for why you'd choose gRPC over REST in specific scenarios. This isn't a claim that gRPC is always better. It's a clear look at where it genuinely wins.</p>
<h3 id="heading-large-payloads-called-by-many-internal-systems">Large Payloads Called by Many Internal Systems</h3>
<p>Consider an internal enterprise API in a large telecommunications company. A single request and response payload for a plan registration or activation flow can contain over a thousand fields. This endpoint is called by dozens of internal applications: billing systems, CRM platforms, customer-facing mobile apps, internal dashboards, and partner portals.</p>
<p>With REST and JSON, every one of those applications sends and receives that thousand-field payload as text. Field names like <code>subscription_activation_status</code>, <code>rate_plan_identifier</code>, and <code>network_provisioning_reference</code> travel over the wire as strings on every single request. A significant portion of every payload isn't data. It's labels for data.</p>
<p>With Protocol Buffers, field names never appear in the payload at all. Only field numbers and values travel over the wire. That thousand-field payload shrinks dramatically. For an endpoint called millions of times per day by dozens of systems, the bandwidth saving is enormous and translates directly to infrastructure cost reduction.</p>
<p>Beyond size, the generated client guarantee is equally important. With REST, each of those dozens of applications reads the API documentation and builds its own understanding of the contract. When the backend changes a field name or type, not every application finds out immediately. Some find out in production when they break.</p>
<p>With a shared <code>.proto</code> file, every application generates its own strongly typed client from the same source. A contract change means every application regenerates. The compiler immediately reports where the breaking change affects each codebase. Nothing reaches production in a broken state.</p>
<h3 id="heading-low-bandwidth-and-remote-network-conditions">Low Bandwidth and Remote Network Conditions</h3>
<p>This is one of the most under-appreciated advantages of gRPC in markets where network quality varies significantly.</p>
<p>In many regions, a substantial portion of mobile users are on 2G or 3G connections. On a 2G connection, bandwidth can be as low as 50 to 100 kilobits per second. A REST JSON response that is 80 kilobytes takes over 6 seconds to download on a 2G connection. The equivalent protobuf binary, which can be 3 to 10 times smaller, takes under 2 seconds.</p>
<p>That difference isn't a technical footnote. It's the line between an application that feels usable and one that feels broken to a significant portion of your users. For any product that operates in markets with variable network conditions, protobuf's binary efficiency is a direct competitive advantage.</p>
<p>Beyond size, gRPC runs over HTTP/2 which maintains a single persistent connection rather than opening a new connection for every request. On slow networks where connection establishment (the TCP handshake and TLS negotiation) can itself take hundreds of milliseconds, reusing a single connection across many calls saves significant time over a session.</p>
<h3 id="heading-microservice-to-microservice-communication">Microservice to Microservice Communication</h3>
<p>When two internal services need to communicate, you have options. A message bus like Kafka or RabbitMQ is excellent when you don't need an immediate response, when the operation can happen asynchronously, and when you're broadcasting something that happened to multiple consumers.</p>
<p>But many service-to-service calls are synchronous by nature. An authentication service needs to validate a token right now before the request proceeds. A fraud detection service needs to assess a transaction right now before the payment is authorized. A pricing service needs to calculate a rate right now before the quote is generated. These operations can't publish an event and wait.</p>
<p>For synchronous service-to-service calls at high frequency, gRPC over HTTP/2 with protobuf encoding is significantly more efficient than REST. The persistent multiplexed connection means no connection setup overhead per call. The binary encoding means no JSON serialization and deserialization overhead on every hop. The generated clients mean both services compile against the same contract.</p>
<p>At scale, when two services are calling each other thousands of times per second, these efficiency differences compound into real performance and cost differences.</p>
<h3 id="heading-managing-api-contracts-across-multiple-teams">Managing API Contracts Across Multiple Teams</h3>
<p>In a large engineering organization, multiple teams build services that others depend on. REST API contracts live in documentation. Documentation goes stale. The backend team changes a field name. The mobile team finds out when users report crashes. The data team finds out when their pipeline throws an error at 2am.</p>
<p>gRPC's protobuf repository approach transforms contract management from a documentation problem into a code problem. Contract changes go through pull requests. Every dependent team reviews the change. Breaking changes are caught at compile time. Nobody is surprised in production.</p>
<p>This governance benefit scales with team size. The larger the organization, the more valuable it becomes.</p>
<h3 id="heading-real-time-communication">Real-Time Communication</h3>
<p>REST is request-response. The client asks and the server answers. The conversation ends. For real-time features, you either poll (wasteful) or bolt on a separate WebSocket server alongside your REST API (two different systems to maintain).</p>
<p>gRPC's streaming patterns handle real-time communication natively within the same framework you use for regular calls. A live balance update, a real-time transaction notification, or a bidirectional chat session all use the same generated client, the same connection, and the same protobuf encoding as your regular unary calls.</p>
<p>One framework with all communication patterns. No separate infrastructure.</p>
<h2 id="heading-protocol-buffers-a-new-language-for-data">Protocol Buffers: A New Language for Data</h2>
<p>RPC is a concept. To implement it, you need two things: a way to define the contract between client and server, and a way to serialize data efficiently for transmission over the network.</p>
<p>This is where Protocol Buffers comes in.</p>
<p>Protocol Buffers, commonly called protobuf, is a language-neutral, platform-neutral, extensible mechanism for serializing structured data. It was developed at Google in 2001, used internally for years, and open-sourced in 2008.</p>
<h3 id="heading-the-json-problem-at-scale">The JSON Problem at Scale</h3>
<p>JSON is the dominant data format for web APIs. It's human-readable, flexible, and universally supported. For many use cases, it's the right choice.</p>
<p>But JSON has structural inefficiencies that become painful at scale.</p>
<p>Consider a user profile response:</p>
<pre><code class="language-json">{
  "id": "usr_001",
  "first_name": "John",
  "last_name": "Smith",
  "email": "john@example.com",
  "phone_number": "+2348012345678",
  "account_type": "savings",
  "balance": 500000.00,
  "currency": "NGN",
  "is_verified": true,
  "is_active": true,
  "kyc_level": 3,
  "created_at": "2024-01-15T10:30:00Z",
  "last_login": "2026-07-20T09:15:00Z"
}
</code></pre>
<p>Every field name travels over the network as a string on every single response. <code>"first_name"</code>, <code>"account_type"</code>, <code>"phone_number"</code> aren't data. They're labels for data. But they consume bytes on every request.</p>
<p>Now consider an internal enterprise API with over a thousand fields in its request and response payload, being called by dozens of internal applications thousands of times per day. A significant portion of every payload is field name strings, not actual data. The overhead accumulates into real bandwidth and processing costs.</p>
<p>Beyond size, JSON has another problem: it has no schema at the network level. Nothing prevents a backend engineer from renaming <code>"first_name"</code> to <code>"firstName"</code> in a new deployment. The client breaks at runtime in production with real users.</p>
<h3 id="heading-what-protocol-buffers-do-differently">What Protocol Buffers Do Differently</h3>
<p>Protocol Buffers solve both problems with a fundamentally different approach to data encoding.</p>
<p>Instead of encoding data as human-readable text with field names, protobuf encodes data as compact binary using only field numbers and values. Field names never travel over the network.</p>
<p>Here's the same user profile defined in protobuf:</p>
<pre><code class="language-protobuf">message UserProfile {
  string id = 1;
  string first_name = 2;
  string last_name = 3;
  string email = 4;
  string phone_number = 5;
  string account_type = 6;
  double balance = 7;
  string currency = 8;
  bool is_verified = 9;
  bool is_active = 10;
  int32 kyc_level = 11;
  string created_at = 12;
  string last_login = 13;
}
</code></pre>
<p>When protobuf encodes this data, the output is binary that no human can read. But to a machine, it's extremely compact and fast to parse. The field numbers (1, 2, 3...) identify each field. The names never appear in the encoded output at all.</p>
<p>The result: the same user profile that's approximately 280 bytes in JSON is approximately 95 bytes in protobuf. That's three times smaller. For a thousand-field enterprise payload, this difference is enormous.</p>
<p>And because the schema is defined in a <code>.proto</code> file that both client and server compile against, field name changes are caught at compile time, not at runtime.</p>
<h2 id="heading-the-proto-file">The Proto File</h2>
<p>The <code>.proto</code> file is the heart of everything in the protobuf and gRPC ecosystem. It's where you define your data models and your service contracts.</p>
<p>It's written in Protocol Buffer Language (proto3) – not Go, not Dart, not Python, not Java. You write it in any text editor. VS Code with the <code>vscode-proto3</code> extension gives you syntax highlighting, autocomplete, and inline validation.</p>
<p>Here's a complete <code>.proto</code> file for a fintech platform:</p>
<pre><code class="language-csharp">syntax = "proto3";

package banking;

option go_package = "./banking";
option java_package = "com.fintech.banking";



service BankingService {
  // Unary: one request, one response
  rpc Login (LoginRequest) returns (LoginResponse);

  // Unary: fetch user profile
  rpc GetProfile (ProfileRequest) returns (UserProfile);

  // Server streaming: real-time balance updates
  rpc WatchBalance (BalanceRequest) returns (stream BalanceResponse);

  // Server streaming: live transaction feed
  rpc StreamTransactions (TransactionRequest) returns (stream Transaction);

  // Client streaming: upload KYC documents in chunks
  rpc UploadDocument (stream DocumentChunk) returns (UploadResponse);

  // Bidirectional streaming: live chat support
  rpc Chat (stream ChatMessage) returns (stream ChatMessage);
}



message LoginRequest {
  string email = 1;
  string password = 2;
}

message LoginResponse {
  string token = 1;
  string user_id = 2;
  int64 expires_at = 3;
}

message ProfileRequest {
  string user_id = 1;
}

message UserProfile {
  string id = 1;
  string first_name = 2;
  string last_name = 3;
  string email = 4;
  string phone_number = 5;
  string account_type = 6;
  double balance = 7;
  string currency = 8;
  bool is_verified = 9;
  int32 kyc_level = 10;
}

message BalanceRequest {
  string user_id = 1;
}

message BalanceResponse {
  double balance = 1;
  string currency = 2;
  int64 timestamp = 3;
}

message TransactionRequest {
  string user_id = 1;
  int32 limit = 2;
}

message Transaction {
  string id = 1;
  double amount = 2;
  string description = 3;
  string type = 4;
  int64 timestamp = 5;
}

message DocumentChunk {
  bytes data = 1;
  string document_type = 2;
  int32 chunk_index = 3;
  bool is_last = 4;
}

message UploadResponse {
  bool success = 1;
  string document_id = 2;
  string message = 3;
}

message ChatMessage {
  string sender_id = 1;
  string content = 2;
  int64 timestamp = 3;
}
</code></pre>
<p>Let's walk through every part of this file carefully.</p>
<h3 id="heading-the-syntax-declaration">The Syntax Declaration</h3>
<pre><code class="language-csharp">syntax = "proto3";
</code></pre>
<p>This tells the protobuf compiler which version of the Protocol Buffer language you're using. proto3 is the current standard. It must be the first non-comment line in every <code>.proto</code> file.</p>
<h3 id="heading-the-package-declaration">The Package Declaration</h3>
<pre><code class="language-csharp">package banking;
</code></pre>
<p>The package name prevents naming conflicts when you have multiple <code>.proto</code> files across different services. It functions like a namespace. If two services both define a <code>UserProfile</code> message, the package name distinguishes them: <code>banking.UserProfile</code> versus <code>auth.UserProfile</code>.</p>
<h3 id="heading-language-specific-options">Language-Specific Options</h3>
<pre><code class="language-protobuf">option go_package = "./banking";
option java_package = "com.fintech.banking";
</code></pre>
<p>These options tell the compiler how to organize the generated code for specific languages. They don't affect the proto file itself, only the generated output.</p>
<h3 id="heading-the-service-definition">The Service Definition</h3>
<pre><code class="language-csharp">service BankingService {
  rpc Login (LoginRequest) returns (LoginResponse);
  rpc WatchBalance (BalanceRequest) returns (stream BalanceResponse);
}
</code></pre>
<p>The <code>service</code> block defines the RPC contract. Think of it exactly like an abstract class in any object-oriented language. It declares what functions exist, what they accept, and what they return.</p>
<p>Each <code>rpc</code> line defines one remote procedure. The <code>stream</code> keyword before a type indicates that multiple messages will flow rather than just one.</p>
<h3 id="heading-message-definitions">Message Definitions</h3>
<pre><code class="language-csharp">message LoginRequest {
  string email = 1;
  string password = 2;
}
</code></pre>
<p>A <code>message</code> is a data structure. Think of it as a class with only fields: no methods, no logic. Each field has three parts.</p>
<p>The <strong>type</strong> can be <code>string</code>, <code>int32</code>, <code>int64</code>, <code>double</code>, <code>bool</code>, <code>bytes</code>, or another message type.</p>
<p>The <strong>name</strong> is the field name as it appears in generated code. This is for human readability only. It never appears in the binary encoding.</p>
<p>The <strong>field number</strong> (= 1, = 2, = 3) is the unique identifier that protobuf uses in the binary output instead of the field name. This is critical: once you assign a field number, you must never change it or reuse it. The binary encoding uses these numbers, not names. If you change a field number, old encoded data becomes unreadable.</p>
<p>You can safely add new fields with new numbers, remove fields (the number stays reserved, never reuse it), and rename fields (names don't appear in binary). You must never change a field number, reuse a removed field's number, or change a field's type.</p>
<h2 id="heading-json-vs-protocol-buffers">JSON vs Protocol Buffers</h2>
<p>Now that you understand both formats, let's make a direct comparison.</p>
<h3 id="heading-size-comparison">Size Comparison</h3>
<p>Let's look at the same login request in both formats:</p>
<p><strong>JSON (text):</strong></p>
<pre><code class="language-csharp">{
  "email": "john@example.com",
  "password": "securepassword123"
}
</code></pre>
<p>Approximately 55 bytes.</p>
<p><strong>Protobuf binary:</strong></p>
<p>Field 1 (email): tag + length + value bytes. Field 2 (password): tag + length + value bytes.</p>
<p>Approximately 38 bytes.</p>
<p>For a simple two-field message, the difference is modest. Now consider a thousand-field enterprise payload. Field names alone in JSON can account for 40-60% of the total payload size. In protobuf, field names contribute zero bytes to the payload.</p>
<p>On a 2G connection where bandwidth can be as low as 50 kilobits per second, the difference between an 80 kilobyte JSON response and a 15 kilobyte protobuf response is the difference between a 13-second load and a 2-second load. For users in areas with limited network infrastructure, this isn't a performance metric. It's a usability threshold.</p>
<h3 id="heading-speed-comparison">Speed Comparison</h3>
<p>Protobuf serialization and deserialization is significantly faster than JSON parsing because binary parsing requires no string tokenizing, quote handling, whitespace skipping, or type inference. The parser reads a field number, reads the value type, reads the value, and moves to the next field. It's a direct binary read.</p>
<p>JSON parsing must tokenize a string character by character, identify keys and values by their surrounding quotes and delimiters, infer types from the value format, and construct objects from dynamic maps.</p>
<p>On a mobile device handling hundreds of responses per session, this parsing difference translates to measurable CPU and battery savings.</p>
<h3 id="heading-schema-and-type-safety">Schema and Type Safety</h3>
<p>JSON has no schema enforcement at the network level. A backend can change <code>"balance"</code> to <code>"current_balance"</code> and the client only discovers this when the app crashes in production.</p>
<p>Protobuf schemas are enforced at compile time. If the <code>.proto</code> file changes in a way that breaks the client, the client fails to compile. The problem is caught before it reaches any user.</p>
<h3 id="heading-the-honest-comparison">The Honest Comparison</h3>
<table>
<thead>
<tr>
<th></th>
<th>JSON</th>
<th>Protocol Buffers</th>
</tr>
</thead>
<tbody><tr>
<td>Encoding</td>
<td>Text (UTF-8)</td>
<td>Binary</td>
</tr>
<tr>
<td>Human readable</td>
<td>Yes</td>
<td>No</td>
</tr>
<tr>
<td>Payload size</td>
<td>Larger (field names included)</td>
<td>3 to 10 times smaller</td>
</tr>
<tr>
<td>Parse speed</td>
<td>Slower (text tokenizing)</td>
<td>Faster (direct binary read)</td>
</tr>
<tr>
<td>Schema enforcement</td>
<td>None at network level</td>
<td>Compile-time enforcement</td>
</tr>
<tr>
<td>Code generation</td>
<td>Optional</td>
<td>Required and automatic</td>
</tr>
<tr>
<td>Best for</td>
<td>Public APIs, human inspection</td>
<td>Internal services, high performance</td>
</tr>
</tbody></table>
<h2 id="heading-the-protoc-compiler-and-code-generation">The Protoc Compiler and Code Generation</h2>
<p>The <code>protoc</code> compiler reads your <code>.proto</code> file and generates code in any language you specify. This is where the universal contract becomes reality.</p>
<p><strong>Generating Go code (for the backend server):</strong></p>
<pre><code class="language-csharp">protoc \
  --go_out=. \
  --go-grpc_out=. \
  proto/banking.proto
</code></pre>
<p>Generates:</p>
<pre><code class="language-plaintext">banking.pb.go        &lt;- the message structs
banking_grpc.pb.go   &lt;- the server interface
</code></pre>
<p><strong>Generating Dart code (for the Flutter client):</strong></p>
<pre><code class="language-csharp">protoc \
  --dart_out=grpc:lib/generated \
  proto/banking.proto
</code></pre>
<p>Generates:</p>
<pre><code class="language-plaintext">lib/generated/
  banking.pb.dart        &lt;- the message classes
  banking.pbgrpc.dart    &lt;- the client stub
</code></pre>
<p><strong>Generating Python code (for a data service):</strong></p>
<pre><code class="language-csharp">protoc \
  --python_out=. \
  --grpc_python_out=. \
  proto/banking.proto
</code></pre>
<p>Generates:</p>
<pre><code class="language-plaintext">banking_pb2.py         &lt;- the message classes
banking_pb2_grpc.py    &lt;- the client and server classes
</code></pre>
<p><strong>Generating TypeScript code (for a web frontend):</strong></p>
<pre><code class="language-csharp">protoc \
  --ts_out=. \
  proto/banking.proto
</code></pre>
<p>Generates:</p>
<pre><code class="language-plaintext">banking.ts             &lt;- typed message classes and client
</code></pre>
<p>All of this from the same single <code>banking.proto</code> file.</p>
<p>The Go backend engineer never writes serialization code. The Flutter engineer never writes deserialization code. The Python data engineer never parses binary manually. The TypeScript web engineer never constructs HTTP requests. All of that is generated automatically from the contract that every team agreed on.</p>
<p>Here's what the generated code looks like in each language to make this concrete:</p>
<p><strong>Generated Go server interface (the backend implements this):</strong></p>
<pre><code class="language-go">// Generated — do not edit
type BankingServiceServer interface {
    Login(context.Context, *LoginRequest) (*LoginResponse, error)
    WatchBalance(*BalanceRequest, BankingService_WatchBalanceServer) error
    mustEmbedUnimplementedBankingServiceServer()
}

// The Go backend engineer writes this implementation
type bankingServer struct {
    pb.UnimplementedBankingServiceServer
}

func (s *bankingServer) Login(
    ctx context.Context,
    req *pb.LoginRequest,
) (*pb.LoginResponse, error) {
    token, err := authService.Login(req.Email, req.Password)
    if err != nil {
        return nil, status.Errorf(codes.Unauthenticated, "invalid credentials")
    }
    return &amp;pb.LoginResponse{
        Token:  token,
        UserId: user.Id,
    }, nil
}
</code></pre>
<p><strong>Generated Python client (the data team uses this):</strong></p>
<pre><code class="language-python">import grpc
import banking_pb2
import banking_pb2_grpc

channel = grpc.secure_channel(
    'api.fintech-platform.com:50051',
    grpc.ssl_channel_credentials()
)
stub = banking_pb2_grpc.BankingServiceStub(channel)

response = stub.Login(banking_pb2.LoginRequest(
    email='john@example.com',
    password='password123'
))

print(f"Token: {response.token}")
print(f"User ID: {response.user_id}")
</code></pre>
<p><strong>Generated Dart client (you use this in Flutter):</strong></p>
<pre><code class="language-dart">import 'package:grpc/grpc.dart';
import 'generated/banking.pbgrpc.dart';
import 'generated/banking.pb.dart';

final channel = ClientChannel('api.fintech-platform.com', port: 50051);
final client = BankingServiceClient(channel);

final response = await client.login(
  LoginRequest(email: 'john@example.com', password: 'password123'),
);

print('Token: ${response.token}');
print('User ID: ${response.userId}');
</code></pre>
<p>Three different languages. Three different teams. One <code>.proto</code> file. All of them are generated, strongly typed, and guaranteed to be in sync with the server.</p>
<h2 id="heading-what-is-grpc">What is gRPC?</h2>
<p>gRPC is Google's open-source Remote Procedure Call framework. It was open-sourced in 2016 and is now a Cloud Native Computing Foundation (CNCF) graduated project. This means it's been production-proven at the highest level of the cloud-native ecosystem.</p>
<p>gRPC combines three things:</p>
<ol>
<li><p><strong>Remote Procedure Calls</strong> as the programming model: calling remote functions like local ones.</p>
</li>
<li><p><strong>Protocol Buffers</strong> as the interface definition language and data serialization format: strongly typed contracts and compact binary encoding.</p>
</li>
<li><p><strong>HTTP/2</strong> as the transport protocol: multiplexed, persistent connections with binary framing.</p>
</li>
</ol>
<p>The combination of these three produces a framework that's faster than REST, more structured than WebSockets, and more powerful than any of its predecessors.</p>
<p>gRPC is used internally at Google for virtually all service-to-service communication. Netflix, Uber, Square, Dropbox, Lyft, and hundreds of other organizations use it for their internal microservice communication. Official support exists for Go, Java, Python, C++, C#, Ruby, Node.js, PHP, Dart, Kotlin, and more.</p>
<h2 id="heading-why-http2-matters-for-grpc">Why HTTP/2 Matters for gRPC</h2>
<p>gRPC is built exclusively on HTTP/2. Understanding what HTTP/2 provides is essential to understanding why gRPC performs the way it does.</p>
<p>HTTP/1.1, which powers most REST APIs, has fundamental performance constraints. Each request must complete before the next one begins on the same connection. Headers are sent as verbose text on every request. The server can't send data unless the client asks first.</p>
<p>HTTP/2 was designed to fix these constraints at the protocol level.</p>
<h3 id="heading-multiplexing">Multiplexing</h3>
<p>HTTP/2 introduces streams within a single connection. Multiple independent requests can travel over the same TCP connection simultaneously.</p>
<pre><code class="language-csharp">Single TCP connection to api.fintech-platform.com

Stream 1: Login request ---------&gt; Login response
Stream 2: Profile request -------&gt; Profile response
Stream 3: Balance request -------&gt; Balance stream (ongoing)
Stream 4: Transactions request --&gt; Transaction stream (ongoing)

All four streams active simultaneously over ONE connection
</code></pre>
<p>In HTTP/1.1, you would need four separate connections or wait for each to complete before starting the next. HTTP/2 handles all four over a single persistent connection with no waiting.</p>
<p>This is the foundation of gRPC's streaming capabilities. A persistent multiplexed connection is what allows the server to keep pushing balance updates and transaction notifications while the client continues making other calls.</p>
<h3 id="heading-binary-framing">Binary Framing</h3>
<p>HTTP/1.1 sends everything as text. HTTP/2 sends everything as binary frames. Binary is more compact and significantly faster for machines to parse.</p>
<p>Every gRPC message is broken into binary frames and sent over the HTTP/2 connection. Combined with protobuf's binary encoding, gRPC data travels in the most compact form possible at every layer.</p>
<h3 id="heading-header-compression-hpack">Header Compression (HPACK)</h3>
<p>HTTP/1.1 sends full headers on every request. An Authorization header carrying a JWT token can be 500 bytes or more, repeated on every request.</p>
<p>HTTP/2 uses HPACK compression. Headers sent on previous requests are cached. Subsequent requests only send headers that changed. The Authorization header, once sent, is referenced by a short index rather than retransmitted in full.</p>
<p>On a mobile application making dozens of authenticated requests per session, this compression is a meaningful bandwidth saving, especially on slow networks where every byte matters.</p>
<h3 id="heading-server-push">Server Push</h3>
<p>HTTP/2 allows the server to proactively send data to the client without waiting for a request. The client opens a stream and the server keeps pushing messages through it as events occur.</p>
<p>This is the mechanism behind gRPC server streaming. The client sends one <code>WatchBalance</code> request and the server pushes a new <code>BalanceResponse</code> every time the balance changes. No polling or repeated requests. The connection stays open and the server speaks whenever it has something new to say.</p>
<h2 id="heading-the-four-grpc-communication-patterns">The Four gRPC Communication Patterns</h2>
<p>This is the most important section of this article. gRPC doesn't have one communication model. It has four. Each one is defined precisely in the <code>.proto</code> file and serves different use cases.</p>
<h3 id="heading-pattern-1-unary-rpc">Pattern 1: Unary RPC</h3>
<p>One request from the client and one response from the server. This is identical to a REST API call in terms of the request-response flow.</p>
<pre><code class="language-csharp">rpc Login (LoginRequest) returns (LoginResponse);
</code></pre>
<pre><code class="language-plaintext">Client ----LoginRequest----&gt; Server
Client &lt;---LoginResponse---- Server
Done.
</code></pre>
<p><strong>When to use Unary RPC:</strong> Login, profile fetch, payment initiation, data creation, configuration retrieval: any operation that follows a simple ask-and-answer pattern.</p>
<p><strong>Dart implementation:</strong></p>
<pre><code class="language-dart">Future&lt;LoginResponse&gt; login(String email, String password) async {
  try {
    return await _client.login(
      LoginRequest(email: email, password: password),
    );
  } on GrpcError catch (e) {
    throw _mapGrpcError(e);
  }
}
</code></pre>
<p><strong>Go server implementation:</strong></p>
<pre><code class="language-go">func (s *bankingServer) Login(
    ctx context.Context,
    req *pb.LoginRequest,
) (*pb.LoginResponse, error) {
    user, err := s.authService.Login(req.Email, req.Password)
    if err != nil {
        return nil, status.Errorf(codes.Unauthenticated, "invalid credentials: %v", err)
    }
    token, _ := s.tokenService.Generate(user.Id)
    return &amp;pb.LoginResponse{
        Token:  token,
        UserId: user.Id,
    }, nil
}
</code></pre>
<h3 id="heading-pattern-2-server-streaming-rpc">Pattern 2: Server Streaming RPC</h3>
<p>One request from the client and a continuous stream of responses from the server. The connection stays open and the server pushes messages as they become available.</p>
<pre><code class="language-csharp">rpc WatchBalance (BalanceRequest) returns (stream BalanceResponse);
rpc StreamTransactions (TransactionRequest) returns (stream Transaction);
</code></pre>
<pre><code class="language-plaintext">Client ----BalanceRequest----&gt; Server
Client &lt;---BalanceResponse---- Server (balance: 500000)
Client &lt;---BalanceResponse---- Server (balance: 495000, after a debit)
Client &lt;---BalanceResponse---- Server (balance: 995000, after a credit)
[stream stays open, server pushes on every change]
</code></pre>
<p><strong>When to use Server Streaming:</strong> Live account balance, real-time transaction notifications, live stock prices, sports scores, news feeds, system monitoring dashboards: anything where the server has an ongoing series of updates to deliver.</p>
<p><strong>Dart implementation:</strong></p>
<pre><code class="language-csharp">Stream&lt;BalanceResponse&gt; watchBalance(String userId) {
  return _client.watchBalance(
    BalanceRequest(userId: userId),
  );
}
</code></pre>
<p>In Flutter, consume this with a <code>StreamBuilder</code>:</p>
<pre><code class="language-csharp">StreamBuilder&lt;BalanceResponse&gt;(
  stream: _dataSource.watchBalance(currentUserId),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {
      return const CircularProgressIndicator();
    }

    if (snapshot.hasError) {
      return Text('Error: ${snapshot.error}');
    }

    if (!snapshot.hasData) {
      return const Text('Waiting for balance...');
    }

    final balance = snapshot.data!;
    return Column(
      children: [
        Text(
          '${balance.currency} ${balance.balance.toStringAsFixed(2)}',
          style: const TextStyle(
            fontSize: 36,
            fontWeight: FontWeight.bold,
          ),
        ),
        Text(
          'Updated: ${DateTime.fromMillisecondsSinceEpoch(balance.timestamp.toInt())}',
        ),
      ],
    );
  },
)
</code></pre>
<p>Every time the server pushes a new balance, the <code>StreamBuilder</code> calls <code>builder</code> again and the widget shows the updated value. There's zero polling logic or manual refresh. The server speaks and the widget listens.</p>
<p><strong>Go server implementation:</strong></p>
<pre><code class="language-csharp">func (s *bankingServer) WatchBalance(
    req *pb.BalanceRequest,
    stream pb.BankingService_WatchBalanceServer,
) error {
    ticker := time.NewTicker(time.Second)
    defer ticker.Stop()

    for {
        select {
        case &lt;-stream.Context().Done():
            return nil
        case &lt;-ticker.C:
            balance, err := s.accountService.GetBalance(req.UserId)
            if err != nil {
                return status.Errorf(codes.Internal, "failed to fetch balance: %v", err)
            }

            if err := stream.Send(&amp;pb.BalanceResponse{
                Balance:   balance.Amount,
                Currency:  balance.Currency,
                Timestamp: time.Now().UnixMilli(),
            }); err != nil {
                return err
            }
        }
    }
}
</code></pre>
<h3 id="heading-pattern-3-client-streaming-rpc">Pattern 3: Client Streaming RPC</h3>
<p>The client sends a stream of messages to the server. The server processes them all and responds once at the end.</p>
<pre><code class="language-csharp">rpc UploadDocument (stream DocumentChunk) returns (UploadResponse);
</code></pre>
<pre><code class="language-plaintext">Client ----Chunk 1 (bytes 0-1024)-----&gt; Server
Client ----Chunk 2 (bytes 1024-2048)--&gt; Server
Client ----Chunk 3 (bytes 2048-3072)--&gt; Server
Client ----Chunk 4 (last chunk)-------&gt; Server
Client &lt;---UploadResponse-------------- Server (document_id: "doc_001")
</code></pre>
<p><strong>When to use Client Streaming:</strong> Uploading large files (KYC documents, profile photos) in chunks, sending a batch of sensor readings, submitting bulk records to a server.</p>
<p><strong>Dart implementation:</strong></p>
<pre><code class="language-dart">Future&lt;UploadResponse&gt; uploadDocument(
  List&lt;Uint8List&gt; chunks,
  String documentType,
) async {
  try {
    Stream&lt;DocumentChunk&gt; chunkStream() async* {
      for (int i = 0; i &lt; chunks.length; i++) {
        yield DocumentChunk(
          data: chunks[i],
          documentType: documentType,
          chunkIndex: i,
          isLast: i == chunks.length - 1,
        );
      }
    }

    return await _client.uploadDocument(chunkStream());
  } on GrpcError catch (e) {
    throw _mapGrpcError(e);
  }
}
</code></pre>
<p><code>chunkStream()</code> is an async generator function. The <code>async*</code> keyword means it yields values over time rather than returning a single value. Each <code>yield</code> produces one <code>DocumentChunk</code> message that gRPC sends to the server. The server receives these one by one and processes them all before sending a single <code>UploadResponse</code> at the end.</p>
<p><strong>Go server implementation:</strong></p>
<pre><code class="language-go">func (s *bankingServer) UploadDocument(
    stream pb.BankingService_UploadDocumentServer,
) error {
    var allData []byte
    var documentType string

    for {
        chunk, err := stream.Recv()
        if err == io.EOF {
            break
        }
        if err != nil {
            return status.Errorf(codes.Internal, "failed to receive chunk: %v", err)
        }

        allData = append(allData, chunk.Data...)
        documentType = chunk.DocumentType
    }

    docId, err := s.documentService.Store(allData, documentType)
    if err != nil {
        return status.Errorf(codes.Internal, "failed to store document: %v", err)
    }

    return stream.SendAndClose(&amp;pb.UploadResponse{
        Success:    true,
        DocumentId: docId,
        Message:    "Document uploaded successfully",
    })
}
</code></pre>
<h3 id="heading-pattern-4-bidirectional-streaming-rpc">Pattern 4: Bidirectional Streaming RPC</h3>
<p>Both the client and server stream messages simultaneously. Both sides can send at any time. Neither waits for the other.</p>
<pre><code class="language-csharp">rpc Chat (stream ChatMessage) returns (stream ChatMessage);
</code></pre>
<pre><code class="language-plaintext">Client ----"Hello"---------------------------&gt; Server
Server &lt;---"Hi, how can I help?"-------------- Client
Client ----"What is my account balance?"-----&gt; Server
Server &lt;---"Your balance is NGN 500,000"------ Client
Server &lt;---"New transaction alert: -5,000"---- Client (server-initiated)
Client ----"Thanks"--------------------------&gt; Server
[both sides communicate freely and simultaneously]
</code></pre>
<p><strong>When to use Bidirectional Streaming:</strong> Real-time chat, live collaborative document editing, multiplayer game state synchronization, interactive trading terminals, real-time customer support sessions.</p>
<p><strong>Dart implementation:</strong></p>
<pre><code class="language-csharp">void startChat(String userId) {
  final outgoing = StreamController&lt;ChatMessage&gt;();

  final incoming = _client.chat(outgoing.stream);

  incoming.listen(
    (message) {
      print('${message.senderId}: ${message.content}');
    },
    onError: (error) {
      print('Chat error: $error');
    },
    onDone: () {
      print('Chat session ended');
    },
  );

  outgoing.add(ChatMessage(
    senderId: userId,
    content: 'Hello, I need help with my account',
    timestamp: DateTime.now().millisecondsSinceEpoch,
  ));
}
</code></pre>
<p><code>StreamController</code> manages the outgoing message stream. You add messages to <code>outgoing</code> whenever the user sends something. The incoming stream delivers messages from the server. Both run simultaneously over the same HTTP/2 connection.</p>
<p><strong>Go server implementation:</strong></p>
<pre><code class="language-go">func (s *bankingServer) Chat(stream pb.BankingService_ChatServer) error {
    for {
        msg, err := stream.Recv()
        if err == io.EOF {
            return nil
        }
        if err != nil {
            return err
        }

        response := s.chatService.Process(msg)
        if err := stream.Send(&amp;pb.ChatMessage{
            SenderId:  "support_agent",
            Content:   response,
            Timestamp: time.Now().UnixMilli(),
        }); err != nil {
            return err
        }
    }
}
</code></pre>
<h2 id="heading-the-protobuf-repository-organizational-best-practice">The Protobuf Repository: Organizational Best Practice</h2>
<p>In a small project, the <code>.proto</code> file can live inside the backend repository. The mobile engineer clones the backend repo to get it. This works at small scale.</p>
<p>In any organization of meaningful size, this approach breaks down. The backend repo becomes the source of truth, giving the backend team unilateral control over the contract. Other teams find out about changes when their builds break.</p>
<p>The industry best practice is a dedicated protobuf repository: a standalone repository that belongs to everyone and is owned exclusively by no one.</p>
<pre><code class="language-plaintext">fintech-api-contracts/
  proto/
    auth/
      auth.proto
    banking/
      banking.proto
    payments/
      payments.proto
    notifications/
      notifications.proto
    kyc/
      kyc.proto
  scripts/
    generate_dart.sh
    generate_go.sh
    generate_python.sh
  README.md
</code></pre>
<h3 id="heading-how-contract-changes-work">How Contract Changes Work</h3>
<p>Every API change follows the same process:</p>
<pre><code class="language-plaintext">Engineer proposes a change to banking.proto
          |
          raises a Pull Request in fintech-api-contracts
          |
Flutter team lead reviews:
  "Does this break our client? Do we need to update?"

Go backend lead reviews:
  "Is this implementable? Does it follow our conventions?"

React web lead reviews:
  "Does the web client need changes?"

Python data lead reviews:
  "Does this affect our data pipelines?"
          |
All teams approve
          |
PR merges — the change is now the law
          |
Every team runs their code generation script
          |
Builds fail where breaking changes exist
Changes are caught at compile time
Before any code reaches production
</code></pre>
<p>This process gives you something REST with documentation can never provide: guaranteed contract synchronization across every team, enforced by the compiler, before anything reaches users.</p>
<h2 id="heading-building-a-complete-grpc-system-with-dart-and-flutter">Building a Complete gRPC System with Dart and Flutter</h2>
<p>Now let's put everything together in a complete, production-structured example.</p>
<h3 id="heading-project-setup">Project Setup</h3>
<p>Add the gRPC dependency to your Flutter project:</p>
<pre><code class="language-yaml"># pubspec.yaml
dependencies:
  flutter:
    sdk: flutter
  grpc: ^3.2.4
  protobuf: ^3.1.0

dev_dependencies:
  protoc_plugin: ^21.1.2
</code></pre>
<p>Install the protoc compiler and the Dart plugin:</p>
<pre><code class="language-yaml"># macOS
brew install protobuf

# Install the Dart protoc plugin
dart pub global activate protoc_plugin
</code></pre>
<p>Generate the Dart code from the proto file:</p>
<pre><code class="language-bash">protoc \
  --dart_out=grpc:lib/generated \
  -I proto \
  proto/banking/banking.proto
</code></pre>
<h3 id="heading-the-data-source-layer">The Data Source Layer</h3>
<pre><code class="language-dart">// lib/features/banking/data/datasources/banking_remote_datasource.dart

import 'package:grpc/grpc.dart';
import '../../../../generated/banking.pb.dart';
import '../../../../generated/banking.pbgrpc.dart';
import '../../../../core/error/app_exception.dart';

class BankingRemoteDataSource {
  late final BankingServiceClient _client;
  late final ClientChannel _channel;

  BankingRemoteDataSource({
    required String host,
    required int port,
    required String authToken,
  }) {
   
    _channel = ClientChannel(
      host,
      port: port,
      options: const ChannelOptions(
        credentials: ChannelCredentials.secure(),
        connectionTimeout: Duration(seconds: 10),
      ),
    );

   
    _client = BankingServiceClient(
      _channel,
      options: CallOptions(
        metadata: {'authorization': 'Bearer $authToken'},
        timeout: const Duration(seconds: 30),
      ),
    );
  }

  Future&lt;LoginResponse&gt; login(String email, String password) async {
    try {
      return await _client.login(
        LoginRequest(email: email, password: password),
      );
    } on GrpcError catch (e) {
      throw _mapGrpcError(e);
    }
  }

  Future&lt;UserProfile&gt; getProfile(String userId) async {
    try {
      return await _client.getProfile(
        ProfileRequest(userId: userId),
      );
    } on GrpcError catch (e) {
      throw _mapGrpcError(e);
    }
  }

  Stream&lt;BalanceResponse&gt; watchBalance(String userId) {
    return _client
        .watchBalance(BalanceRequest(userId: userId))
        .handleError((error) {
      if (error is GrpcError) throw _mapGrpcError(error);
      throw error;
    });
  }

  Stream&lt;Transaction&gt; streamTransactions(String userId, {int limit = 20}) {
    return _client
        .streamTransactions(
          TransactionRequest(userId: userId, limit: limit),
        )
        .handleError((error) {
      if (error is GrpcError) throw _mapGrpcError(error);
      throw error;
    });
  }

  Future&lt;UploadResponse&gt; uploadDocument(
    List&lt;Uint8List&gt; chunks,
    String documentType,
  ) async {
    try {
      Stream&lt;DocumentChunk&gt; chunkStream() async* {
        for (int i = 0; i &lt; chunks.length; i++) {
          yield DocumentChunk(
            data: chunks[i],
            documentType: documentType,
            chunkIndex: i,
            isLast: i == chunks.length - 1,
          );
        }
      }
      return await _client.uploadDocument(chunkStream());
    } on GrpcError catch (e) {
      throw _mapGrpcError(e);
    }
  }

  ResponseStream&lt;ChatMessage&gt; startChat(Stream&lt;ChatMessage&gt; outgoing) {
    return _client.chat(outgoing);
  }

  Future&lt;void&gt; dispose() async {
    await _channel.shutdown();
  }

  AppException _mapGrpcError(GrpcError error) {
    switch (error.code) {
      case StatusCode.unauthenticated:
        return AppException.unauthorized(
          message: error.message ?? 'Unauthorized',
        );
      case StatusCode.notFound:
        return AppException.notFound(
          message: error.message ?? 'Not found',
        );
      case StatusCode.deadlineExceeded:
        return AppException.timeout(message: 'Request timed out');
      case StatusCode.unavailable:
        return AppException.serverUnavailable(
          message: 'Service unavailable',
        );
      default:
        return AppException.unknown(
          message: error.message ?? 'Unknown error',
        );
    }
  }
}
</code></pre>
<p>Let's walk through the important decisions in this data source.</p>
<h4 id="heading-the-channel">The Channel:</h4>
<pre><code class="language-csharp">_channel = ClientChannel(
  host,
  port: port,
  options: const ChannelOptions(
    credentials: ChannelCredentials.secure(),
    connectionTimeout: Duration(seconds: 10),
  ),
);
</code></pre>
<p>The channel is the physical HTTP/2 connection to the server. You create it once and reuse it for every call. <code>ChannelCredentials.secure()</code> enables TLS encryption. <code>connectionTimeout</code> prevents the app from waiting indefinitely if the server is unreachable.</p>
<p>The channel is the core of gRPC's performance advantage. A single persistent channel multiplexes all requests through one HTTP/2 connection. Creating a new channel per request would eliminate this advantage entirely and perform worse than REST.</p>
<h4 id="heading-authentication-via-metadata">Authentication via Metadata:</h4>
<pre><code class="language-dart">_client = BankingServiceClient(
  _channel,
  options: CallOptions(
    metadata: {'authorization': 'Bearer $authToken'},
    timeout: const Duration(seconds: 30),
  ),
);
</code></pre>
<p>gRPC uses metadata (key-value pairs) for what HTTP uses headers. Passing the auth token as metadata on the <code>CallOptions</code> means every single call made through this client automatically includes the Authorization metadata. You write it once. It applies everywhere.</p>
<h4 id="heading-error-mapping">Error Mapping:</h4>
<pre><code class="language-csharp">AppException _mapGrpcError(GrpcError error) {
  switch (error.code) {
    case StatusCode.unauthenticated:
      return AppException.unauthorized(...);
    case StatusCode.deadlineExceeded:
      return AppException.timeout(...);
    ...
  }
}
</code></pre>
<p>gRPC has its own set of status codes similar to HTTP status codes but not identical. Mapping them to your application's exception types at the data source layer means the rest of your code (use cases, notifiers, widgets) never deals with gRPC-specific errors directly. Your domain layer stays clean and framework-independent.</p>
<h3 id="heading-the-repository-layer">The Repository Layer</h3>
<pre><code class="language-dart">
abstract class BankingRepository {
  Future&lt;Result&lt;UserProfile, AppException&gt;&gt; getProfile(String userId);
  Stream&lt;BalanceResponse&gt; watchBalance(String userId);
  Stream&lt;Transaction&gt; streamTransactions(String userId);
  Future&lt;Result&lt;UploadResponse, AppException&gt;&gt; uploadDocument(
    List&lt;Uint8List&gt; chunks,
    String documentType,
  );
}


class BankingRepositoryImpl implements BankingRepository {
  final BankingRemoteDataSource _dataSource;

  BankingRepositoryImpl(this._dataSource);

  @override
  Future&lt;Result&lt;UserProfile, AppException&gt;&gt; getProfile(String userId) async {
    try {
      final profile = await _dataSource.getProfile(userId);
      return Result.success(profile);
    } on AppException catch (e) {
      return Result.failure(e);
    }
  }

  @override
  Stream&lt;BalanceResponse&gt; watchBalance(String userId) {
    return _dataSource.watchBalance(userId);
  }

  @override
  Stream&lt;Transaction&gt; streamTransactions(String userId) {
    return _dataSource.streamTransactions(userId);
  }

  @override
  Future&lt;Result&lt;UploadResponse, AppException&gt;&gt; uploadDocument(
    List&lt;Uint8List&gt; chunks,
    String documentType,
  ) async {
    try {
      final response = await _dataSource.uploadDocument(chunks, documentType);
      return Result.success(response);
    } on AppException catch (e) {
      return Result.failure(e);
    }
  }
}
</code></pre>
<h3 id="heading-the-riverpod-providers">The Riverpod Providers</h3>
<pre><code class="language-dart">
part 'banking_providers.g.dart';

@riverpod
Stream&lt;BalanceResponse&gt; balanceStream(BalanceStreamRef ref, String userId) {
  final repository = ref.watch(bankingRepositoryProvider);
  return repository.watchBalance(userId);
}

@riverpod
Stream&lt;Transaction&gt; transactionStream(
  TransactionStreamRef ref,
  String userId,
) {
  final repository = ref.watch(bankingRepositoryProvider);
  return repository.streamTransactions(userId);
}
</code></pre>
<p>With Riverpod, a provider that returns a <code>Stream</code> automatically becomes an <code>AsyncValue</code> that widgets can watch. Every new value pushed from the gRPC server stream triggers a widget rebuild automatically.</p>
<h3 id="heading-the-ui">The UI</h3>
<pre><code class="language-dart">// lib/features/banking/presentation/pages/dashboard_page.dart
class DashboardPage extends ConsumerWidget {
  final String userId;

  const DashboardPage({required this.userId, super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final balanceAsync = ref.watch(balanceStreamProvider(userId));
    final transactionsAsync = ref.watch(transactionStreamProvider(userId));

    return Scaffold(
      appBar: AppBar(title: const Text('Dashboard')),
      body: Column(
        children: [
          balanceAsync.when(
            data: (balance) =&gt; BalanceCard(
              amount: balance.balance,
              currency: balance.currency,
            ),
            loading: () =&gt; const BalanceShimmer(),
            error: (e, _) =&gt; ErrorCard(message: e.toString()),
          ),

          const SizedBox(height: 24),

          Expanded(
            child: transactionsAsync.when(
              data: (transaction) =&gt; TransactionTile(
                transaction: transaction,
              ),
              loading: () =&gt; const TransactionShimmer(),
              error: (e, _) =&gt; ErrorCard(message: e.toString()),
            ),
          ),
        ],
      ),
    );
  }
}
</code></pre>
<p>Both the balance and transactions arrive through gRPC server streams. Both update in real-time as the server pushes new data. Both are handled identically through Riverpod's <code>AsyncValue</code> pattern. One framework with all patterns covered.</p>
<h2 id="heading-production-concerns">Production Concerns</h2>
<h3 id="heading-authentication-with-interceptors">Authentication with Interceptors</h3>
<p>For more granular authentication control, such as refreshing an expired token and retrying automatically, you implement a client interceptor:</p>
<pre><code class="language-dart">class AuthInterceptor extends ClientInterceptor {
  final TokenService _tokenService;

  AuthInterceptor(this._tokenService);

  @override
  ResponseFuture&lt;R&gt; interceptUnary&lt;Q, R&gt;(
    ClientMethod&lt;Q, R&gt; method,
    Q request,
    CallOptions options,
    ClientUnaryInvoker&lt;Q, R&gt; invoker,
  ) {
    final token = _tokenService.currentToken;
    final authenticatedOptions = options.mergedWith(
      CallOptions(metadata: {'authorization': 'Bearer $token'}),
    );
    return invoker(method, request, authenticatedOptions);
  }

  @override
  ResponseStream&lt;R&gt; interceptServerStreaming&lt;Q, R&gt;(
    ClientMethod&lt;Q, R&gt; method,
    Q request,
    CallOptions options,
    ClientServerStreamingInvoker&lt;Q, R&gt; invoker,
  ) {
    final token = _tokenService.currentToken;
    final authenticatedOptions = options.mergedWith(
      CallOptions(metadata: {'authorization': 'Bearer $token'}),
    );
    return invoker(method, request, authenticatedOptions);
  }
}
</code></pre>
<p>Pass the interceptor when creating the client:</p>
<pre><code class="language-dart">_client = BankingServiceClient(
  _channel,
  interceptors: [AuthInterceptor(tokenService)],
);
</code></pre>
<p>The interceptor fires on every call automatically. The data source code never touches auth logic directly.</p>
<h3 id="heading-error-handling-grpc-status-codes">Error Handling: gRPC Status Codes</h3>
<p>gRPC defines a standard set of status codes that every implementation follows:</p>
<table>
<thead>
<tr>
<th>Status Code</th>
<th>Meaning</th>
<th>Recommended Action</th>
</tr>
</thead>
<tbody><tr>
<td>OK (0)</td>
<td>Success</td>
<td>Use the response</td>
</tr>
<tr>
<td>CANCELLED (1)</td>
<td>Client cancelled the call</td>
<td>Ignore or log</td>
</tr>
<tr>
<td>UNKNOWN (2)</td>
<td>Unknown server error</td>
<td>Show generic error</td>
</tr>
<tr>
<td>INVALID_ARGUMENT (3)</td>
<td>Bad request data</td>
<td>Show validation error</td>
</tr>
<tr>
<td>DEADLINE_EXCEEDED (4)</td>
<td>Call timed out</td>
<td>Retry or show timeout message</td>
</tr>
<tr>
<td>NOT_FOUND (5)</td>
<td>Resource does not exist</td>
<td>Show not found UI</td>
</tr>
<tr>
<td>ALREADY_EXISTS (6)</td>
<td>Duplicate resource</td>
<td>Show conflict message</td>
</tr>
<tr>
<td>PERMISSION_DENIED (7)</td>
<td>Insufficient permissions</td>
<td>Show access denied</td>
</tr>
<tr>
<td>UNAUTHENTICATED (16)</td>
<td>Invalid or expired credentials</td>
<td>Navigate to login</td>
</tr>
<tr>
<td>RESOURCE_EXHAUSTED (8)</td>
<td>Rate limited</td>
<td>Back off and retry</td>
</tr>
<tr>
<td>UNAVAILABLE (14)</td>
<td>Server temporarily down</td>
<td>Show offline message</td>
</tr>
</tbody></table>
<pre><code class="language-dart">AppException _mapGrpcError(GrpcError error) {
  switch (error.code) {
    case StatusCode.unauthenticated:
      return AppException.unauthorized(message: 'Session expired');
    case StatusCode.permissionDenied:
      return AppException.forbidden(message: 'Access denied');
    case StatusCode.notFound:
      return AppException.notFound(message: error.message ?? 'Not found');
    case StatusCode.deadlineExceeded:
      return AppException.timeout(message: 'Request timed out');
    case StatusCode.unavailable:
      return AppException.serverUnavailable(message: 'Service unavailable');
    case StatusCode.resourceExhausted:
      return AppException.rateLimited(message: 'Too many requests');
    case StatusCode.invalidArgument:
      return AppException.validation(
        message: error.message ?? 'Invalid input',
      );
    default:
      return AppException.unknown(
        message: error.message ?? 'An error occurred',
      );
  }
}
</code></pre>
<h3 id="heading-deadlines-and-timeouts">Deadlines and Timeouts</h3>
<p>Every gRPC call should have a deadline. Without deadlines, a slow server can make your app hang indefinitely.</p>
<p>Per-call deadline:</p>
<pre><code class="language-dart">Future&lt;UserProfile&gt; getProfile(String userId) async {
  return await _client.getProfile(
    ProfileRequest(userId: userId),
    options: CallOptions(timeout: const Duration(seconds: 10)),
  );
}
</code></pre>
<p>Default deadline for all calls:</p>
<pre><code class="language-dart">_client = BankingServiceClient(
  _channel,
  options: CallOptions(
    timeout: const Duration(seconds: 30),
    metadata: {'authorization': 'Bearer $authToken'},
  ),
);
</code></pre>
<p>When the deadline is exceeded, the call throws a <code>GrpcError</code> with <code>StatusCode.deadlineExceeded</code>, which your error mapper handles appropriately.</p>
<h3 id="heading-logging-interceptor">Logging Interceptor</h3>
<pre><code class="language-dart">class LoggingInterceptor extends ClientInterceptor {
  @override
  ResponseFuture&lt;R&gt; interceptUnary&lt;Q, R&gt;(
    ClientMethod&lt;Q, R&gt; method,
    Q request,
    CallOptions options,
    ClientUnaryInvoker&lt;Q, R&gt; invoker,
  ) {
    final stopwatch = Stopwatch()..start();
    debugPrint('[gRPC] --&gt; ${method.path}');

    final response = invoker(method, request, options);

    response.then((_) {
      stopwatch.stop();
      debugPrint(
        '[gRPC] &lt;-- ${method.path} (${stopwatch.elapsedMilliseconds}ms)',
      );
    }).catchError((error) {
      stopwatch.stop();
      debugPrint(
        '[gRPC] ERROR ${method.path}: $error (${stopwatch.elapsedMilliseconds}ms)',
      );
    });

    return response;
  }
}
</code></pre>
<h2 id="heading-grpc-vs-rest-vs-websockets-when-to-use-what">gRPC vs REST vs WebSockets: When to Use What</h2>
<h3 id="heading-when-to-use-rest">When to Use REST</h3>
<p>The API is consumed by third-party developers or external partners. JSON over HTTP is the universal language that every developer in every language can access immediately without learning new tooling.</p>
<p>The operation is simple request-response with no streaming requirements and only one client platform. REST is simpler to implement, simpler to debug, and simpler to test for straightforward CRUD operations.</p>
<p>Public documentation and human readability matter. REST with OpenAPI/Swagger gives you browsable, testable documentation that developers can explore in a browser.</p>
<p>Caching is important. REST GET responses can be cached at every layer: CDN, reverse proxy, browser cache. gRPC requests can't leverage standard HTTP caching.</p>
<h3 id="heading-use-websockets-when">Use WebSockets When</h3>
<p>You need true bidirectional real-time communication and gRPC isn't already in your stack. Chat applications, multiplayer games, and collaborative tools where both sides need to speak freely are natural WebSocket use cases.</p>
<p>Browser support without a proxy layer is required. WebSockets work natively in every modern browser. gRPC in the browser requires gRPC-Web and a proxy layer.</p>
<h3 id="heading-when-to-use-grpc">When to Use gRPC</h3>
<p>Multiple platform teams share the same service contract. When Flutter, React, Go, and Python services all call the same backend, a <code>.proto</code> file enforced by the compiler prevents contract drift across every team.</p>
<p>Large payloads are called by many internal applications. The more fields in the payload and the more applications consuming it, the stronger the case for protobuf's binary encoding and generated clients.</p>
<p>Network conditions are variable and payload size matters. Users on 2G or 3G connections benefit directly from protobuf's compact binary format. The same data in protobuf can be 3 to 10 times smaller than JSON, translating to faster load times and lower data consumption for users on limited data plans.</p>
<p>Real-time streaming is required and you want one unified framework for all communication patterns. gRPC's four patterns cover every scenario without requiring a separate WebSocket server alongside your API.</p>
<p>Service-to-service communication at high frequency is involved. Two internal services calling each other thousands of times per second over a persistent multiplexed HTTP/2 connection with binary protobuf encoding will significantly outperform REST with JSON over HTTP/1.1.</p>
<h2 id="heading-the-hybrid-architecture">The Hybrid Architecture</h2>
<p>The mature engineering decision is not choosing gRPC over REST or REST over gRPC. It's knowing where each belongs and using both deliberately.</p>
<p>Most organizations of meaningful scale end up with a hybrid:</p>
<p>The public REST API serves external consumers who need simplicity and JSON. The internal gRPC network handles high-frequency, high-performance service-to-service calls. The mobile gRPC endpoints give Flutter clients real-time capabilities over efficient binary connections.</p>
<p>Each layer uses the right tool for its specific requirements. No ideological commitment to one protocol. Pure engineering pragmatism.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Remote Procedure Calls began with a simple observation: network communication shouldn't require developers to think about network communication. Calling a function on another machine should feel like calling a function on your own.</p>
<p>Protocol Buffers took this further by solving the data problem. JSON is readable but verbose. Binary encoding with a compiler-enforced schema produces payloads that are smaller, faster to parse, and guaranteed to match the contract every team agreed on. For users on slow networks and internal systems processing millions of requests daily, this efficiency is a business advantage.</p>
<p>gRPC combined RPC semantics, Protocol Buffer encoding, and HTTP/2 transport into a framework that supports four distinct communication patterns: unary request-response, server streaming, client streaming, and bidirectional streaming. All from the same generated client, using the same persistent connection, and enforced by the same <code>.proto</code> contract.</p>
<p>The organizational practice of a shared protobuf repository transforms gRPC from a technical tool into an engineering discipline. Contract changes go through review. Breaking changes are caught by the compiler. Every team generates their own strongly typed client from the same source of truth and stays in sync automatically, regardless of programming language.</p>
<p>In Flutter specifically, gRPC server streams integrate naturally with Dart's <code>Stream</code> type and Riverpod's stream providers. Real-time balance updates and live transaction feeds that would require polling with REST or a separate WebSocket implementation become simple stream subscriptions. The server pushes, the widget listens, and nothing else is required.</p>
<p>The decision of when to use gRPC versus REST versus WebSockets isn't about preference. It's about matching the tool to the requirement. Public APIs belong behind REST. High-frequency internal service communication belongs on gRPC. Large payloads consumed by many internal systems belong in protobuf. Real-time bidirectional features belong on gRPC streaming. Users on variable networks deserve the smallest payloads you can give them.</p>
<p>Understanding all of these tools, understanding why they exist, and knowing when to reach for each one is what separates engineers who use tools from engineers who think in systems.</p>
<p>Happy Coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build a Dropbox-like Distributed File Storage System Using MinIO and gRPC ]]>
                </title>
                <description>
                    <![CDATA[ In this tutorial, I’ll guide you through building a distributed file storage system inspired by Dropbox, using MinIO (an open-source, S3-compatible object storage server) and gRPC. The goal is to create a system that can store, replicate, and manage ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-build-a-dropbox-like-distributed-file-storage-system-using-minio-and-grpc/</link>
                <guid isPermaLink="false">6733b4dc73da063aa0407447</guid>
                
                    <category>
                        <![CDATA[ #minio ]]>
                    </category>
                
                    <category>
                        <![CDATA[ gRPC ]]>
                    </category>
                
                    <category>
                        <![CDATA[ storage ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Docker ]]>
                    </category>
                
                    <category>
                        <![CDATA[ minio object storage ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Birkaran Sachdev ]]>
                </dc:creator>
                <pubDate>Tue, 12 Nov 2024 20:04:44 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/GWQ67jjUg9g/upload/e37080969188b807a15d6ebdaf813fa2.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this tutorial, I’ll guide you through building a <strong>distributed file storage system</strong> inspired by Dropbox, using MinIO (an open-source, S3-compatible object storage server) and gRPC. The goal is to create a system that can <strong>store, replicate, and manage files</strong> across multiple nodes, ensuring data availability and resilience.</p>
<p>We'll implement core features like file replication, metadata management, and versioning, all while demonstrating how to achieve eventual consistency in a distributed environment. By the end, you'll have a fully functional distributed file storage system that can handle high traffic, optimize storage, and ensure data integrity.</p>
<h3 id="heading-what-you-will-learn">What You Will Learn</h3>
<ul>
<li><p>How to set up <strong>MinIO</strong> for distributed object storage.</p>
</li>
<li><p>How to use <strong>gRPC</strong> for efficient client-server communication.</p>
</li>
<li><p>How to implement <strong>file replication</strong> and <strong>metadata management</strong>.</p>
</li>
<li><p>How to understand <strong>data consistency</strong> in a distributed system.</p>
</li>
<li><p>How to use <strong>Docker</strong> to deploy a scalable, distributed architecture.</p>
</li>
</ul>
<h3 id="heading-prerequisites">Prerequisites</h3>
<p>Before starting, ensure you have the following installed:</p>
<ul>
<li><p>Node.js (v14 or higher)</p>
</li>
<li><p>MinIO</p>
</li>
<li><p>gRPC and gRPC-tools</p>
</li>
<li><p>Docker</p>
</li>
</ul>
<p>You’ll also need to have a basic understanding of Node.js, object storage, and distributed systems.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-project-overview">Project Overview</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-1-setting-up-the-project">Step 1: Setting Up the Project</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-2-setting-up-minio-distributed-storage-nodes">Step 2: Setting Up MinIO Distributed Storage Nodes</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-3-defining-the-grpc-protocol">Step 3: Defining the gRPC Protocol</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-4-implementing-the-grpc-server">Step 4: Implementing the gRPC Server</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-5-creating-the-client">Step 5: Creating the Client</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-6-running-the-system">Step 6: Running the System</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion-what-youve-learned">Conclusion: What You’ve Learned</a></p>
</li>
</ul>
<h2 id="heading-project-overview">Project Overview</h2>
<p>We'll build a <strong>distributed file storage system</strong> where:</p>
<ol>
<li><p>Users can upload and download files.</p>
</li>
<li><p>Files are replicated across multiple storage nodes to ensure high availability.</p>
</li>
<li><p>Metadata (like file names, upload times, and versions) is managed centrally.</p>
</li>
<li><p>The system handles <strong>eventual consistency</strong> by syncing file updates across nodes.</p>
</li>
</ol>
<h3 id="heading-system-architecture">System Architecture</h3>
<p>Our system will consist of:</p>
<ol>
<li><p><strong>gRPC Server</strong>: Manages file uploads, downloads, and metadata.</p>
</li>
<li><p><strong>MinIO Distributed Storage Nodes</strong>: Handles object storage and replication.</p>
</li>
<li><p><strong>Client Interface</strong>: Allows users to interact with the system via HTTP.</p>
</li>
</ol>
<h2 id="heading-step-1-setting-up-the-project">Step 1: Setting Up the Project</h2>
<p>Create a new directory for the project and initialize a Node.js application:</p>
<pre><code class="lang-javascript">mkdir distributed-file-storage
cd distributed-file-storage
npm init -y
</code></pre>
<p>Now, install the necessary dependencies:</p>
<pre><code class="lang-javascript">npm install grpc @grpc/grpc-js @grpc/proto-loader express multer dotenv minio
</code></pre>
<ul>
<li><p><strong>grpc</strong>: For building gRPC server and client.</p>
</li>
<li><p><strong>@grpc/proto-loader</strong>: Loads gRPC protocol files.</p>
</li>
<li><p><strong>express</strong>: For the client-side HTTP server.</p>
</li>
<li><p><strong>multer</strong>: For handling file uploads.</p>
</li>
<li><p><strong>dotenv</strong>: For managing environment variables.</p>
</li>
<li><p><strong>minio</strong>: MinIO client for interacting with storage nodes.</p>
</li>
</ul>
<p>Create a <strong>.env</strong> file with the following content:</p>
<pre><code class="lang-javascript">MINIO_ENDPOINT_1=localhost:<span class="hljs-number">9001</span>
MINIO_ACCESS_KEY=minioadmin
MINIO_SECRET_KEY=minioadmin
PORT=<span class="hljs-number">5000</span>
</code></pre>
<h2 id="heading-step-2-setting-up-minio-distributed-storage-nodes">Step 2: Setting Up MinIO Distributed Storage Nodes</h2>
<p>We'll use <strong>Docker</strong> to run multiple MinIO instances, simulating a distributed environment. Run the following commands to set up three MinIO containers:</p>
<pre><code class="lang-javascript">docker run -p <span class="hljs-number">9001</span>:<span class="hljs-number">9000</span> --name minio1 -e <span class="hljs-string">"MINIO_ACCESS_KEY=minioadmin"</span> -e <span class="hljs-string">"MINIO_SECRET_KEY=minioadmin"</span> -d minio/minio server /data
docker run -p <span class="hljs-number">9002</span>:<span class="hljs-number">9000</span> --name minio2 -e <span class="hljs-string">"MINIO_ACCESS_KEY=minioadmin"</span> -e <span class="hljs-string">"MINIO_SECRET_KEY=minioadmin"</span> -d minio/minio server /data
docker run -p <span class="hljs-number">9003</span>:<span class="hljs-number">9000</span> --name minio3 -e <span class="hljs-string">"MINIO_ACCESS_KEY=minioadmin"</span> -e <span class="hljs-string">"MINIO_SECRET_KEY=minioadmin"</span> -d minio/minio server /data
</code></pre>
<p>These commands will start three MinIO nodes, each listening on a different port.</p>
<h2 id="heading-step-3-defining-the-grpc-protocol">Step 3: Defining the gRPC Protocol</h2>
<p>Create a new folder named <strong>protos</strong> and inside it, create a file called <strong>storage.proto</strong>:</p>
<pre><code class="lang-javascript">syntax = <span class="hljs-string">"proto3"</span>;

service FileStorage {
  rpc UploadFile(stream FileRequest) returns (UploadResponse);
  rpc DownloadFile(FileDownloadRequest) returns (stream FileResponse);
  rpc GetMetadata(FileMetadataRequest) returns (MetadataResponse);
}

message FileRequest {
  bytes fileData = <span class="hljs-number">1</span>;
  string fileName = <span class="hljs-number">2</span>;
}

message UploadResponse {
  string message = <span class="hljs-number">1</span>;
}

message FileDownloadRequest {
  string fileName = <span class="hljs-number">1</span>;
}

message FileResponse {
  bytes fileData = <span class="hljs-number">1</span>;
}

message FileMetadataRequest {
  string fileName = <span class="hljs-number">1</span>;
}

message MetadataResponse {
  string fileName = <span class="hljs-number">1</span>;
  string uploadTime = <span class="hljs-number">2</span>;
  string version = <span class="hljs-number">3</span>;
}
</code></pre>
<ul>
<li><p><strong>UploadFile</strong>: Streams file data from the client to the server.</p>
</li>
<li><p><strong>DownloadFile</strong>: Streams file data from the server to the client.</p>
</li>
<li><p><strong>GetMetadata</strong>: Retrieves metadata like file name, upload time, and version.</p>
</li>
</ul>
<h2 id="heading-step-4-implementing-the-grpc-server">Step 4: Implementing the gRPC Server</h2>
<p>Create a file called <strong>server.js</strong>:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">require</span>(<span class="hljs-string">'dotenv'</span>).config();
<span class="hljs-keyword">const</span> grpc = <span class="hljs-built_in">require</span>(<span class="hljs-string">'@grpc/grpc-js'</span>);
<span class="hljs-keyword">const</span> protoLoader = <span class="hljs-built_in">require</span>(<span class="hljs-string">'@grpc/proto-loader'</span>);
<span class="hljs-keyword">const</span> Minio = <span class="hljs-built_in">require</span>(<span class="hljs-string">'minio'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);
<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'path'</span>);

<span class="hljs-keyword">const</span> packageDefinition = protoLoader.loadSync(<span class="hljs-string">'protos/storage.proto'</span>);
<span class="hljs-keyword">const</span> storageProto = grpc.loadPackageDefinition(packageDefinition).FileStorage;

<span class="hljs-comment">// Set up MinIO clients for each node</span>
<span class="hljs-keyword">const</span> minioClients = [
  <span class="hljs-keyword">new</span> Minio.Client({
    <span class="hljs-attr">endPoint</span>: process.env.MINIO_ENDPOINT_1.split(<span class="hljs-string">':'</span>)[<span class="hljs-number">0</span>],
    <span class="hljs-attr">port</span>: <span class="hljs-built_in">parseInt</span>(process.env.MINIO_ENDPOINT_1.split(<span class="hljs-string">':'</span>)[<span class="hljs-number">1</span>]),
    <span class="hljs-attr">accessKey</span>: process.env.MINIO_ACCESS_KEY,
    <span class="hljs-attr">secretKey</span>: process.env.MINIO_SECRET_KEY,
    <span class="hljs-attr">useSSL</span>: <span class="hljs-literal">false</span>,
  })
];

<span class="hljs-comment">// Upload file to MinIO</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">uploadFile</span>(<span class="hljs-params">call, callback</span>) </span>{
  <span class="hljs-keyword">const</span> chunks = [];
  call.on(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =&gt;</span> chunks.push(chunk.fileData));
  call.on(<span class="hljs-string">'end'</span>, <span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">const</span> buffer = Buffer.concat(chunks);
    <span class="hljs-keyword">const</span> fileName = call.metadata.get(<span class="hljs-string">'fileName'</span>)[<span class="hljs-number">0</span>];

    <span class="hljs-comment">// Store file in MinIO</span>
    <span class="hljs-keyword">const</span> client = minioClients[<span class="hljs-number">0</span>];
    <span class="hljs-keyword">await</span> client.putObject(<span class="hljs-string">'files'</span>, fileName, buffer);
    callback(<span class="hljs-literal">null</span>, { <span class="hljs-attr">message</span>: <span class="hljs-string">`File <span class="hljs-subst">${fileName}</span> uploaded successfully`</span> });
  });
}

<span class="hljs-comment">// Download file from MinIO</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">downloadFile</span>(<span class="hljs-params">call</span>) </span>{
  <span class="hljs-keyword">const</span> { fileName } = call.request;
  <span class="hljs-keyword">const</span> client = minioClients[<span class="hljs-number">0</span>];

  client.getObject(<span class="hljs-string">'files'</span>, fileName, <span class="hljs-function">(<span class="hljs-params">err, stream</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">return</span> call.emit(<span class="hljs-string">'error'</span>, err);
    stream.on(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =&gt;</span> call.write({ <span class="hljs-attr">fileData</span>: chunk }));
    stream.on(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =&gt;</span> call.end());
  });
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">main</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> server = <span class="hljs-keyword">new</span> grpc.Server();
  server.addService(storageProto.FileStorage.service, { uploadFile, downloadFile });
  server.bindAsync(<span class="hljs-string">'0.0.0.0:5000'</span>, grpc.ServerCredentials.createInsecure(), <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'gRPC server running on port 5000'</span>);
    server.start();
  });
}

main();
</code></pre>
<p>Here’s what’s going on in this code:</p>
<ol>
<li><p><strong>uploadFile</strong>: Handles file uploads by streaming data to the server and storing it in MinIO.</p>
</li>
<li><p><strong>downloadFile</strong>: Streams the requested file back to the client from MinIO.</p>
</li>
<li><p><strong>MinIO Clients</strong>: We set up multiple MinIO clients to handle distributed storage.</p>
</li>
</ol>
<h2 id="heading-step-5-creating-the-client">Step 5: Creating the Client</h2>
<p>Create a file named <strong>client.js</strong>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> grpc = <span class="hljs-built_in">require</span>(<span class="hljs-string">'@grpc/grpc-js'</span>);
<span class="hljs-keyword">const</span> protoLoader = <span class="hljs-built_in">require</span>(<span class="hljs-string">'@grpc/proto-loader'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);

<span class="hljs-keyword">const</span> packageDefinition = protoLoader.loadSync(<span class="hljs-string">'protos/storage.proto'</span>);
<span class="hljs-keyword">const</span> storageProto = grpc.loadPackageDefinition(packageDefinition).FileStorage;
<span class="hljs-keyword">const</span> client = <span class="hljs-keyword">new</span> storageProto(<span class="hljs-string">'localhost:5000'</span>, grpc.credentials.createInsecure());

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">uploadFile</span>(<span class="hljs-params">filePath</span>) </span>{
  <span class="hljs-keyword">const</span> call = client.uploadFile();
  <span class="hljs-keyword">const</span> fileName = filePath.split(<span class="hljs-string">'/'</span>).pop();
  <span class="hljs-keyword">const</span> stream = fs.createReadStream(filePath);

  stream.on(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =&gt;</span> call.write({ <span class="hljs-attr">fileData</span>: chunk }));
  stream.on(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =&gt;</span> call.end());
  call.on(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(response.message));
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">downloadFile</span>(<span class="hljs-params">fileName</span>) </span>{
  <span class="hljs-keyword">const</span> call = client.downloadFile({ fileName });
  <span class="hljs-keyword">const</span> writeStream = fs.createWriteStream(<span class="hljs-string">`downloaded_<span class="hljs-subst">${fileName}</span>`</span>);

  call.on(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =&gt;</span> writeStream.write(chunk.fileData));
  call.on(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Downloaded <span class="hljs-subst">${fileName}</span>`</span>));
}

uploadFile(<span class="hljs-string">'test.txt'</span>);  <span class="hljs-comment">// Example usage</span>
</code></pre>
<h2 id="heading-step-6-running-the-system">Step 6: Running the System</h2>
<ol>
<li><p><strong>Start the gRPC Server</strong>:</p>
<pre><code class="lang-javascript"> node server.js
</code></pre>
</li>
<li><p><strong>Run the Client</strong>:</p>
<pre><code class="lang-javascript"> node client.js
</code></pre>
</li>
</ol>
<h2 id="heading-conclusion-what-youve-learned">Conclusion: What You’ve Learned</h2>
<p>Congratulations! You've built a distributed file storage system using <strong>MinIO</strong> and <strong>gRPC</strong>. In this tutorial, you learned how to:</p>
<ol>
<li><p>Set up a <strong>distributed object storage</strong> system using MinIO.</p>
</li>
<li><p>Use <strong>gRPC</strong> to handle file uploads, downloads, and metadata management.</p>
</li>
<li><p>Implement <strong>file replication</strong> and <strong>eventual consistency</strong> across multiple nodes.</p>
</li>
<li><p>Utilize <strong>Docker</strong> to simulate a scalable distributed environment.</p>
</li>
</ol>
<h3 id="heading-next-steps">Next Steps:</h3>
<ol>
<li><p><strong>Add File Versioning</strong>: Store multiple versions of files for rollback.</p>
</li>
<li><p><strong>Implement Authentication</strong>: Secure your gRPC endpoints with JWT.</p>
</li>
<li><p><strong>Deploy with Kubernetes</strong>: Scale your system across multiple nodes for high availability.</p>
</li>
</ol>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
