Serving gRPC with tonic beside Axum

Learn what gRPC is, how to define a service in a proto file, generate the code with tonic, and run the gRPC server next to an Axum HTTP server in one program

gRPC is a way for programs to call each other over the network as if they were calling a function. A service is defined once, in a .proto file, and code is generated from that definition for the server and the client. The tonic crate is the Rust implementation of gRPC, built on Tokio, and it can run next to an Axum server in the same program: Axum answers HTTP requests from browsers and clients, and tonic answers gRPC calls from other services. This page builds both, runs them side by side, and calls the gRPC service with a real client.

Where This Fits

HTTP with JSON is the right shape for browsers and for public APIs, because every client speaks it. Between services, inside one system, the needs are different: the callers are programs, not people, the contract is fixed, and the traffic is heavy. gRPC fits that shape. The contract is a file both sides share, the messages are binary instead of text, and the client is generated code instead of hand written HTTP calls. A service that talks to a browser keeps its Axum routes. A service that talks to another service adds a gRPC endpoint beside them.

Think of a restaurant with two counters. The front counter serves walk-in customers who order in plain language. The back counter serves the delivery kitchen, which orders by ticket number from a fixed menu. Both counters are the same kitchen. The front counter is Axum. The back counter is tonic.

The Smallest Working Version

A gRPC service needs three things: a .proto file that defines it, a build script that generates Rust code from that file, and a program that serves the generated service. The protoc compiler must be installed first, because the build script calls it to read the .proto file.

apt-get install -y protobuf-compiler
protoc --version

The version used to check this page was libprotoc 3.21.12. Create the project with the tonic crates. The versions matter here, because tonic 0.14 changed how code generation is set up: the proto compilation lives in tonic-prost-build, the runtime codec lives in tonic-prost, and the old tonic-build crate no longer compiles .proto files.

Cargo.toml
[package]
name = "greeter-service"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tonic = "0.14"
tonic-prost = "0.14"
prost = "0.14"

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

The .proto file defines one service with one method. Protocol Buffers, the format the file is written in, is a way to describe messages as fields with numbers. Each field has a name, a type, and a number that identifies it on the wire. The numbers are part of the contract: renumbering a field breaks old clients.

proto/greeter.proto
syntax = "proto3";
package greeter;

service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply);
}

message HelloRequest {
  string name = 1;
}

message HelloReply {
  string message = 1;
}

The service block names the service and its methods. Each rpc line is one method, with its request message and its response message. The message blocks are the shapes of those two values. proto3 is the version of the format, and package greeter is a namespace that keeps these names apart from other services.

The build script compiles the .proto file into Rust code when the project builds. It runs before the main compilation, and its output goes into a directory Cargo provides, which the code then includes.

build.rs
fn main() {
    tonic_prost_build::compile_protos("proto/greeter.proto").unwrap();
}

The server implements the generated trait and runs both servers at once, on two different ports.

src/main.rs
use axum::{Router, routing::get};
use greeter::greeter_server::{Greeter, GreeterServer};
use greeter::{HelloReply, HelloRequest};
use tonic::{Request, Response, Status};

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

#[derive(Default)]
struct MyGreeter;

#[tonic::async_trait]
impl Greeter for MyGreeter {
    async fn say_hello(
        &self,
        request: Request<HelloRequest>,
    ) -> Result<Response<HelloReply>, Status> {
        let name = request.into_inner().name;
        Ok(Response::new(HelloReply {
            message: format!("Hello, {name}!"),
        }))
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let grpc_addr = "127.0.0.1:50051".parse()?;
    let grpc = tonic::transport::Server::builder()
        .add_service(GreeterServer::new(MyGreeter::default()))
        .serve(grpc_addr);

    let http_app = Router::new().route("/health", get(|| async { "OK" }));
    let http_listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await?;
    let http = axum::serve(http_listener, http_app);

    println!("gRPC on 127.0.0.1:50051, HTTP on http://127.0.0.1:3000");
    tokio::try_join!(
        async { grpc.await.map_err(|e| Box::new(e) as Box<dyn std::error::Error>) },
        async { http.await.map_err(|e| Box::new(e) as Box<dyn std::error::Error>) },
    )?;
    Ok(())
}

Run it with cargo run. The program prints both addresses and then waits, serving both servers. Check the HTTP side:

curl http://127.0.0.1:3000/health
OK

Check the gRPC side with a small client program. Put this in a second binary in the same project, src/bin/client.rs, so it shares the generated code and the .proto file.

src/bin/client.rs
use greeter::greeter_client::GreeterClient;
use greeter::HelloRequest;

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

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut client = GreeterClient::connect("http://127.0.0.1:50051").await?;
    let response = client.say_hello(HelloRequest { name: "Nitiksh".into() }).await?;
    println!("gRPC reply: {}", response.into_inner().message);
    Ok(())
}

