CodeSampleX

Ejemplo

google.golang.org/grpc v1.83.0: Configure gRPC-Go client and server receive message size limits to handle payloads exceeding the default 4MB limit

Muestra verificada para golang google.golang.org/grpc v1.83.0: Configure gRPC-Go client and server receive message size limits to handle payloads exceeding…

sha256:2a0fa7cb93fe3b863e2520ac8f3cb87f14c3964a07c329047abda9a63073769d

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
3
Claves de firma que lo compilaron
2
Entorno declarado go 1.26 linux x64 go 1.26 go go

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
go 1.26 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1
2026-08-17
go 1.26 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1
2026-08-18
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 FAIL compile:SKIPPED · contract:FAIL · load:SKIPPED · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-09-08

Caso

HOW
Objetivo
Configure gRPC-Go client and server receive message size limits to handle payloads exceeding the default 4MB limit
Paquetes
Símbolos
  • google.golang.org/grpc.NewServer
  • google.golang.org/grpc.NewClient
  • google.golang.org/grpc.MaxRecvMsgSize
  • google.golang.org/grpc.MaxCallRecvMsgSize
  • google.golang.org/grpc.MaxCallSendMsgSize
  • google.golang.org/grpc.WithDefaultCallOptions
  • google.golang.org/grpc.WithContextDialer
  • google.golang.org/grpc.WithTransportCredentials
  • google.golang.org/grpc.ClientConn.Invoke
  • google.golang.org/grpc/status.Code
  • google.golang.org/grpc/codes.ResourceExhausted
Entorno
go 1.26
Creado
2026-08-17T11:54:02Z

Contrato

  1. When a gRPC server returns a 5MB payload to a client with default options, the server transmits it without error but the client fails to decode the response with status code ResourceExhausted because the default client-side receive limit is 4MB.
  2. Configuring grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(10*1024*1024)) on the client does not permit receiving 5MB responses and still results in ResourceExhausted.
  3. Configuring grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(10*1024*1024)) or passing grpc.MaxCallRecvMsgSize to Invoke allows the client to successfully receive the 5MB response.
  4. Sending a 5MB request from a client to a server with default options causes the server to reject the incoming message with status code ResourceExhausted unless the server is configured with grpc.MaxRecvMsgSize.

Archivos

  • NOTES.md
  • csx.json
  • go.mod
  • go.sum
  • message_size_test.go

Descargar el artefacto de código fuente (tar.gz)

Código fuente

NOTES.md
# gRPC-Go message size limit configuration

The known-solution lookup returned an existing sample `sha256:a8acd8ef9a84180020f012467fae967f3de130dff4d432708ac5bf0a6df64717` covering outgoing metadata replacement in client interceptors. This sample explores inbound and outbound message size limits on gRPC-Go pinned to `v1.83.0`.

In gRPC-Go, both clients and servers enforce a default inbound receive message limit of 4 MiB (4,194,304 bytes), while outbound send message limits are unlimited (`math.MaxInt32`).

When a server returns a response larger than 4 MiB (such as 5 MiB):
1. The server serializes and transmits the frame successfully without error.
2. The client transport encounters the frame exceeding 4 MiB during decoding and fails the RPC loudly with status code `codes.ResourceExhausted` and message `grpc: received message larger than max (5242885 vs. 4194304)`.
3. Configuring `grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(10*1024*1024))` on the client fails to resolve the error because send limits govern only client-to-server outbound messages.
4. The client must configure `grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(10*1024*1024))` or provide `grpc.MaxCallRecvMsgSize(10*1024*1024)` as a per-call `CallOption` on `Invoke`.

Similarly, when a client sends a 5 MiB payload to a server with default options, the server rejects the request with `codes.ResourceExhausted` unless the server is configured with `grpc.MaxRecvMsgSize(10*1024*1024)`.

