The short version

  • A custom binary protocol writes only the values, in an order both sides agree on, so it skips the field names, quotes, brackets and commas that JSON sends in every message.
  • In my Python benchmark one player's game state was 301 bytes as JSON and 75 bytes in a custom binary format, and 50 players at 60 updates a second came to 0.90 MB a second per client as JSON against 0.22 MB as binary.
  • Compressing JSON closes most of the size gap, because repeated field names compress well, but zlib took longer per message than encoding the JSON did.
  • A custom format isn't automatically faster on the CPU. In Python, the C-based json and msgpack modules decoded faster than my hand-written binary decoder, so measure it in your own language.
  • JSON is the right default for REST APIs and normal web apps. For performance-critical systems like game servers, measure your payload at your real update rate and consider Protocol Buffers, MessagePack or a format of your own.

A custom binary protocol sends the same data as JSON in far fewer bytes, because it drops the field names, quotes, brackets and commas and writes only the values, in an order both sides agree on. In my Python benchmark, one player's game state was 301 bytes as JSON and 75 bytes in a custom binary format, and a broadcast of 50 players went from 15 KB to 3.7 KB.

This page builds that benchmark: a small multiplayer game server that can talk JSON or binary, then a script that measures how big and how fast JSON, compact JSON, MessagePack and a hand-written binary format are. The video above covers the same demo. Every number here was measured on my machine with the code below, so they differ a little from the 311 and 104 bytes in the video, which used an earlier version of the code.

Why JSON costs so many bytes

JSON is the standard on the web, and every REST API you've written probably uses it. I'm not saying that's wrong. For a web app it makes a lot of sense.

But look at what one player in a game sends:

{ "id": "4eaa67ec-dc57-42f5-84ea-2faa42b3de0b", "username": "player1", "x": -365.64, "y": 42.37, "z": 263.77, "rotation": 91.82, "velocity_x": -0.05, "velocity_y": 0.0, "velocity_z": -0.51, "health": 100, "mana": 80, "stamina": 95, "level": 42, "experience": 99513, "equipment": [ 101, 205, 310, 412 ] } 

On the wire that's one line, and it still comes to 301 bytes. Most of it isn't data. Every message carries the curly brackets, the double quotes, the colons and the commas, and every player repeats the words username, rotation, health and mana, even though both sides already know exactly what the fields are. With 20 players you send those words 20 times.

The values are wasteful too. The ID is a UUID written out as 36 characters of text plus quotes, when the UUID itself is 16 bytes. The number 99513 is five characters, where a 4-byte integer holds anything up to about 4.2 billion.

What a custom binary protocol sends instead

A binary protocol writes just the list of values, one after the other. Instead of "experience": 99513, it writes the four bytes of the number 99513 at a position the receiver knows to read it from. Here's the layout I use for one player:

Field Type Bytes
ID UUID 16
Username length unsigned byte 1
Username UTF-8 text 7 for "player1"
x, y, z, rotation, velocity x/y/z 32-bit float each 28
Health, mana, stamina, level 16-bit integer each 8
Experience 32-bit integer 4
Number of equipment items unsigned byte 1
Equipment item IDs 16-bit integer each 8 for four items

That's 73 bytes per player, plus 2 bytes at the start of each broadcast for the player count, which is where the 75 comes from. Text can't have a fixed size, so the username is written with its length in front, and so is the equipment list.

The price is that the receiver has to know the layout. A JSON message explains itself and a binary one is meaningless without the code that wrote it.

The demo: a game server in Python

The setup is the one from the video. A central server keeps every connected player's state and broadcasts all of it to every client, because every player needs to know where every other player is. Clients connect over TCP sockets, and the message format is a flag, so you can run the same server with JSON and then with binary and compare.

I used Python 3.14. The game itself only uses the standard library, and MessagePack is only for the benchmark:

mkdir binary-vs-json && cd binary-vs-json python3 -m venv .venv source .venv/bin/activate pip install msgpack 

Three files:

binary-vs-json/ ├── protocol.py # player state, JSON and binary encoders ├── game.py # the server and the client └── bench.py # the size and speed comparison 

protocol.py

