Every Python service serializes JSON somewhere in its hot path, and every team eventually hits the same wall: the standard library’s json module is flexible but slow, while the “fast” replacements that proliferated in the 2010s were fast partly by being careless. Datetimes, big integers, non-string dictionary keys, invalid UTF-8 — each library made its own quiet decisions, and production incidents followed. That pain is exactly the gap orjson targets: aggressive about speed, conservative about semantics.
What makes orjson unusual among fast Python libraries is that it is not a C extension at all. It is a Rust crate, compiled to a cdylib and loaded by CPython as a native module. Its serialization core depends on a handful of small, focused crates — no serde data model, no general-purpose JSON framework — just hand-written formatting code aimed directly at the CPython C API.
This post walks the actual master tree of orjson (version 3.13.0) rather than an idealized summary. The layout changed substantially when the serializer was rewritten for 3.12, so we follow the code as it exists today: src/lib.rs for the binding layer, src/serialize/ and src/deserialize/ for the two cores, and build.rs for the machinery stitching the C and Rust halves together. Readers of our earlier runtime tours will recognize much of the vocabulary.
orjson at a glance: the typed Python surface, the binding layer, and the two Rust cores that do the real work.
Reading the overview from left to right:
- orjson_init_exec, L100 — the module’s exec slot registers
dumps,loads, theFragmenttype, fourteenOPT_*integer constants and both exception classes; there is no Python-level module init at all. - INDENT_2 and friends, L6 — every serialization option is one bit of a
u32;OPT_INDENT_2is bit 0,OPT_NON_STR_KEYSis bit 2, and two legacy flags are now hardcoded to zero. - pyobject_to_obtype_likely, L47 — the hot-path type check is raw pointer equality against cached
PyTypeObjectpointers, sostr,int,dictand friends are classified with no string comparison. - ContainerSerializer, L66 — the whole serialization walk lives in one
repr(align(128))struct carrying the output buffer, recursion depth and the user’sdefaultcallable. - write_datetime, L70 — datetimes are hand-formatted into RFC 3339, including the spec’s rule for rounding offsets whose seconds are not a whole minute.
- write_integer, L39 — integers are printed by the
itoapcrate and finite floats byzmij; infinity and NaN quietly becomenull. - Deserializer::deserialize, L25 — the trivial documents
[],{}and""short-circuit before any parser is invoked. - deserialize, L61 — loading goes through the vendored yyjson C parser, whose tape is walked into Python lists and dicts using a pool allocator fed by
PyMem_Malloc. - KeyMap, L37 — object keys are hashed with xxh3 and looked up in a 2048-entry direct-mapped cache of already-interned strings.
The detail view: the serializer's object walk and writer stack on the left, the loader's input handling, yyjson backend and key cache on the right.
A C extension, but written in Rust
The binding layer is a case study in how little machinery you need to expose a Python module from Rust. The crate declares crate-type = ["cdylib"], builds against pyo3-ffi — the raw, unsafe C-API bindings rather than the ergonomic safe wrapper — and exports a conventional PyInit_orjson. Module initialization uses the multi-phase API: a Py_mod_exec slot points at the init function, Python 3.13+ slots advertise GIL status, and the module declares Py_mod_multiple_interpreters as not supported, an honest statement that its global caches are not subinterpreter-safe.
orjson_init_exec, L100 does everything a Python package would normally do at import time. It caches pointers to built-in types, interns the attribute strings the serializer will need — including __dataclass_fields__ for dataclass detection — imports uuid.UUID, enum.EnumMeta and dataclasses._FIELD, and constructs the exception classes. Those construction choices repay a second read in typeref.rs: orjson.JSONEncodeError is literally assigned PyExc_TypeError, so a bare except TypeError catches serialization failures, while orjson.JSONDecodeError is created with PyErr_NewException as a subclass of the standard library’s json.JSONDecodeError, keeping existing except clauses working.
Error reporting follows interpreter conventions exactly. raise_loads_exception, L14 builds the same (msg, doc, pos) tuple that json.JSONDecodeError expects, converting the parser’s byte offset into a character position. When a user-supplied default callable raises, the dumps side captures the in-flight exception and re-raises the encode error with PyException_SetCause, preserving the __cause__ chain a Python developer expects in a traceback.
One more detail keeps the memory story clean: a custom #[global_allocator] in alloc.rs forwards every Rust allocation to PyMem_Malloc and PyMem_Free. Rust and Python objects share the interpreter’s allocator — and with it pymetrics’ view of the process. It is the kind of integration that only becomes obvious after working inside the cpython runtime for a while.
From serde to itoap and zmij: the serialization rewrite
The changelog for 3.12 is blunt: “Serialization implementation substantially rewritten.” The current tree shows what that means. Earlier generations leaned on the serde ecosystem; the 3.13 tree contains no serde dependency at all. The serializer is now a direct interpreter of Python objects: an ObType enum with nineteen variants, populated by a two-tier type check.
The tiering is where the speed comes from. The likely path compares the object’s type pointer against cached pointers for the eight most common types — str, int, bool, None, float, list, dict, datetime — and returns immediately. Only on a full miss does execution fall into a cold, #[inline(never)] path that inspects subclass flags via PyType_GetFlags, detects Enum by comparing an object’s metatype, probes for __dataclass_fields__, and finally, behind OPT_SERIALIZE_NUMPY, looks for numpy scalars and arrays. The walk itself lives in ContainerSerializer, whose state is one 128-byte-aligned struct — the alignment keeps hot per-instance state from straddling cache-line boundaries — with the recursion counter stopping nested containers at 254 levels.
The leaf writers are the most engineered part. Integer output goes through itoap, which writes digits directly into the output buffer. Float output goes through zmij, a shortest-round-trip formatter writing into a stack buffer — no intermediate String, no allocation per scalar. Strings get a 256-entry NEED_ESCAPED table plus an SSE2 scanner that copies sixteen bytes per stride, using a saturating-subtract trick to detect control characters in the same comparison that finds quotes and backslashes; bytes needing escape are resolved through an 8-byte-per-entry table (QUOTE_TAB, adapted from cloudwego’s sonic-rs) that supplies text and length in one store. On CPUs reporting AVX-512VL, a function pointer installed at init swaps in a 512-bit scanner — format_str.rs calls is_x86_feature_detected!("avx512vl") once, never again.
None of this is idiomatic general-purpose rust application code; it is deliberately flat, benchmarked code with cold_path! markers on branches that must never dominate a profile. The Cargo release profile agrees: lto = "fat", panic = "abort", codegen-units = 1 — one solid unit, so cross-crate inlining collapses digits, mantissas and buffer arithmetic into straight-line machine code.
Loading JSON: the vendored yyjson core and its key cache
Deserialization is where the architecture changed most visibly. src/deserialize/ is layered: an input adapter, a thin core, and a backend. The adapter normalizes anything the stub promises — bytes, bytearray, memoryview, str — into a validated UTF-8 slice using the simdutf8 crate’s AVX2 or NEON validators; empty input is rejected up front.
The backend vendors the yyjson C library under include/yyjson/ and compiles it directly in build.rs, with preprocessor switches that switch off everything unused: the writer, incremental parsing, non-standard extensions, and yyjson’s own UTF-8 validation, which would be redundant since orjson validated already. The parser’s maximum depth is pinned at 1024. From yyjson, orjson keeps the tape: a flat array of tagged values where each entry’s tag distinguishes string, uint64, int64, double, null, true, false, array and object. The Rust walker dispatches on that tag and builds Python objects through the same typed ref wrappers the serializer uses, while a pool allocator carved from one PyMem_Malloc block — sized roughly as (len/2)*24 + 256 bytes — holds the tape, so parsing costs one allocation before any Python object exists.
On top of the tape walk sits a long-standing optimization: the object-key cache. Real JSON repeats the same keys across thousands of objects, and fresh PyUnicode objects for each are pure waste. The loader hashes each key with xxh3_64 and probes a 2048-entry, direct-mapped cache with round-robin replacement; a hit returns the already-interned string with an incremented refcount, and keys longer than 64 bytes bypass the cache because collisions would cost more than they save. The cache is compiled out entirely under free-threaded builds, where a global mutable cache would be a contention point.
Strictness as a design choice
What separates orjson from the fast-JSON graveyard is that speed never came from loosening the spec. With OPT_STRICT_INTEGER, integers outside the 53-bit range IEEE doubles represent exactly are rejected — the bounds are hardcoded as ±9007199254740991, cited straight from RFC 7159 section 6. Without the flag, 64-bit integers still round-trip exactly, more than JavaScript-facing serializers can promise.
Datetime handling shows the same discipline. time objects with tzinfo are rejected outright; naive datetimes serialize only with OPT_NAIVE_UTC; offsets with non-whole-minute seconds are rounded to the nearest minute, exactly as RFC 3339 section 5.8 prescribes. And the conservatism is enforced mechanically: the test directory is a pytest suite, including the JSON Checker acceptance files, and test_api.py, L15 pins the loader’s recursion limit at 1024 — matching the parser depth the build pins for yyjson. That suite, built on the pytest conventions from our pytest tour, is the honest backbone behind the benchmarks.
Honest Limits
The source is candid about what orjson will not do. Enjoyed this post? Never miss out on future posts by following us build.rs hard-fails for anything that is not CPython — PyPy and GraalPy are named and rejected — and free-threaded CPython builds are gated behind an explicit ORJSON_BUILD_FREETHREADED environment variable, so the default wheel is the classic GIL build. dumps returns bytes, never str — correct for network I/O, but string-handling code needs one decode step. The loader accepts only bytes-like input or str, no file objects or streams, and infinity or NaN serialize as null, matching JSON’s number grammar rather than Python’s float grammar. The legacy OPT_SERIALIZE_DATACLASS and OPT_SERIALIZE_UUID flags are compile-time zeros, and 3.13 stopped publishing 32-bit Windows wheels. None of this is hidden; each decision sits in the exact files this tour linked, which is the real value of reading the source instead of the README.