The contract verifies these behaviors using `bufconn` in-memory networking with `passthrough:///bufnet.example.com` and insecure credentials, requiring no TCP listener or external network access.
csx.json
{"case":{"believed":"A client can receive responses larger than 4MB without additional configuration because the default 4MB limit applies only to server request payloads, or by setting grpc.MaxCallSendMsgSize on the client.","caseId":"case:sha256:2fc3253dd78cbfdcbc113ec2131d80b0c4c565da7ee3471a914dca4d0af4350f","contract":["When a gRPC server returns a 5MB payload to a client with default options, the server transmits it without error but the client fails to decode the response with status code ResourceExhausted because the default client-side receive limit is 4MB.","Configuring grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(10*1024*1024)) on the client does not permit receiving 5MB responses and still results in ResourceExhausted.","Configuring grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(10*1024*1024)) or passing grpc.MaxCallRecvMsgSize to Invoke allows the client to successfully receive the 5MB response.","Sending a 5MB request from a client to a server with default options causes the server to reject the incoming message with status code ResourceExhausted unless the server is configured with grpc.MaxRecvMsgSize."],"goal":"Configure gRPC-Go client and server receive message size limits to handle payloads exceeding the default 4MB limit","kind":"HOW","packages":["pkg:golang/google.golang.org/grpc@v1.83.0","pkg:golang/google.golang.org/protobuf@v1.36.11"],"schemaVersion":1,"symbols":["google.golang.org/grpc.NewServer","google.golang.org/grpc.NewClient","google.golang.org/grpc.MaxRecvMsgSize","google.golang.org/grpc.MaxCallRecvMsgSize","google.golang.org/grpc.MaxCallSendMsgSize","google.golang.org/grpc.WithDefaultCallOptions","google.golang.org/grpc.WithContextDialer","google.golang.org/grpc.WithTransportCredentials","google.golang.org/grpc.ClientConn.Invoke","google.golang.org/grpc/status.Code","google.golang.org/grpc/codes.ResourceExhausted"]},"contractCommand":["go","test","-mod=readonly","-count=1","./..."],"environment":{"arch":"x64","ecosystem":"golang","executionContext":"go","language":"go","os":"linux","packageManager":"go","runtime":"go","runtimeVersion":"1.26","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/google.golang.org/grpc@v1.83.0","pkg:golang/google.golang.org/protobuf@v1.36.11"],"schemaVersion":1,"symbols":["google.golang.org/grpc.NewServer","google.golang.org/grpc.NewClient","google.golang.org/grpc.MaxRecvMsgSize","google.golang.org/grpc.MaxCallRecvMsgSize","google.golang.org/grpc.MaxCallSendMsgSize","google.golang.org/grpc.WithDefaultCallOptions","google.golang.org/grpc.WithContextDialer","google.golang.org/grpc.WithTransportCredentials","google.golang.org/grpc.ClientConn.Invoke","google.golang.org/grpc/status.Code","google.golang.org/grpc/codes.ResourceExhausted"],"verifierAdapter":"golang@1"}
go.mod
module example.com/grpc-message-size-limit

go 1.25.0

require (
	google.golang.org/grpc v1.83.0
	google.golang.org/protobuf v1.36.11
)

require (
	golang.org/x/net v0.55.0 // indirect
	golang.org/x/sys v0.45.0 // indirect
	golang.org/x/text v0.37.0 // indirect
	google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect
)
go.sum
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=
go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=
go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI=
go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=
go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa h1:mZHHdPZl0dbGHCflZgAq/Q468DWVFcU2whhB2KAo8fk=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
google.golang.org/grpc v1.83.0 h1:JeNZEKJFbQxArAMl+hiytHauacDNqJUllNfmIMmpqnQ=
google.golang.org/grpc v1.83.0/go.mod h1:kDyl6SKsiHKt0uylY5gtn5cEjkrIOhQOGDgIc4JGwzQ=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
message_size_test.go
// Package grpcconfig proves how gRPC-Go message size limit configuration works.
// By default, both gRPC clients and servers enforce a 4 MiB (4,194,304 bytes)
// inbound message receive limit, while outbound send size is unlimited.
// Receiving payloads larger than 4 MiB requires configuring MaxCallRecvMsgSize on
// the client (or MaxRecvMsgSize on the server), and configuring MaxCallSendMsgSize
// alone is ineffective.
package grpcconfig