Run it in a second terminal while the server is running:

cargo run --bin client

On the machine used to check this page, the client printed:

gRPC reply: Hello, Nitiksh!

The call crossed the network as a binary gRPC message and came back as a string, with no HTTP and no JSON involved on that path. The health route kept answering plain HTTP at the same time.

Working Setup:

If curl http://127.0.0.1:3000/health prints OK and the client prints gRPC reply: Hello, Nitiksh!, both servers are up and the generated code matches the .proto file on both sides.

The Pieces, One at a Time

1. The proto file is the contract

The .proto file is the only place the service is defined. The server implements it, the client calls it, and both sides generate their code from the same file. Changing the file and rebuilding changes both sides together. A client built from an old .proto file and a server built from a new one disagree, and the disagreement shows up as a failed call, not as a compile error, which is why the file is usually kept in version control and shared deliberately, not copied by hand.

Field numbers deserve a sentence of their own. The number after each field is its identity on the wire. Adding a new field means taking a fresh number. Removing a field means leaving its number unused forever, never reusing it for a different field, because an old client might still send the old field under that number. The numbers are the reason old and new versions of a service can talk to each other at all.

2. The build script generates the code

fn main() {
    tonic_prost_build::compile_protos("proto/greeter.proto").unwrap();
}

The build script runs protoc on the .proto file and generates Rust code for the messages and for the service traits. The generated code is not in the source tree. It lives in the build output directory, and the tonic::include_proto! macro pulls it into the program at compile time. The macro argument is the package name from the .proto file, "greeter", and the module it creates holds everything generated: the message structs, the server trait, and the client struct.

In tonic 0.14, the crate that does this is tonic-prost-build, not tonic-build. The older crate still exists, but it no longer compiles .proto files; it only generates the service stubs from already compiled messages. Code written for tonic 0.13 that calls tonic_build::compile_protos does not compile against 0.14. The fix is the new crate name and the new call, as shown above, plus the tonic-prost runtime crate in the main dependencies, which the generated code refers to for its message codec.

3. The service trait is implemented by hand

#[tonic::async_trait]
impl Greeter for MyGreeter {
    async fn say_hello(
        &self,
        request: Request<HelloRequest>,
    ) -> Result<Response<HelloReply>, Status> {
        let name = request.into_inner().name;
        Ok(Response::new(HelloReply {
            message: format!("Hello, {name}!"),
        }))
    }
}

The generated trait has one method per rpc line, with the same name converted to Rust's snake case: SayHello becomes say_hello. The method takes a tonic::Request wrapping the message, and returns a Result holding a tonic::Response wrapping the reply, or a tonic::Status describing an error. request.into_inner() unwraps the message. Response::new(...) wraps the reply. The #[tonic::async_trait] attribute is needed because Rust traits cannot have async methods directly, and the attribute rewrites the trait into a form that works. The struct itself, MyGreeter, holds whatever state the service needs, and #[derive(Default)] gives it an empty starting value.

Status is the gRPC error type. It carries a code, such as not found or invalid argument, and a message. Returning Err(Status::not_found("no such user")) sends a proper gRPC error to the client, which the client sees as a failed call with that code and message. It is the gRPC equivalent of an HTTP status plus an error body, and it is the right way to report failures from a handler.

4. The two servers run on two ports

let grpc = tonic::transport::Server::builder()
    .add_service(GreeterServer::new(MyGreeter::default()))
    .serve(grpc_addr);
let http = axum::serve(http_listener, http_app);
tokio::try_join!(
    async { grpc.await.map_err(|e| Box::new(e) as Box<dyn std::error::Error>) },
    async { http.await.map_err(|e| Box::new(e) as Box<dyn std::error::Error>) },
)?;

tonic::transport::Server::builder() builds the gRPC server, .add_service(...) registers the generated service, and .serve(addr) runs it. The Axum side is the familiar listener and serve. tokio::try_join! runs both futures at once and waits for both. If either one fails, the other is dropped and the error is returned. The two servers share the Tokio runtime and the process, but they listen on different ports, 50051 for gRPC and 3000 for HTTP, and they never see each other's traffic. Port 50051 is the conventional default for gRPC examples, and it is a good choice here because nothing else on a development machine uses it.

Two Ports Means Two Addresses to Configure:

