medium.com 4 min read Original Source

A Complete Guide to MessagePack: From Basics to Advanced Usage

Hey there! If you’ve ever worked with data interchange formats like JSON, you’ve probably run into situations where things feel a bit… bloated. JSON is great because it’s human-readable and works everywhere, but when you’re dealing with high-performance apps, mobile networks, or massive datasets, that text-based overhead starts to add up. Enter MessagePack (often shortened to MsgPack or msgpack) — a binary serialization format that’s basically “JSON, but fast and small.”

In this article, we’ll go from the absolute basics (what it is and why you’d use it) all the way to advanced topics like custom extensions and streaming. I’ll explain everything step by step, with real examples, hex dumps, and code snippets from popular languages. By the end, you’ll have a solid understanding of how MessagePack works under the hood and how to use it in your projects.

What Is MessagePack?

MessagePack is a binary serialization format for exchanging data between different systems or languages. It was created by Sadayuki Furuhashi back in the late 2000s, and it’s designed to be:

  • Compact: Smaller payloads than JSON.
  • Fast: Quicker to serialize and deserialize.
  • Cross-language: Works seamlessly across dozens of programming languages.
  • Schema-less: Like JSON, you don’t need a predefined schema (unlike Protocol Buffers).

Think of it as a binary version of JSON. It supports the same kinds of data structures — numbers, strings, arrays, objects (maps) — but packs them into efficient bytes instead of readable text.

For example:

  • JSON: {“hello”: “world”} → about 20 bytes.
  • MessagePack: The same data → just 11 bytes.

The official spec lives on GitHub, and the website is msgpack.org. It’s open-source, widely adopted, and used in everything from Redis caching to real-time games.

Why Choose MessagePack? A Quick Comparison

Let’s compare it to the big players:

MessagePack shines when you want JSON-like flexibility without the text overhead. It’s schema-less (dynamic typing), supports native binary blobs, and doesn’t force you to define interfaces upfront like Protobuf. But if you need maximum compression and strict validation, Protobuf might edge it out.

Real-world wins:

  • Smaller network payloads → better for mobile data.
  • Faster parsing → great for games (e.g., Unity) or microservices.
  • Used by companies like Redis, Fluentd, and Unity for internal messaging.

Core Concepts: The Type System

MessagePack defines a simple but powerful set of data types. Everything is serialized into bytes with a 1-byte header that tells the deserializer what type it is.

Here are all the supported types:

  1. Nil (null) — Represents absence of value.
  2. Boolean — true or false.
  3. Integer — Signed or unsigned, from -²⁶³ to ²⁶⁴-1.
  4. Float — 32-bit or 64-bit IEEE 754 (double precision by default).
  5. String — UTF-8 encoded text.
  6. Binary — Raw bytes (great for images, files, etc.).
  7. Array — Ordered list of values.
  8. Map — Key-value pairs (keys can be any type, usually strings).
  9. Extension — Custom types (more on this later). Includes the built-in Timestamp.

That’s it! No dates, no decimals natively — but you can handle those via extensions.

How the Binary Format Works

The magic is in the compact encoding. MessagePack uses different “families” of formats based on size:

  • Fixed formats for small values (embedded in the header byte).
  • Variable formats for larger ones (with 1, 2, or 4-byte length prefixes).

All multi-byte numbers are big-endian.

Here’s a simplified table of the most common format codes (in hex):

Key rule: Always use the smallest possible format. A 5-byte string uses fixstr (header 0xa5), not the longer str 8.

Basic Encoding Examples (with Hex Dumps)

Let’s see some real bytes:

  1. null → c0
  2. true → c3
  3. false → c2
  4. Integer 0 → 00
  5. Integer 123 → 7b
  6. Integer -1 → ff
  7. Large int 100000 → ce 00 01 86 a0
  8. Float 3.14 → cb 40 09 1e b8 51 eb 85 1f (double)
  9. String “hello” → a5 68 65 6c 6c 6f
  10. Binary [0x01, 0x02] → c4 02 01 02
  11. Array [1, 2, “three”] → 93 01 02 a5 74 68 72 65 65
  12. Map {“a”: 1, “b”: 2} → 82 a1 61 01 a1 62 02

These are tiny compared to JSON!

Advanced Features

Extension Types

This is where MessagePack gets powerful. Extensions let you define custom types with a signed 8-bit type code and a byte payload.

  • Type codes 0 to 127: For your app.
  • -128 to -1: Reserved (e.g., -1 is Timestamp).