import (
	"context"
	"net"
	"testing"
	"time"

	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/status"
	"google.golang.org/grpc/test/bufconn"
	"google.golang.org/protobuf/types/known/emptypb"
	"google.golang.org/protobuf/types/known/wrapperspb"
)

const (
	fiveMB = 5 * 1024 * 1024
	tenMB  = 10 * 1024 * 1024

	echoMethod     = "/sample.PayloadService/Echo"
	generateMethod = "/sample.PayloadService/GenerateBig"
)

type payloadService interface {
	Echo(context.Context, *wrapperspb.BytesValue) (*wrapperspb.BytesValue, error)
	GenerateBig(context.Context, *emptypb.Empty) (*wrapperspb.BytesValue, error)
}

type payloadServer struct{}

func (s *payloadServer) Echo(_ context.Context, in *wrapperspb.BytesValue) (*wrapperspb.BytesValue, error) {
	return in, nil
}

func (s *payloadServer) GenerateBig(_ context.Context, _ *emptypb.Empty) (*wrapperspb.BytesValue, error) {
	return &wrapperspb.BytesValue{Value: make([]byte, fiveMB)}, nil
}

var serviceDescription = grpc.ServiceDesc{
	ServiceName: "sample.PayloadService",
	HandlerType: (*payloadService)(nil),
	Methods: []grpc.MethodDesc{
		{
			MethodName: "Echo",
			Handler: func(srv any, ctx context.Context, decode func(any) error, interceptor grpc.UnaryServerInterceptor) (any, error) {
				in := new(wrapperspb.BytesValue)
				if err := decode(in); err != nil {
					return nil, err
				}
				if interceptor == nil {
					return srv.(payloadService).Echo(ctx, in)
				}
				info := &grpc.UnaryServerInfo{Server: srv, FullMethod: echoMethod}
				handler := func(ctx context.Context, req any) (any, error) {
					return srv.(payloadService).Echo(ctx, req.(*wrapperspb.BytesValue))
				}
				return interceptor(ctx, in, info, handler)
			},
		},
		{
			MethodName: "GenerateBig",
			Handler: func(srv any, ctx context.Context, decode func(any) error, interceptor grpc.UnaryServerInterceptor) (any, error) {
				in := new(emptypb.Empty)
				if err := decode(in); err != nil {
					return nil, err
				}
				if interceptor == nil {
					return srv.(payloadService).GenerateBig(ctx, in)
				}
				info := &grpc.UnaryServerInfo{Server: srv, FullMethod: generateMethod}
				handler := func(ctx context.Context, req any) (any, error) {
					return srv.(payloadService).GenerateBig(ctx, req.(*emptypb.Empty))
				}
				return interceptor(ctx, in, info, handler)
			},
		},
	},
	Metadata: "payload.proto",
}

func startServer(t *testing.T, opts ...grpc.ServerOption) *bufconn.Listener {
	t.Helper()

	lis := bufconn.Listen(32 * 1024 * 1024)
	srv := grpc.NewServer(opts...)
	srv.RegisterService(&serviceDescription, &payloadServer{})
	go func() {
		_ = srv.Serve(lis)
	}()
	t.Cleanup(func() {
		srv.Stop()
		_ = lis.Close()
	})
	return lis
}

