{"id":"e9d55d46a2e9520c","repo":"nestjs/nest","slug":"the-packet-length-length-exceeds-the-maximum","errorCode":null,"errorMessage":"The packet length (${length}) exceeds the maximum allowed length","messagePattern":"The packet length \\((.+?)\\) exceeds the maximum allowed length","errorType":"exception","errorClass":"MaxPacketLengthExceededException","httpStatus":null,"severity":"error","filePath":"packages/microservices/helpers/json-socket.ts","lineNumber":42,"sourceCode":"  }\n\n  protected handleSend(message: any, callback?: (err?: any) => void) {\n    this.socket.write(this.formatMessageData(message), 'utf-8', callback);\n  }\n\n  protected handleData(dataRaw: Buffer | string) {\n    const data = Buffer.isBuffer(dataRaw)\n      ? this.stringDecoder.write(dataRaw)\n      : dataRaw;\n    this.buffer += data;\n\n    // Iterative loop replaces recursion to prevent stack overflow on pipelined\n    // TCP messages (e.g. many small frames arriving in one read event).\n    while (true) {\n      if (this.buffer.length > this.maxBufferSize) {\n        const bufferLength = this.buffer.length;\n        this.buffer = '';\n        throw new MaxPacketLengthExceededException(bufferLength);\n      }\n\n      if (this.contentLength === null) {\n        const i = this.buffer.indexOf(this.delimiter);\n        /**\n         * Check if the buffer has the delimiter (#),\n         * if not, the end of the buffer string might be in the middle of a content length string\n         */\n        if (i === -1) {\n          break;\n        }\n        const rawContentLength = this.buffer.substring(0, i);\n        this.contentLength = parseInt(rawContentLength, 10);\n\n        if (isNaN(this.contentLength)) {\n          this.contentLength = null;\n          this.buffer = '';\n          throw new CorruptedPacketLengthException(rawContentLength);","sourceCodeStart":24,"sourceCodeEnd":60,"githubUrl":"https://github.com/nestjs/nest/blob/6ec0e2783d15290732447f304d8549b591b9749e/packages/microservices/helpers/json-socket.ts#L24-L60","documentation":"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().","triggerScenarios":"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.","commonSituations":"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.","solutions":["Reduce payload size sent over the TCP transport, or chunk/stream large data instead of one big message.","Increase maxBufferSize in the JsonSocket options if your payloads legitimately exceed the 128MB default.","Ensure client and server use compatible serializers so frames are well-formed (correct length prefix matching JSON length).","Switch to a transport better suited to large payloads (gRPC streaming, RMQ with message-size limits) if this recurs."],"exampleFix":"// before\n// large base64 blob over TCP -> buffer grows past 128MB\nclient.send('upload', { file: hugeBase64 }).subscribe();\n\n// after\n// chunk the upload, or raise maxBufferSize on the server's JsonSocket\nnew ServerTCP({ port: 3001 }, { maxBufferSize: 512 * 1024 * 1024 });","handlingStrategy":"validation","validationCode":"function estimateFrameSize(payload: unknown): number {\n  return JSON.stringify(payload).length;\n}\nconst MAX = 128 * 1024 * 1024; // default\nif (estimateFrameSize(payload) > MAX) {\n  throw new Error('Payload too large for TCP transport; chunk or raise maxBufferSize.');\n}","typeGuard":"const isMaxPacketLengthError = (e: unknown): boolean =>\n  /exceeds the maximum allowed length/.test((e as Error)?.message ?? '');","tryCatchPattern":"// The socket is closed by the framework when this fires; catch at the send() site.\ntry {\n  await firstValueFrom(client.send('big', payload));\n} catch (e) {\n  if (isMaxPacketLengthError(e)) { /* chunk payload or raise maxBufferSize */ }\n  else throw e;\n}","preventionTips":["Avoid sending very large messages over the TCP transport; chunk streams instead.","If large frames are legitimate, raise maxBufferSize on the server's JsonSocket options.","Ensure client and server serializers agree so frames are not accidentally inflated."],"tags":["tcp","framing","memory","json-socket","typescript"],"analyzedSha":"6ec0e2783d15290732447f304d8549b591b9749e","analyzedAt":"2026-08-03T17:42:23.673Z","schemaVersion":2}