A client needs to know both addresses, and a deployment needs to expose both ports. Forgetting the gRPC port in a firewall rule or a container setup produces a server that answers health checks and refuses every service call. The health route says the process is up. It says nothing about the gRPC port.

The Concept Behind It

gRPC is remote procedure call. A remote procedure call is a function call where the function lives in another program. The caller writes what looks like a normal call, client.say_hello(request), and the framework turns it into bytes, sends them across the network, waits for the answer bytes, and turns them back into a value. The caller never sees the network. The .proto file is what makes that illusion safe: both sides agree on the shapes in advance, so the bytes always parse.

Underneath, gRPC runs on HTTP/2, which is the newer version of HTTP that multiplexes many streams over one connection. That is why a gRPC client can make many calls at once over a single connection, and why a gRPC server can push a stream of responses for one call. The binary message format is Protocol Buffers, which is smaller and faster to parse than JSON, and which is why services that talk to each other thousands of times a second prefer it. None of that is visible in the code above, which is the point: the framework carries the mechanism, and the code carries the logic.

Why Two Protocols in One Program

The honest answer is that each protocol serves a different audience, and one program can serve both audiences without duplicating its logic. The Axum routes serve browsers, CLIs, and public clients, speaking HTTP and JSON. The tonic service serves other programs inside the same system, speaking HTTP/2 and Protocol Buffers. The two can share the same state, the same database pool, and the same business functions, because they are two front doors to one program.

The alternative is two programs, one per protocol, which duplicates the deployment and the shared logic, or one protocol for everything, which forces browsers to speak gRPC or services to speak JSON. Two front doors in one program is the middle shape, and it is the right one when both audiences exist and the logic is shared.

A Richer Example with Two Methods and a Shared Store

A greeter that only says hello is a toy. This version adds a second method and a shared counter, so the service holds state that both methods and the HTTP side can see.

proto/greeter.proto
syntax = "proto3";
package greeter;

service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply);
  rpc SayGoodbye (HelloRequest) returns (HelloReply);
}

message HelloRequest {
  string name = 1;
}

message HelloReply {
  string message = 1;
}
src/main.rs
use axum::{Json, Router, extract::State, routing::get};
use greeter::greeter_server::{Greeter, GreeterServer};
use greeter::{HelloReply, HelloRequest};
use serde::Serialize;
use std::sync::{Arc, Mutex};
use tonic::{Request, Response, Status};

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

#[derive(Clone, Default)]
struct MyGreeter {
    greetings: Arc<Mutex<u64>>,
}

#[tonic::async_trait]
impl Greeter for MyGreeter {
    async fn say_hello(
        &self,
        request: Request<HelloRequest>,
    ) -> Result<Response<HelloReply>, Status> {
        let name = request.into_inner().name;
        let mut count = self.greetings.lock().unwrap();
        *count += 1;
        let n = *count;
        Ok(Response::new(HelloReply {
            message: format!("Hello, {name}! (greeting number {n})"),
        }))
    }

    async fn say_goodbye(
        &self,
        request: Request<HelloRequest>,
    ) -> Result<Response<HelloReply>, Status> {
        let name = request.into_inner().name;
        Ok(Response::new(HelloReply {
            message: format!("Goodbye, {name}!"),
        }))
    }
}

#[derive(Serialize)]
struct Stats {
    greetings: u64,
}

async fn stats(State(greeter): State<MyGreeter>) -> Json<Stats> {
    Json(Stats { greetings: *greeter.greetings.lock().unwrap() })
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let greeter = MyGreeter::default();
    let grpc_addr = "127.0.0.1:50051".parse()?;
    let grpc = tonic::transport::Server::builder()
        .add_service(GreeterServer::new(greeter.clone()))
        .serve(grpc_addr);

    let http_app = Router::new()
        .route("/health", get(|| async { "OK" }))
        .route("/stats", get(stats))
        .with_state(greeter);
    let http_listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await?;
    let http = axum::serve(http_listener, http_app);

    println!("gRPC on 127.0.0.1:50051, HTTP on http://127.0.0.1:3000");
    tokio::try_join!(
        async { grpc.await.map_err(|e| Box::new(e) as Box<dyn std::error::Error>) },
        async { http.await.map_err(|e| Box::new(e) as Box<dyn std::error::Error>) },
    )?;
    Ok(())
}

