nestjs/nest · error · MaxPacketLengthExceededException

The packet length (${length}) exceeds the maximum allowed le

Error message

The packet length (${length}) exceeds the maximum allowed length

What it means

Thrown as MaxPacketLengthExceededException from JsonSocket.handleData() when this.buffer.length grows past this.maxBufferSize (default DEFAULT_MAX_BUFFER_SIZE = 128MB of characters). The NestJS TCP transport frames messages as '<length>#<json>'; if the accumulated buffer exceeds the cap before a complete frame is parsed, the socket discards the buffer and throws to protect the process from unbounded memory growth. The error is emitted on the socket 'error' event and the socket is torn down by TcpSocket.onData().

Source

Thrown at packages/microservices/helpers/json-socket.ts:42

  }

  protected handleSend(message: any, callback?: (err?: any) => void) {
    this.socket.write(this.formatMessageData(message), 'utf-8', callback);
  }

  protected handleData(dataRaw: Buffer | string) {
    const data = Buffer.isBuffer(dataRaw)
      ? this.stringDecoder.write(dataRaw)
      : dataRaw;
    this.buffer += data;

    // Iterative loop replaces recursion to prevent stack overflow on pipelined
    // TCP messages (e.g. many small frames arriving in one read event).
    while (true) {
      if (this.buffer.length > this.maxBufferSize) {
        const bufferLength = this.buffer.length;
        this.buffer = '';
        throw new MaxPacketLengthExceededException(bufferLength);
      }

      if (this.contentLength === null) {
        const i = this.buffer.indexOf(this.delimiter);
        /**
         * Check if the buffer has the delimiter (#),
         * if not, the end of the buffer string might be in the middle of a content length string
         */
        if (i === -1) {
          break;
        }
        const rawContentLength = this.buffer.substring(0, i);
        this.contentLength = parseInt(rawContentLength, 10);

        if (isNaN(this.contentLength)) {
          this.contentLength = null;
          this.buffer = '';
          throw new CorruptedPacketLengthException(rawContentLength);

View on GitHub (pinned to 6ec0e2783d)

Solutions

  1. Reduce payload size sent over the TCP transport, or chunk/stream large data instead of one big message.
  2. Increase maxBufferSize in the JsonSocket options if your payloads legitimately exceed the 128MB default.
  3. Ensure client and server use compatible serializers so frames are well-formed (correct length prefix matching JSON length).
  4. Switch to a transport better suited to large payloads (gRPC streaming, RMQ with message-size limits) if this recurs.

Example fix

// before
// large base64 blob over TCP -> buffer grows past 128MB
client.send('upload', { file: hugeBase64 }).subscribe();

// after
// chunk the upload, or raise maxBufferSize on the server's JsonSocket
new ServerTCP({ port: 3001 }, { maxBufferSize: 512 * 1024 * 1024 });
Defensive patterns

Strategy: validation

Validate before calling

function estimateFrameSize(payload: unknown): number {
  return JSON.stringify(payload).length;
}
const MAX = 128 * 1024 * 1024; // default
if (estimateFrameSize(payload) > MAX) {
  throw new Error('Payload too large for TCP transport; chunk or raise maxBufferSize.');
}

Type guard

const isMaxPacketLengthError = (e: unknown): boolean =>
  /exceeds the maximum allowed length/.test((e as Error)?.message ?? '');

Try / catch

// The socket is closed by the framework when this fires; catch at the send() site.
try {
  await firstValueFrom(client.send('big', payload));
} catch (e) {
  if (isMaxPacketLengthError(e)) { /* chunk payload or raise maxBufferSize */ }
  else throw e;
}

Prevention

When it happens

Trigger: A single message (or accumulated pipelined messages) larger than maxBufferSize arriving over a TCP microservice link. A malformed framing where the length prefix is huge and the JSON body keeps streaming in. Custom serializer that emits very large payloads (big blobs, base64 files) over TCP. maxBufferSize lowered below the real message size.

Common situations: Streaming large binary payloads as base64 over the TCP transport. Mismatched serializer/deserializer between client and server producing oversized frames. Lowering maxBufferSize for memory reasons while still sending large messages. Network replay/corruption that injects garbage inflating the buffer.

Related errors


AI-assisted analysis of nestjs/nest@6ec0e2783d (2026-08-03). Data as JSON: /data/errors/e9d55d46a2e9520c.json. Report an issue: GitHub.