Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 39 ยท Interceptors and Security

gRPC Interceptors Explained

Learn how gRPC interceptors work: unary and stream interceptors on client and server, chaining order, and how to write them in Go, with runnable middleware stand-ins.

Almost every service needs the same extras around each call: log it, time it, check a token, recover from panics, count it in a metric, attach a trace ID. Copying that code into every handler is tedious and easy to forget. An interceptor is gRPC's middleware: a function that wraps a call, runs code before and after it, and can even refuse to call the real handler.

If you have used HTTP middleware in Express, ASP.NET or Go's net/http, the idea is the same. What gRPC adds is that there are four flavours, because calls come in two shapes (unary and streaming) and two sides (client and server).

The real grpc-go interceptor signatures are shown read-only. The runnable blocks build the same wrapping pattern with plain Go functions, so you can see the chain order and short-circuiting without the library.

The four kinds

Side Unary RPC Streaming RPC
Server grpc.UnaryInterceptor grpc.StreamInterceptor
Client grpc.WithUnaryInterceptor grpc.WithStreamInterceptor

A unary interceptor sees one request and one response, so it is easy. A stream interceptor sees the stream, not individual messages; to look at messages you wrap the stream object. Streaming is covered in the Streaming chapter.

A server unary interceptor (real API)

Go
func timingInterceptor(
    ctx context.Context,
    req any,
    info *grpc.UnaryServerInfo,
    handler grpc.UnaryHandler,
) (any, error) {
    start := time.Now()
    resp, err := handler(ctx, req) // call the next interceptor or the real method
    log.Printf("%s took %v, code=%v", info.FullMethod, time.Since(start), status.Code(err))
    return resp, err
}

srv := grpc.NewServer(grpc.UnaryInterceptor(timingInterceptor))

info.FullMethod looks like /users.v1.UserService/GetUser. Calling handler(ctx, req) continues the call. Not calling it short-circuits: you return your own response or error, and the real method never runs. That is how authentication interceptors reject calls.

Client interceptors (real API)

Go
func addVersionInterceptor(
    ctx context.Context, method string, req, reply any,
    cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption,
) error {
    ctx = metadata.AppendToOutgoingContext(ctx, "x-client-version", "2.4.0")
    return invoker(ctx, method, req, reply, cc, opts...)
}

conn, _ := grpc.NewClient(target, grpc.WithUnaryInterceptor(addVersionInterceptor))

The client version works the same way but gets invoker instead of handler, and the response is passed in as reply. Client interceptors are great for adding metadata, default deadlines and tokens.

Chaining and order

Pass several with grpc.ChainUnaryInterceptor(a, b, c). The first one is the outermost: a runs first on the way in and last on the way out, like layers of an onion.

flowchart LR
    R["Request"] --> A["recovery"]
    A --> B["logging"]
    B --> C["auth"]
    C --> H["Handler"]
    H -.->|"response"| C
    C -.-> B
    B -.-> A
    A -.-> O["Response"]

Request flows inward through the chain; the response flows back out in reverse order.

A sensible order is recovery outermost (so it catches panics from every layer below), then logging and metrics, then authentication, then validation closest to the handler.

Runnable: a chain of interceptors

Go Interceptor chain, logging and auth

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.

In the second call the real upper handler never runs; auth answers instead, but logging, which sits outside it, still records the failure.

Interceptors that modify the call

Interceptors can also change data. A server interceptor may add values to the context (the authenticated user, a request ID) for the handler to read with ctx.Value. A client interceptor may add metadata. Keep context keys in a private type so they cannot collide:

Go
type ctxKey struct{}

func userFrom(ctx context.Context) (string, bool) {
    u, ok := ctx.Value(ctxKey{}).(string)
    return u, ok
}
Go An interceptor passes data through the context

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.

Stream interceptors in one glance

A server stream interceptor receives the grpc.ServerStream. To observe messages you wrap it and override RecvMsg and SendMsg:

Go
type countingStream struct {
    grpc.ServerStream
    received int
}

func (s *countingStream) RecvMsg(m any) error {
    err := s.ServerStream.RecvMsg(m)
    if err == nil {
        s.received++
    }
    return err
}

func streamLogger(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, h grpc.StreamHandler) error {
    cs := &countingStream{ServerStream: ss}
    err := h(srv, cs)
    log.Printf("%s received %d messages", info.FullMethod, cs.received)
    return err
}

Embedding the interface means every method you do not override is forwarded automatically.

Do and do not

  • Keep interceptors small and single-purpose; compose them with a chain.
  • Do not read or modify request bodies unless you must. Big messages cost memory.
  • Never swallow errors. Return what the handler returned unless the interceptor's job is to translate it.
  • Prefer community packages (go-grpc-middleware) for logging, recovery, retries and validation instead of hand-rolling them.
  • Interceptors run per call, so avoid slow work such as a database lookup for every request without caching.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does a server interceptor reject a call without running the real method?

    Not calling the handler short-circuits the chain, so the interceptor's own response or error is returned.
  2. 2. In ChainUnaryInterceptor(a, b, c), which one sees the request first?

    The first interceptor is the outermost layer: first in on the way in, last out on the way back.
  3. 3. Where does a recovery interceptor usually belong in the chain?

    Placed outermost, it wraps everything below it and can turn any panic into an INTERNAL status.
  4. 4. What does a stream interceptor see?

    Stream interceptors get the ServerStream (or ClientStream); wrap it to override RecvMsg and SendMsg.

Summary

  • Interceptors are gRPC middleware: they wrap calls on the server or client, unary or streaming.
  • Call handler (server) or invoker (client) to continue; skip it to short-circuit.
  • grpc.ChainUnaryInterceptor builds an onion: the first interceptor is outermost.
  • Use context values for per-call data and wrap streams to observe messages.
  • Typical uses: recovery, logging, metrics, tracing, authentication and validation.

Next: Logging and Recovery Interceptors