import json import random import struct import uuid # One player's state, in a fixed order. The binary format depends on this order. # id (16-byte UUID), username, position x/y/z, rotation, velocity x/y/z, # health, mana, stamina, level, experience, equipment item IDs HEADER = struct.Struct("<16sB") # UUID bytes, username length BODY = struct.Struct("<7f3HHI") # 7 floats, health/mana/stamina, level, experience ITEM = struct.Struct("<H") # one equipment item ID COUNT = struct.Struct("<H") # number of players in a broadcast def new_player(username): return { "id": str(uuid.uuid4()), "username": username, "x": round(random.uniform(-500, 500), 2), "y": round(random.uniform(0, 50), 2), "z": round(random.uniform(-500, 500), 2), "rotation": round(random.uniform(0, 360), 2), "velocity_x": round(random.uniform(-5, 5), 2), "velocity_y": 0.0, "velocity_z": round(random.uniform(-5, 5), 2), "health": 100, "mana": 80, "stamina": 95, "level": random.randint(1, 60), "experience": random.randint(0, 250_000), "equipment": [101, 205, 310, 412], } # ---------- JSON ---------- def encode_json(players): return json.dumps(players).encode() def decode_json(data): return json.loads(data) # ---------- Custom binary ---------- def encode_binary(players): out = bytearray(COUNT.pack(len(players))) for p in players: name = p["username"].encode() out += HEADER.pack(uuid.UUID(p["id"]).bytes, len(name)) out += name out += BODY.pack( p["x"], p["y"], p["z"], p["rotation"], p["velocity_x"], p["velocity_y"], p["velocity_z"], p["health"], p["mana"], p["stamina"], p["level"], p["experience"], ) out += bytes([len(p["equipment"])]) for item in p["equipment"]: out += ITEM.pack(item) return bytes(out) def decode_binary(data): (count,) = COUNT.unpack_from(data, 0) offset = COUNT.size players = [] for _ in range(count): raw_id, name_len = HEADER.unpack_from(data, offset) offset += HEADER.size username = data[offset:offset + name_len].decode() offset += name_len x, y, z, rot, vx, vy, vz, hp, mp, sp, lvl, xp = BODY.unpack_from(data, offset) offset += BODY.size n_items = data[offset] offset += 1 equipment = [ITEM.unpack_from(data, offset + i * ITEM.size)[0] for i in range(n_items)] offset += n_items * ITEM.size players.append({ "id": str(uuid.UUID(bytes=raw_id)), "username": username, "x": x, "y": y, "z": z, "rotation": rot, "velocity_x": vx, "velocity_y": vy, "velocity_z": vz, "health": hp, "mana": mp, "stamina": sp, "level": lvl, "experience": xp, "equipment": equipment, }) return players FORMATS = { "json": (encode_json, decode_json), "binary": (encode_binary, decode_binary), } 

The JSON side is two lines. The binary side is all of Python's struct module, which packs numbers into bytes from a format string. <7f3HHI means little-endian, then seven 32-bit floats (f), three 16-bit unsigned integers (H), one more H for the level and a 32-bit unsigned integer (I) for experience. The decoder reads the same formats back in the same order and moves an offset along the bytes as it goes.

One thing to know about 32-bit floats: they hold about seven significant digits, so -365.64 comes back as -365.6400146484375. For a position in a game that's fine. For money it isn't, and you'd send an integer number of cents instead.

game.py

import argparse import asyncio import struct from protocol import FORMATS, new_player LENGTH = struct.Struct("<I") # every message starts with its size in bytes players = {} # writer -> that client's player state async def handle_client(reader, writer): player = new_player(f"player{len(players) + 1}") players[writer] = player print(f"{player['username']} joined ({len(players)} connected)") try: await reader.read() # wait until the client disconnects finally: del players[writer] print(f"{player['username']} left ({len(players)} connected)") async def broadcast_loop(encode, rate): while True: await asyncio.sleep(1 / rate) if not players: continue for p in players.values(): # pretend everyone keeps moving p["x"] = round(p["x"] + p["velocity_x"], 2) p["z"] = round(p["z"] + p["velocity_z"], 2) payload = encode(list(players.values())) message = LENGTH.pack(len(payload)) + payload for writer in list(players): try: writer.write(message) await writer.drain() except ConnectionError: pass # handle_client removes it print(f"broadcast size: {len(payload)} bytes for {len(players)} players") async def run_server(port, fmt, rate): encode, _ = FORMATS[fmt] server = await asyncio.start_server(handle_client, "127.0.0.1", port) print(f"server listening on port {port}, format {fmt}") async with server: await asyncio.gather(server.serve_forever(), broadcast_loop(encode, rate)) async def run_client(port, fmt): _, decode = FORMATS[fmt] reader, _ = await asyncio.open_connection("127.0.0.1", port) while True: (size,) = LENGTH.unpack(await reader.readexactly(LENGTH.size)) state = decode(await reader.readexactly(size)) print(f"received {size} bytes:") for p in state: print(f" {p['username']} {p['id']} at ({p['x']:.2f}, {p['z']:.2f})") if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--mode", choices=["server", "client"], required=True) parser.add_argument("--format", choices=list(FORMATS), required=True) parser.add_argument("--port", type=int, default=8080) parser.add_argument("--rate", type=float, default=1, help="broadcasts per second") args = parser.parse_args() try: if args.mode == "server": asyncio.run(run_server(args.port, args.format, args.rate)) else: asyncio.run(run_client(args.port, args.format)) except (KeyboardInterrupt, asyncio.IncompleteReadError): pass 