The MyGreeter struct now holds an Arc<Mutex<u64>> counter, shared by cloning the struct into both servers. Each SayHello increments it and reports the count in its message. The /stats HTTP route reads the same counter through Axum State, so a browser can see how many greetings the gRPC service has served. The counter is a Mutex because the gRPC methods run on Tokio tasks that may run on different workers, and the count must not be lost to a race. The lock is held only for the increment, never across an await, which keeps it from blocking other tasks.

Call both methods from the client to see the two replies:

gRPC reply: Hello, Nitiksh!
gRPC reply: Goodbye, Nitiksh!

Then check the shared state over HTTP:

curl http://127.0.0.1:3000/stats
{"greetings":1}

One greeting was counted, and the HTTP side saw it. The two front doors share one set of facts.

One Port for Both, and Why This Page Does Not Do It

It is possible to serve HTTP and gRPC on the same port, by inspecting each incoming connection and routing HTTP/1.1 traffic to Axum and HTTP/2 traffic to tonic. The mechanism is a Tower service that peeks at the connection's protocol version and dispatches accordingly. It works, and it saves a port and a firewall rule, but it adds a layer of connection handling that is easy to get subtly wrong, and it makes the setup harder to debug: a connection that fails could be failing in the dispatcher, in Axum, or in tonic, and the error gives no hint which.

Two ports is the shape that is easy to understand, easy to test, and easy to operate. Each server has its own address, its own logs, and its own failure mode. Use two ports until there is a concrete reason, such as a platform that exposes exactly one port, to merge them. When that reason appears, the merge is a transport detail, and the service code does not change.

gRPC Needs HTTP/2:

A gRPC client that connects over plain HTTP/1.1 will fail, because gRPC is built on HTTP/2. The http:// in the client address is the scheme tonic expects for an unencrypted connection, and tonic negotiates HTTP/2 on it. A load balancer or proxy in front of the gRPC port must pass HTTP/2 through, or the calls will fail at the handshake.

What the Flow Looks Like

Client calls client.say_hello(request)
        |
        v
Generated client encodes the message as protobuf bytes
        |
        v
Bytes travel over HTTP/2 to 127.0.0.1:50051
        |
        v
tonic decodes the bytes into HelloRequest
        |
        v
MyGreeter::say_hello runs and builds HelloReply
        |
        v
tonic encodes the reply and sends it back
        |
        v
Client decodes it into HelloReply
        |
        v
Browser calls GET /health on port 3000
        |
        v
Axum routes it to the handler and answers "OK"

The two flows share the process and the runtime, and nothing else. The gRPC flow never touches Axum, and the HTTP flow never touches tonic.

Testing It

A gRPC service can be tested without a network by calling the trait implementation directly, and the HTTP side can be tested through the router the usual way.

tests/app_test.rs
use axum::{
    body::Body,
    http::{Request, StatusCode},
};
use greeter_service::MyGreeter;
use greeter_service::greeter::{HelloRequest, greeter_server::Greeter};
use tonic::Request as GrpcRequest;
use tower::ServiceExt;

#[tokio::test]
async fn say_hello_greets_by_name() {
    let greeter = MyGreeter::default();
    let response = greeter
        .say_hello(GrpcRequest::new(HelloRequest { name: "Ada".into() }))
        .await
        .unwrap();
    assert_eq!(response.into_inner().message, "Hello, Ada!");
}

That test needs the service struct and the generated module to be public in the library, which is a small restructuring: move MyGreeter and the greeter module into src/lib.rs, and keep src/main.rs as the thin server startup. The test calls the method directly, with a tonic::Request built by hand, and checks the message. No network is involved, and the test runs in milliseconds. A test of the full path, client to server over a real socket, is the next step, and it needs a server bound to an ephemeral port and a client pointed at it. The direct test catches logic errors. The network test catches wiring errors. Both are worth having, and the direct one is the one to write first.

The test needs tower as a dev dependency for the HTTP side, and tonic itself is already a main dependency:

Cargo.toml
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }

Common Beginner Mistakes

Using the old build crate

// Wrong - tonic-build 0.14 does not compile .proto files
fn main() {
    tonic_build::compile_protos("proto/greeter.proto").unwrap();
}

In tonic 0.14 the function does not exist on that crate, and the build fails with a cannot find function error. The fix is tonic-prost-build in [build-dependencies] and tonic_prost_build::compile_protos in the build script, plus tonic-prost in the main dependencies. This is the single most likely compile failure when following older tonic tutorials, because every tutorial written before 0.14 uses the old crate.

Forgetting protoc

The build script calls protoc, and without it the build fails with an error about the compiler not being found. The fix is to install it, as shown at the top of the page. A project that builds on one machine and fails on another has usually lost protoc in the move, not the Rust code.

