ขนมปังกลมต้นฉบับกำลังบีบผ้าผืนใหญ่ลงกล่องเล็กก่อนคลี่กลับบนโต๊ะสว่าง

Bun Zstandard round trip: บีบ Uint8Array แล้วเปิดกลับโดยไม่เสีย byte

พี่โชว์Engineering

เมื่อ cache หรือ protocol ต้องเก็บข้อความซ้ำจำนวนมาก Zstandard ให้ compression ratio ที่ดีโดยยังถอดเร็วครับ Bun มีทั้ง async และ sync ผ่าน Bun.zstdCompress() / Bun.zstdCompressSync() คู่กับฟังก์ชัน decompress และรับ Uint8Array โดยตรง

WHY: ทดสอบ byte ไม่ใช่ดูว่า “อ่านข้อความได้”

Compression เป็นการแปลงไบนารี ขอบเขตที่ควรพิสูจน์คือ byte ทุกตำแหน่งกลับมาเหมือนเดิม ไม่ใช่เพียง TextDecoder อ่านแล้วดูคล้ายกัน เพราะข้อมูลจริงอาจเป็นภาพ protobuf หรือ buffer ที่มีศูนย์อยู่กลางก้อน

const source = new TextEncoder().encode(
  JSON.stringify({ events: Array.from({ length: 200 }, (_, i) => ({ i, ok: i % 3 === 0 })) }),
);

const compressed = Bun.zstdCompressSync(source, { level: 3 });
const restored = Bun.zstdDecompressSync(compressed);

if (restored.byteLength !== source.byteLength) {
  throw new Error("round trip changed the byte length");
}
for (let i = 0; i < source.byteLength; i += 1) {
  if (source[i] !== restored[i]) {
    throw new Error(`byte mismatch at index ${i}`);
  }
}
if (compressed.byteLength >= source.byteLength) {
  throw new Error("repetitive fixture should compress smaller");
}

Level สูงขึ้นไม่ได้แปลว่าดีกว่าสำหรับทุก request มันแลก CPU กับขนาด ควร benchmark ด้วย payload จริงที่ขนาดและ entropy ใกล้ production สำหรับ request path ที่ latency สำคัญ ใช้ async API หรือ worker เมื่อก้อนใหญ่แทนการบล็อก event loop ด้วย sync call

Boundary ที่ต้องมี

ข้อมูลบีบอัดขนาดเล็กอาจแตกเป็นข้อมูลใหญ่มากได้ จึงต้องจำกัดทั้งขนาด input, ขนาดผลลัพธ์ที่ยอมรับ และเวลาประมวลผล อย่ารับ blob จากผู้ใช้แล้ว decompress โดยไม่มี quota เหมือนรับกล่องสุญญากาศใบเล็กที่เปิดแล้วกลายเป็นฟูกเต็มห้อง

เก็บ content type, compression algorithm และ version ของ envelope แยกจาก payload อย่าเดาจาก byte อย่างเดียว หากข้อมูลต้องข้ามระบบที่ไม่ได้ใช้ Bun ให้ทำ fixture round trip ข้าม implementation และตรวจ checksum ที่ชั้น protocol

Recap

  • เทียบ byte ทุกตำแหน่งหลัง compress/decompress
  • เลือก sync เฉพาะก้อนเล็กและเส้นทางที่ยอมบล็อกได้
  • วางเพดานขนาดและเวลาเพื่อกัน decompression bomb
  • benchmark level ด้วย payload จริง ไม่เลือกจากตัวเลขสูงสุด