Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 39 · Error Handling and Metadata

gRPC Metadata, Headers and Trailers

Understand gRPC metadata: request headers, response headers and trailers, key rules, binary values, and how to read and send them in Go, with runnable stand-ins.

A gRPC request has a body (your protobuf message) and, next to it, metadata: a list of key-value pairs about the call. Metadata is the right place for things that are about the call rather than part of the business data: an authentication token, a request ID, a tracing header, a client version, a locale.

Metadata is just HTTP/2 headers underneath. That is why you will see the words headers and trailers all the time. Understanding who can send what, and when, saves hours of confusion.

Real grpc-go code is shown read-only because this site cannot run the gRPC library. The runnable blocks are plain Go stand-ins that model keys, values and the three metadata phases.

Three places metadata can appear

sequenceDiagram
    participant C as Client
    participant S as Server
    C->>S: request headers (client metadata)
    C->>S: request message(s)
    S-->>C: response headers (header metadata)
    S-->>C: response message(s)
    S-->>C: trailers (status + trailer metadata)

Headers go first, then messages, then trailers close the call.

  • Request headers: sent by the client before the first message. Examples: authorization, x-request-id.
  • Response headers: sent by the server before the first response message (or with the trailers if there is no message). Use them for data you know early.
  • Trailers: sent by the server last, after all messages. They always carry grpc-status and grpc-message, and you can add your own. Use them for data you only know at the end, such as the number of rows scanned or a checksum.

Key and value rules

  • Keys are lowercase ASCII letters, digits, -, _ and .. grpc-go lowercases keys for you.
  • Keys starting with grpc- are reserved. Never invent your own grpc-* key.
  • A key may have several values; order is preserved per key.
  • Values are printable ASCII text by default. For binary data the key must end in -bin; the library base64 encodes it for you.
  • Keep metadata small. Headers have size limits (often 8 KB to 16 KB in proxies) and a rejected request surfaces as a confusing RESOURCE_EXHAUSTED or UNAVAILABLE.

Client side: sending metadata (real API)

Go
import "google.golang.org/grpc/metadata"

md := metadata.Pairs(
    "authorization", "Bearer abc123",
    "x-request-id", "req-7f3a",
)
ctx := metadata.NewOutgoingContext(context.Background(), md)

// add to existing outgoing metadata without replacing it:
ctx = metadata.AppendToOutgoingContext(ctx, "x-client-version", "2.4.0")

var header, trailer metadata.MD
resp, err := client.GetUser(ctx, req,
    grpc.Header(&header),   // capture response headers
    grpc.Trailer(&trailer), // capture trailers
)
fmt.Println(header.Get("x-served-by"), trailer.Get("x-rows-scanned"))

NewOutgoingContext replaces any existing outgoing metadata; AppendToOutgoingContext adds to it. Use append inside libraries so you do not wipe what a caller set.

Server side: reading and writing (real API)

Go
func (s *server) GetUser(ctx context.Context, req *pb.GetUserRequest) (*pb.User, error) {
    md, ok := metadata.FromIncomingContext(ctx)
    if ok {
        if ids := md.Get("x-request-id"); len(ids) > 0 {
            log.Println("request id:", ids[0])
        }
    }

    // response header: sent right away (or with the first message)
    grpc.SendHeader(ctx, metadata.Pairs("x-served-by", "node-3"))

    // trailer: sent at the very end of the call
    grpc.SetTrailer(ctx, metadata.Pairs("x-rows-scanned", "42"))
    return s.lookup(req.GetId())
}

grpc.SetHeader queues headers that go out with the first message; grpc.SendHeader sends them immediately. Both must be called before the first response message is written.

A runnable stand-in

The stand-in implements a small MD type with the same rules: lowercase keys, multi-values, and a check that -bin keys are the only place for binary data.

Go A tiny metadata type

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.

Headers versus trailers in a streaming call

A unary call has one request and one response, so the difference is small. In a server-streaming call the server may send thousands of messages. Headers describe the stream before it starts (the server name, the chosen shard). Trailers summarize it afterwards (items sent, checksum). The status is always in the trailers, which is why a stream can start fine and still end with an error: the client only learns the final status when the trailers arrive.

Go Headers first, trailers last

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.

Good habits

  • Put credentials and tracing data in metadata, business data in messages.
  • Treat incoming metadata as untrusted input: validate and limit it like any user input.
  • Do not put large or secret data in metadata; it appears in proxy logs more often than message bodies do.
  • Use -bin keys for binary values such as serialized trace contexts.
  • Interceptors are the natural place to read and set metadata for every call; see interceptors.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Which part of a gRPC call always carries grpc-status?

    The final status is delivered in the trailers, after all messages have been sent.
  2. 2. Which key can carry raw binary values?

    Keys ending in -bin carry binary values; the library base64 encodes them. Keys with the grpc- prefix are reserved.
  3. 3. In grpc-go, how do you add a header to the outgoing context without wiping existing metadata?

    AppendToOutgoingContext adds pairs to what is already there; NewOutgoingContext replaces it.
  4. 4. Why can a streaming call start successfully and still end with an error status?

    Messages may already have been delivered when the server fails; the error status is sent last in the trailers.

Summary

  • Metadata are key-value pairs sent as HTTP/2 headers: request headers, response headers and trailers.
  • Keys are lowercase; grpc- is reserved; binary values need a -bin key.
  • Trailers always carry the final status and are the place for facts known only at the end.
  • In Go: metadata.NewOutgoingContext, AppendToOutgoingContext, FromIncomingContext, grpc.SendHeader, grpc.SetTrailer, and the grpc.Header/grpc.Trailer call options.
  • Keep metadata small and treat it as untrusted input.

Next: Deadlines and Cancellation