liveBook · Manning

Context

As explained in gRPC Microservices in Go

A Go context is a request-scoped value that carries cancellation, deadlines, and other metadata across call boundaries.

A Go context carries deadlines, cancellation signals, and key-value data across call boundaries. Generated gRPC service functions take a context.Context as their first parameter, so a caller can pass a time limit into a service call. section 6.1.1

Use a timeout when a slow dependency could make an upstream service miss its latency commitment. For an Order service waiting on Shipping or Payment, a bounded call can fail fast instead of waiting indefinitely. context.WithDeadline takes a target time; context.WithTimeout takes a duration. Both derive a context from a parent and return a cancellation function. section 6.1.1

Listing 6.1 Timeout pattern on the client side
shippingClient := shipping.NewShippingServiceClient(conn)   #1
    ctx, _ := context.WithDeadline(context.Background(), 
     time.Now().Add(1*time.Second))                         #2
    log.Println("Creating shipping...")
    _, errCreate := shippingClient.Create(ctx,   
     &shipping.CreateShippingRequest{UserId: 23})
    if errCreate != nil {
        log.Printf("Failed to create shipping. Err: %v", errCreate)
    } else {
        log.Println("Shipping is created successfully.")
    }

The Shipping client creates a one-second deadline and passes the resulting context to Create; the caller handles a returned error rather than assuming the shipment succeeded. section 6.1.1

Pass the same context into downstream calls to carry the caller’s time limit across service boundaries. A cancellation function can also stop work that is no longer needed: if several endpoints compete to provide a result, cancel the shared context once one returns. section 6.1.1

Context also connects a request to its logs. In a gRPC order operation, a logrus formatter can read span data from the log entry’s context and add trace_id and span_id fields to JSON output. Those fields let a logging backend find messages associated with the same operation. section 9.3.7

...
type serviceLogger struct {
    formatter log.JSONFormatter                                    #1
}
 
func (l serviceLogger) Format(entry *log.Entry) ([]byte, error) {
    span := trace.SpanFromContext(entry.Context)                   #2
    entry.Data["trace_id"] = span.SpanContext().TraceID().String()
    entry.Data["span_id"] = span.SpanContext().SpanID().String()
    //Below injection is Just to understand what Context has
    entry.Data["Context"] = span.SpanContext()
    return l.formatter.Format(entry)                               #3
}
...

The formatter retrieves the span from entry.Context and writes its trace and span IDs into the log entry before JSON formatting. section 9.3.7

How gRPC Microservices in Go covers it

How deep it goes
Explains deadline and timeout constructors, cancellation, downstream propagation, and span extraction through client and logging code; does not detail context internals.
Examples
Uses a one-second Shipping call, context propagation through Order and Product services, and a logrus formatter that adds trace IDs.
What it assumes
Assumes familiarity with generated gRPC service calls while defining Go context and its deadline and cancellation roles.
What you can do after
Apply it via Go context constructors and gRPC calls to bound waits, then use logrus context-aware logging to correlate operations.
How it connects
Connects context to gRPC, timeout patterns, cancellation, distributed tracing, and structured logging.

Also explained in

Compare how 7 books explain context →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of gRPC Microservices in Go. The section links point to the parts of the book it draws on.