Updated November 2026: Updated for tonic 0.14, prost 0.14 and Rust edition 2024: codegen now lives in tonic-prost-build, the runtime codec in tonic-prost, and the code uses typed enums.

gRPC is my default for service-to-service APIs, and in Rust the go-to crate for it is tonic . In this post, I build the simplest useful gRPC service I can think of, a voting service, plus a client that calls it. Both are generated from the same .proto file.

What is tonic

tonic is a gRPC implementation for Rust built on hyper (HTTP/2) and tokio . It brings code generation that turns standard protocol buffer definitions (.proto) into a server trait and a client stub, using prost for the message types.

Since tonic 0.14, the protobuf pieces are split into their own crates:

  • tonic: the gRPC runtime (server, client, transport)
  • tonic-prost: the prost codec the generated code uses at runtime
  • tonic-prost-build: the build-time codegen you call from build.rs (this used to be tonic_build::compile_protos)

Here is what a single unary call looks like once everything is wired up:

One unary call through the generated client and server

Prerequisites

  • A current Rust toolchain (rustup update). tonic 0.14 needs Rust 1.88 or newer, and cargo new creates edition 2024 projects.
  • protoc, the Protocol Buffers compiler. tonic-prost-build calls it at build time and fails with “Could not find protoc” if it is missing. Install it with brew install protobuf on macOS, apt install protobuf-compiler on Debian/Ubuntu, or grab a release from protobuf.dev . If it lives somewhere unusual, point the PROTOC environment variable at the binary.

Create the client and server projects

The finished code is in the rusty-grpc repository on GitHub . To build it step by step, start with two Cargo projects and a shared folder for the service definition:

BASH
mkdir rusty-grpc && cd rusty-grpc

cargo new server
cargo new client

# shared folder for the service definition
mkdir protos

Define the service

Create protos/voting.proto with the following service definition:

PROTO
syntax = "proto3";
package voting;

service Voting {
  rpc Vote (VotingRequest) returns (VotingResponse);
}

message VotingRequest {
  enum Vote {
    UP = 0;
    DOWN = 1;
  }

  string url = 1;
  Vote vote = 2;
}

message VotingResponse {
  string confirmation = 1;
}

Consumers vote up or down for a url and get a confirmation back. Nothing fancy, but it is enough to see every moving part.

Build the gRPC server

Add dependencies

BASH
cd server

cargo add tonic tonic-prost prost
cargo add tokio -F macros,rt-multi-thread
cargo add tonic-prost-build --build

Your server/Cargo.toml now looks like this:

TOML
[package]
name = "server"
version = "0.1.0"
edition = "2024"

[dependencies]
prost = "0.14.6"
tokio = { version = "1.54.1", features = ["macros", "rt-multi-thread"] }
tonic = "0.14.9"
tonic-prost = "0.14.9"

[build-dependencies]
tonic-prost-build = "0.14.9"

All three runtime crates are required: the generated code derives prost::Message for the message types and uses tonic_prost::ProstCodec to put them on the wire.

Generate the code in build.rs

Create server/build.rs (next to Cargo.toml, not in src):

RUST
fn main() -> Result<(), Box<dyn std::error::Error>> {
    tonic_prost_build::compile_protos("../protos/voting.proto")?;
    Ok(())
}

On every build, this runs protoc and writes voting.rs (messages, the Voting server trait and the VotingClient stub) into Cargo’s OUT_DIR. If you need more control, for example to generate only the server, use tonic_prost_build::configure().build_client(false).compile_protos(&["../protos/voting.proto"], &["../protos"])?.

Implement the service

Replace server/src/main.rs with the following code. tonic::include_proto!("voting") pulls the generated code into a voting module; the argument is the package name from the .proto file.

RUST
use tonic::{Request, Response, Status, transport::Server};
use voting::voting_request::Vote;
use voting::voting_server::{Voting, VotingServer};
use voting::{VotingRequest, VotingResponse};

pub mod voting {
    tonic::include_proto!("voting");
}

