Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 39 ยท Services and RPC Types

Defining Services and Unary RPCs

Define a gRPC service in a .proto file with unary methods, design request and response messages, follow naming and CRUD conventions, and see a typed method registry in Go.

A service is a named group of methods that clients can call. You declare it in the .proto file with the service keyword, and each method with rpc. The simplest kind of method is unary: the client sends one request message and receives one response message, exactly like a function call. Most gRPC methods in the real world are unary.

In this lesson you will design a small catalog service, learn the naming and design conventions that keep APIs consistent, and run Go stand-ins that model how a service is registered and dispatched. The .proto code is read-only (no compiler here).

Anatomy of a service

PROTO
syntax = "proto3";

package shop.v1;

service Catalog {
  rpc GetProduct(GetProductRequest) returns (Product);
  rpc ListProducts(ListProductsRequest) returns (ListProductsResponse);
  rpc CreateProduct(CreateProductRequest) returns (Product);
  rpc UpdateProduct(UpdateProductRequest) returns (Product);
  rpc DeleteProduct(DeleteProductRequest) returns (google.protobuf.Empty);
}

message GetProductRequest { int64 id = 1; }

message ListProductsRequest {
  int32 page_size = 1;
  string page_token = 2;
}
message ListProductsResponse {
  repeated Product products = 1;
  string next_page_token = 2;
}

Every rpc has exactly one input message and one output message. You cannot write rpc Foo(int32) returns (string): both sides must be messages, which is why wrapper messages exist for single values. The method's full name on the wire is /shop.v1.Catalog/GetProduct.

flowchart TD
  S["service Catalog"] --> M1["GetProduct (unary)"]
  S --> M2["ListProducts (unary)"]
  S --> M3["CreateProduct (unary)"]
  M1 --> R1["GetProductRequest to Product"]
  M2 --> R2["ListProductsRequest to ListProductsResponse"]

A service is a table of methods, each mapping an input message to an output message.

Naming conventions

  • Services: UpperCamelCase nouns (Catalog, OrderService). Buf's lint requires the suffix Service in the STANDARD ruleset.
  • Methods: verb + noun in UpperCamelCase (GetProduct, CreateOrder).
  • Request message: <Method>Request. Response message: <Method>Response.
  • Standard method verbs, borrowed from Google's API design guide: Get, List, Create, Update, Delete, plus custom verbs such as Cancel or Publish.
  • Give every method its own request and response types, even if two are identical today. Sharing types couples methods together, and changing one later forces changes on the other.

Returning the resource directly (as GetProduct does above) is common, but the lint rule STANDARD expects GetProductResponse. Pick one convention and apply it throughout; consistency matters more than the choice.

Designing unary methods

Get: input is the identifier, output is the resource.

List: always paginate. Unbounded lists grow until a response exceeds the default 4 MB receive limit. Use page_size and an opaque page_token, and return next_page_token. An empty token means "last page".

Create: input carries the resource; the server assigns the id and returns the stored version. Add a client-supplied request id when retries must not create duplicates.

Update: either send the whole resource or send the resource plus a FieldMask (see oneof, optional and well-known types).

Delete: return google.protobuf.Empty, or a response message if you expect to add fields later.

Idempotency

A method is idempotent if repeating it has the same effect as calling it once. Get, Delete and a full Update are idempotent; Create is not unless you include an idempotency key. This matters because networks fail and clients retry. gRPC's built-in retry policies (covered in clients and channels) are only safe for idempotent methods.

Stand-in 1: a typed method registry

This runnable program models what the generated Register...Server code does: it stores a handler per full method name, with request and response types, and dispatches by name. It uses Go generics and JSON in place of generated code and protobuf.

Go Stand-in: typed registry and dispatch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Notice how the typed function getProduct knows nothing about bytes. The generated gRPC code does exactly this wrapping, with protobuf instead of JSON.

Stand-in 2: paginating a list

Pagination with page tokens is the standard answer to unbounded lists. Here the token is simply the next offset, base64-encoded to look opaque (real services often sign or encrypt tokens).

Go Stand-in: ListProducts with page tokens

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Common design mistakes

  1. A single method that does everything, with a mode string field. Separate methods are clearer and easier to authorize and monitor.
  2. Returning huge lists. Paginate, or use server streaming.
  3. Reusing one message for request and response, then later needing a field only one side uses.
  4. Using strings for everything, including dates and statuses. Use Timestamp and enums.
  5. Leaking database details, such as auto-increment ids or SQL column names, into the contract.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How many input and output messages does an rpc declare?

    Both sides of an rpc must be a single message type (streams repeat that message).
  2. 2. What is the full wire path of method GetProduct in service Catalog, package shop.v1?

    The path is /package.Service/Method.
  3. 3. Why paginate a List method?

    Unbounded lists grow without limit and can exceed the default 4 MB message limit.
  4. 4. Which unary method is NOT naturally idempotent?

    Repeating a create may create duplicates, so retries need a request id.

Summary

  • A service groups rpc methods; each takes one message and returns one message.
  • Follow Get/List/Create/Update/Delete naming and give each method its own request and response types.
  • Paginate lists with page_size, page_token and next_page_token.
  • Think about idempotency before enabling retries.
  • The generated registration code maps method paths to typed handlers.

Next: Implementing a gRPC Server