func newClient(t *testing.T, lis *bufconn.Listener, opts ...grpc.DialOption) *grpc.ClientConn {
	t.Helper()

	baseOpts := []grpc.DialOption{
		grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) {
			return lis.DialContext(ctx)
		}),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
	}
	cc, err := grpc.NewClient("passthrough:///bufnet.example.com", append(baseOpts, opts...)...)
	if err != nil {
		t.Fatalf("grpc.NewClient: %v", err)
	}
	t.Cleanup(func() {
		_ = cc.Close()
	})
	return cc
}

func TestDefaultClientFailsReceivingFiveMegabyteResponse(t *testing.T) {
	lis := startServer(t)
	cc := newClient(t, lis)

	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()

	var resp wrapperspb.BytesValue
	err := cc.Invoke(ctx, generateMethod, &emptypb.Empty{}, &resp)
	if got, want := status.Code(err), codes.ResourceExhausted; got != want {
		t.Fatalf("status.Code(err) = %v, want %v (err: %v)", got, want, err)
	}
}

func TestClientWithMaxCallSendMsgSizeStillFailsReceivingFiveMegabyteResponse(t *testing.T) {
	lis := startServer(t)
	cc := newClient(t, lis, grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(tenMB)))

	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()

	var resp wrapperspb.BytesValue
	err := cc.Invoke(ctx, generateMethod, &emptypb.Empty{}, &resp)
	if got, want := status.Code(err), codes.ResourceExhausted; got != want {
		t.Fatalf("status.Code(err) = %v, want %v (err: %v)", got, want, err)
	}
}

func TestClientWithDefaultMaxCallRecvMsgSizeReceivesFiveMegabyteResponse(t *testing.T) {
	lis := startServer(t)
	cc := newClient(t, lis, grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(tenMB)))

	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()

	var resp wrapperspb.BytesValue
	err := cc.Invoke(ctx, generateMethod, &emptypb.Empty{}, &resp)
	if err != nil {
		t.Fatalf("Invoke failed: %v", err)
	}
	if got, want := len(resp.Value), fiveMB; got != want {
		t.Fatalf("received byte length = %d, want %d", got, want)
	}
}

func TestDefaultClientWithPerCallMaxCallRecvMsgSizeReceivesFiveMegabyteResponse(t *testing.T) {
	lis := startServer(t)
	cc := newClient(t, lis)

	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()

	var resp wrapperspb.BytesValue
	err := cc.Invoke(ctx, generateMethod, &emptypb.Empty{}, &resp, grpc.MaxCallRecvMsgSize(tenMB))
	if err != nil {
		t.Fatalf("Invoke with CallOption failed: %v", err)
	}
	if got, want := len(resp.Value), fiveMB; got != want {
		t.Fatalf("received byte length = %d, want %d", got, want)
	}
}

func TestDefaultServerRejectsFiveMegabyteRequest(t *testing.T) {
	lis := startServer(t)
	cc := newClient(t, lis)

	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()

	req := &wrapperspb.BytesValue{Value: make([]byte, fiveMB)}
	var resp wrapperspb.BytesValue
	err := cc.Invoke(ctx, echoMethod, req, &resp)
	if got, want := status.Code(err), codes.ResourceExhausted; got != want {
		t.Fatalf("status.Code(err) = %v, want %v (err: %v)", got, want, err)
	}
}

func TestConfiguredServerAcceptsFiveMegabyteRequest(t *testing.T) {
	lis := startServer(t, grpc.MaxRecvMsgSize(tenMB))
	cc := newClient(t, lis, grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(tenMB)))

	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()

	req := &wrapperspb.BytesValue{Value: make([]byte, fiveMB)}
	var resp wrapperspb.BytesValue
	err := cc.Invoke(ctx, echoMethod, req, &resp)
	if err != nil {
		t.Fatalf("Invoke on configured server failed: %v", err)
	}
	if got, want := len(resp.Value), fiveMB; got != want {
		t.Fatalf("received byte length = %d, want %d", got, want)
	}
}

Seeder de origen

csx-seed