Calling the service on the HTTP port

A gRPC client pointed at port 3000, the Axum port, fails with a protocol error, because Axum speaks HTTP/1.1 and the client speaks HTTP/2 with gRPC framing. The two ports are different protocols, and the client must use the gRPC one. When a client fails to connect, check the port first, before doubting the service code.

Returning a plain error instead of a Status

A handler that returns Err(anyhow::Error) cannot compile, because the trait demands Status. A handler that panics on bad input closes the call without an answer. Map failures to a Status with a code that describes the failure: Status::invalid_argument for bad input, Status::not_found for a missing record, Status::internal for something unexpected. The client can then branch on the code instead of parsing a message.

Do Not Reuse a Proto Field Number:

Removing a field from a message and giving its number to a new field breaks old clients silently: they send the old field under that number, and the server reads it as the new field. Leave removed numbers unused forever. The .proto file can note the retired numbers in a comment, so nobody reuses them by accident.

Final Complete Example

Here is everything from the page put together: the proto file, the build script, the service with its two methods and shared counter, both servers, and the client.

proto/greeter.proto
syntax = "proto3";
package greeter;

service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply);
  rpc SayGoodbye (HelloRequest) returns (HelloReply);
}

message HelloRequest {
  string name = 1;
}

message HelloReply {
  string message = 1;
}
build.rs
fn main() {
    tonic_prost_build::compile_protos("proto/greeter.proto").unwrap();
}
src/main.rs
use axum::{Router, routing::get};
use greeter::greeter_server::{Greeter, GreeterServer};
use greeter::{HelloReply, HelloRequest};
use tonic::{Request, Response, Status};

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

#[derive(Default)]
struct MyGreeter;

#[tonic::async_trait]
impl Greeter for MyGreeter {
    async fn say_hello(
        &self,
        request: Request<HelloRequest>,
    ) -> Result<Response<HelloReply>, Status> {
        let name = request.into_inner().name;
        Ok(Response::new(HelloReply {
            message: format!("Hello, {name}!"),
        }))
    }

    async fn say_goodbye(
        &self,
        request: Request<HelloRequest>,
    ) -> Result<Response<HelloReply>, Status> {
        let name = request.into_inner().name;
        Ok(Response::new(HelloReply {
            message: format!("Goodbye, {name}!"),
        }))
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let grpc_addr = "127.0.0.1:50051".parse()?;
    let grpc = tonic::transport::Server::builder()
        .add_service(GreeterServer::new(MyGreeter::default()))
        .serve(grpc_addr);

    let http_app = Router::new().route("/health", get(|| async { "OK" }));
    let http_listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await?;
    let http = axum::serve(http_listener, http_app);

    println!("gRPC on 127.0.0.1:50051, HTTP on http://127.0.0.1:3000");
    tokio::try_join!(
        async { grpc.await.map_err(|e| Box::new(e) as Box<dyn std::error::Error>) },
        async { http.await.map_err(|e| Box::new(e) as Box<dyn std::error::Error>) },
    )?;
    Ok(())
}
src/bin/client.rs
use greeter::greeter_client::GreeterClient;
use greeter::HelloRequest;

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

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut client = GreeterClient::connect("http://127.0.0.1:50051").await?;
    let response = client.say_hello(HelloRequest { name: "Nitiksh".into() }).await?;
    println!("gRPC reply: {}", response.into_inner().message);
    let response = client.say_goodbye(HelloRequest { name: "Nitiksh".into() }).await?;
    println!("gRPC reply: {}", response.into_inner().message);
    Ok(())
}
Cargo.toml
[package]
name = "greeter-service"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tonic = "0.14"
tonic-prost = "0.14"
prost = "0.14"

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

Install protoc, run the server with cargo run, and run the client with cargo run --bin client. The client prints both greetings, and curl http://127.0.0.1:3000/health prints OK.

Summary

The single most important insight is that the .proto file is the contract, and everything else is generated from it. The server implements the generated trait, the client calls the generated struct, and both sides agree because they read the same file. The Axum server and the tonic server are two front doors to one program, on two ports, sharing the runtime and whatever state the program holds. That shape lets each audience use the protocol that fits it, without duplicating the logic behind either door.

The decision framework follows from that. Use Axum alone while the callers are browsers and public clients. Add a tonic service when programs inside the system need to call the service with a fixed contract and heavy traffic, and keep the two servers on separate ports until a platform forces them together. And when following a tonic tutorial, check its version first: tonic 0.14 moved proto compilation to tonic-prost-build, and the old build call is the first thing that will fail.