Example: Send a custom “UserID” as ext type 10 with 8-byte data.

Built-in Timestamp Extension (type -1)

Timestamps are encoded efficiently:

  • 32-bit: seconds only (up to 2106).
  • 64-bit: 30-bit nanos + 34-bit seconds.
  • 96-bit: full 64-bit seconds + 32-bit nanos.

Example: Unix epoch + 1 second → d6 ff 00 00 00 01 (fixext 4, type -1, 4-byte seconds).

Streaming

Many libraries support streaming — serialize/deserialize objects one by one without loading everything into memory. Perfect for logs or large datasets.

Compatibility Notes

  • Old versions used “raw” for both strings and binary.
  • New spec separates str (UTF-8) and bin (raw bytes).
  • Libraries often have a “compatibility mode” for older data.

Using MessagePack in Code

There are excellent libraries in almost every language. Here are some practical examples:

Python (msgpack or ormsgpack)

import msgpack
data = {"name": "Alice", "age": 30, "active": True}
packed = msgpack.packb(data)          # b'x83xa4namexa5Alicexa3agex1exa6activexc3'
unpacked = msgpack.unpackb(packed)
print(unpacked)                       # {'name': 'Alice', 'age': 30, 'active': True}
import msgpack
data = {"name": "Alice", "age": 30, "active": True}
packed = msgpack.packb(data)          # b'x83xa4namexa5Alicexa3agex1exa6activexc3'
unpacked = msgpack.unpackb(packed)
print(unpacked)                       # {'name': 'Alice', 'age': 30, 'active': True}

JavaScript (Node.js with @msgpack/msgpack)

const { encode, decode } = require("@msgpack/msgpack");
const obj = { nil: null, integer: 42, string: "hello" };
const buffer = encode(obj);
console.log(buffer);                  // Uint8Array
const restored = decode(buffer);
console.log(restored);
const { encode, decode } = require("@msgpack/msgpack");
const obj = { nil: null, integer: 42, string: "hello" };
const buffer = encode(obj);
console.log(buffer);                  // Uint8Array
const restored = decode(buffer);
console.log(restored);

C# (.NET with MessagePack-CSharp — super fast!)

<button data-code="using MessagePack;
[MessagePackObject]
public class Person {
[Key(0)] public string Name { get; set; }
[Key(1)] public int Age { get; set; }
}
var person = new Person { Name = "Bob", Age = 25 };
byte[] bytes = MessagePackSerializer.Serialize(person);
Person restored = MessagePackSerializer.Deserialize(bytes);” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

using MessagePack;
[MessagePackObject]
public class Person {
    [Key(0)] public string Name { get; set; }
    [Key(1)] public int Age { get; set; }
}
var person = new Person { Name = "Bob", Age = 25 };
byte[] bytes = MessagePackSerializer.Serialize(person);
Person restored = MessagePackSerializer.Deserialize<Person>(bytes);
using MessagePack;
[MessagePackObject]
public class Person {
    [Key(0)] public string Name { get; set; }
    [Key(1)] public int Age { get; set; }
}
var person = new Person { Name = "Bob", Age = 25 };
byte[] bytes = MessagePackSerializer.Serialize(person);
Person restored = MessagePackSerializer.Deserialize<Person>(bytes);

Go (with ugorji/go codec)

import "github.com/ugorji/go/codec"
var mh codec.MsgpackHandle
enc := codec.NewEncoderBytes(&bytes, &mh)
enc.Encode(map[string]int{"x": 1, "y": 2})
import "github.com/ugorji/go/codec"
var mh codec.MsgpackHandle
enc := codec.NewEncoderBytes(&bytes, &mh)
enc.Encode(map[string]int{"x": 1, "y": 2})

Many libraries add extras like LZ4 compression, zero-copy, or typeless serialization.

Limitations and Best Practices

  • Max sizes: Strings/binary ≤ 4GB-1, arrays/maps ≤ 4GB-1 elements.
  • No built-in decimals or dates → use extensions.
  • Security: Validate input, some libraries have options to prevent hash-DoS attacks on maps.
  • Best practice: Use the official or high-performance library for your language (e.g., MessagePack-CSharp for .NET, msgpack-rust for Rust).

Wrapping Up

MessagePack is a fantastic middle ground: all the flexibility of JSON with the efficiency of a binary protocol. Whether you’re building a real-time game, optimizing API traffic, or just need a fast cache format, it’s worth trying.

Give it a spin in your next project — you’ll likely notice the speed and size improvements immediately. If you have questions or want examples in a specific language, let me know! 🚀