Each client that connects gets a new player. The broadcast loop moves everyone a little, encodes the whole player list in the chosen format and sends it to every client, then prints the size.

TCP is a stream of bytes with no message boundaries, so every message starts with its own length as a 4-byte integer. The client reads those 4 bytes, then reads exactly that many more and decodes them. You need some framing like this whatever the format is. JSON over a raw socket needs it too.

Run it

Start the server in JSON mode, then a client in each of two more terminals:

python game.py --mode server --format json python game.py --mode client --format json python game.py --mode client --format json 

The server prints the size of every broadcast. With one client connected and then two:

server listening on port 8080, format json player1 joined (1 connected) broadcast size: 295 bytes for 1 players broadcast size: 297 bytes for 1 players player2 joined (2 connected) broadcast size: 598 bytes for 2 players broadcast size: 598 bytes for 2 players broadcast size: 598 bytes for 2 players broadcast size: 595 bytes for 2 players player1 left (1 connected) player2 left (0 connected) 

Stop everything with Ctrl+C and do the same with --format binary:

server listening on port 8080, format binary player1 joined (1 connected) broadcast size: 75 bytes for 1 players broadcast size: 75 bytes for 1 players broadcast size: 75 bytes for 1 players player2 joined (2 connected) broadcast size: 148 bytes for 2 players broadcast size: 148 bytes for 2 players broadcast size: 148 bytes for 2 players player1 left (1 connected) player2 left (0 connected) 

Same game, same players, about a quarter of the bytes. Notice the JSON size moves around as players move, because -95.86 and -395.54 take a different number of characters. The binary size never changes, since a float is always 4 bytes.

The benchmark: JSON vs MessagePack vs custom binary

One broadcast a second is a demo. A game that runs at 60 frames per second sends 60 updates a second, and the broadcast holds every player. So the real question is what 50 players at 60 updates a second costs. bench.py measures that, and adds two more formats: JSON without the spaces after commas and colons, and MessagePack, an existing binary format that keeps the field names but stores them and the values as bytes instead of text.

import json import random import timeit import zlib import msgpack from protocol import decode_binary, decode_json, encode_binary, encode_json, new_player PLAYERS = 50 RATE = 60 # broadcasts per second random.seed(1) players = [new_player(f"player{i + 1}") for i in range(PLAYERS)] formats = { "JSON": (encode_json, decode_json), "JSON, no spaces": ( lambda ps: json.dumps(ps, separators=(",", ":")).encode(), json.loads, ), "MessagePack": (msgpack.packb, msgpack.unpackb), "Custom binary": (encode_binary, decode_binary), } print(f"{PLAYERS} players, {RATE} broadcasts per second\n") print(f"{'format':<16}{'1 player':>10}{'50 players':>12}{'zipped':>8}" f"{'per client':>13}{'encode':>10}{'decode':>10}{'zip time':>10}") for name, (encode, decode) in formats.items(): one = len(encode(players[:1])) payload = encode(players) compressed = len(zlib.compress(payload)) per_client = len(payload) * RATE / 1_000_000 # MB/s each client receives runs = 2000 enc_us = timeit.timeit(lambda: encode(players), number=runs) / runs * 1e6 dec_us = timeit.timeit(lambda: decode(payload), number=runs) / runs * 1e6 zlib_us = timeit.timeit(lambda: zlib.compress(payload), number=runs) / runs * 1e6 print(f<...
Source:https://dev.to/hassan_aziz_88b11714fef8b/custom-binary-protocol-vs-json-with-a-python-benchmark-36db