nats-io/nats-server · error

error writing to compression writer: %w

Error message

error writing to compression writer: %w

What it means

LocalCache.Compress compresses a cache entry with an s2.Writer. If io.CopyN into the writer fails, the error is wrapped with certidp.ErrCannotWriteCompressed ("error writing to compression writer: %w").

Source

Thrown at server/ocsp_responsecache.go:350

	for _, resp := range c.cache {
		switch resp.RespStatus {
		case ocsp.Good:
			c.stats.Goods++
		case ocsp.Revoked:
			c.stats.Revokes++
		case ocsp.Unknown:
			c.stats.Unknowns++
		}
	}
}

func (c *LocalCache) Compress(buf []byte) ([]byte, error) {
	bodyLen := int64(len(buf))
	var output bytes.Buffer
	writer := s2.NewWriter(&output)
	input := bytes.NewReader(buf[:bodyLen])
	if n, err := io.CopyN(writer, input, bodyLen); err != nil {
		return nil, fmt.Errorf(certidp.ErrCannotWriteCompressed, err)
	} else if n != bodyLen {
		return nil, fmt.Errorf(certidp.ErrTruncatedWrite, n, bodyLen)
	}
	if err := writer.Close(); err != nil {
		return nil, fmt.Errorf(certidp.ErrCannotCloseWriter, err)
	}
	return output.Bytes(), nil
}

func (c *LocalCache) Decompress(buf []byte) ([]byte, error) {
	bodyLen := int64(len(buf))
	input := bytes.NewReader(buf[:bodyLen])
	reader := io.NopCloser(s2.NewReader(input))
	output, err := io.ReadAll(reader)
	if err != nil {
		return nil, fmt.Errorf(certidp.ErrCannotReadCompressed, err)
	}
	return output, reader.Close()

View on GitHub (pinned to 3a66a489d2)

Solutions

  1. Retry the Put operation (transient failure)
  2. Check host memory availability; s2 compression allocates buffers
  3. Upgrade the NATS server / golang s2 library to pick up compression bug fixes

Example fix

// before
compressed, err := cache.Compress(buf)  // err surfaces from s2 writer
// after
if err != nil {
    return fmt.Errorf("compressing cache entry failed: %w", err) // retry Put
}
Defensive patterns

Strategy: try-catch

Validate before calling

if len(buf) == 0 { return errors.New("nothing to compress") }

Try / catch

compressed, err := cache.Compress(buf)
if err != nil {
    var we *s2.Writer // log and retry the Put
    log.Printf("cache compress failed: %v; retrying", err)
    compressed, err = cache.Compress(buf)
    if err != nil { return err }
}

Prevention

When it happens

Trigger: Put() stores a response body and Compress's io.CopyN(writer, input, bodyLen) returns a non-nil error from the s2 writer writing to the underlying bytes.Buffer.

Common situations: Memory pressure/allocation failure in the s2 writer, pathological input causing writer errors, or a corrupted internal buffer state in the response cache.

Related errors


AI-assisted analysis of nats-io/nats-server@3a66a489d2 (2026-09-02). Data as JSON: /api/errors/785df33897b42698. Report an issue: GitHub.