#[derive(Debug, Default)]
pub struct VotingService {}

#[tonic::async_trait]
impl Voting for VotingService {
    async fn vote(
        &self,
        request: Request<VotingRequest>,
    ) -> Result<Response<VotingResponse>, Status> {
        let r = request.into_inner();
        let confirmation = match r.vote() {
            Vote::Up => format!("Happy to confirm that you upvoted for {}", r.url),
            Vote::Down => format!("Confirmation that you downvoted for {}", r.url),
        };
        Ok(Response::new(VotingResponse { confirmation }))
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let address = "[::1]:8080".parse()?;
    let voting_service = VotingService::default();

    println!("Voting server listening on {address}");
    Server::builder()
        .add_service(VotingServer::new(voting_service))
        .serve(address)
        .await?;
    Ok(())
}

A few things worth knowing:

  • prost stores enum fields as i32 on the message. The generated r.vote() getter turns that into the typed Vote enum (and falls back to the default, Up, for unknown values), so there is no magic 0/1 matching.
  • The Voting trait is generated with #[tonic::async_trait], so the implementation needs the same attribute.
  • Server::builder() registers the service and serve binds it to the socket and runs until the process stops.

Start the server with cargo run in the server folder:

BASH
cargo run
Voting server listening on [::1]:8080

Build the gRPC client

Add dependencies

The client needs the same crates:

BASH
cd ../client

cargo add tonic tonic-prost prost
cargo add tokio -F macros,rt-multi-thread
cargo add tonic-prost-build --build

Its Cargo.toml matches the server’s, except for name = "client". Create client/build.rs with the same content as on the server:

RUST
fn main() -> Result<(), Box<dyn std::error::Error>> {
    tonic_prost_build::compile_protos("../protos/voting.proto")?;
    Ok(())
}

Call the service

Replace client/src/main.rs. The client asks for a URL and a vote in a loop and calls the server through the generated VotingClient. Anything other than u or d ends the loop.

RUST
use std::io::stdin;

use voting::voting_client::VotingClient;
use voting::voting_request::Vote;
use voting::VotingRequest;

pub mod voting {
    tonic::include_proto!("voting");
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut client = VotingClient::connect("http://[::1]:8080").await?;
    loop {
        println!("\nPlease vote for a particular url");
        let mut url = String::new();
        let mut vote = String::new();
        println!("Please provide a url: ");
        stdin().read_line(&mut url)?;
        println!("Please vote (d)own or (u)p: ");
        stdin().read_line(&mut vote)?;
        let vote = match vote.trim().to_lowercase().chars().next() {
            Some('u') => Vote::Up,
            Some('d') => Vote::Down,
            _ => break,
        };
        let request = tonic::Request::new(VotingRequest {
            url: url.trim().to_string(),
            vote: vote.into(),
        });
        let response = client.vote(request).await?;
        println!("Got: '{}' from service", response.into_inner().confirmation);
    }
    Ok(())
}

vote.into() converts the typed enum into the i32 the message field expects. VotingClient::connect takes a URI with a scheme; http:// means plain-text HTTP/2 (h2c), which is what the server above speaks.

Run it

With the server still running, invoke cargo run in the client folder:

BASH
cargo run

Please vote for a particular url
Please provide a url:
https://rust-lang.org
Please vote (d)own or (u)p:
u
Got: 'Happy to confirm that you upvoted for https://rust-lang.org' from service

Please vote for a particular url
Please provide a url:
https://thorsten-hans.com
Please vote (d)own or (u)p:
d
Got: 'Confirmation that you downvoted for https://thorsten-hans.com' from service

Combine client and server in one package

Client and server share all dependencies and the build.rs, so you can also put both into a single package with two [[bin]] targets. I kept them separate here to keep the steps in order.

For production services, add tonic-health for the standard gRPC health checking service and tonic-reflection so tools like grpcurl can discover your services without the .proto file. If you want to run the server in the cloud, see how to expose gRPC services in Azure Container Apps .