backgroundbackground
Updated October 14, 2026 in
Rethinking Serialization in Rust
blog image
Backend Guru
1 min read
1 Views
1 min read
1 Views
blog image
Backend Guru
blog image
Table of Contents
Table of Contents

Share this article

blogDetail.empower

blogDetail.digitalFuture

blogDetail.hook
blogDetail.linkToServices

Table of Contents

Serde has been the default answer to Rust serialization for a decade, and for most projects it is still the right one. But rust serialization design is not a solved problem: the trait shape Serde chose in 2016 forces real, measurable compromises on deeply nested untrusted input, arbitrary-precision numbers, and streaming.

A serialization design is the contract between a format's parser and your types: who drives whom, where state lives, and what information survives buffering. Serde puts the type in the driver's seat. A newer experiment called Deser swaps those halves — the format pushes events into heap-allocated sinks — and the trade-offs it exposes are worth understanding even if you never migrate.

Why Serde's design is hard to replace

Serde is not just a library; it is a load-bearing part of the ecosystem. Because of Rust's orphan rule, every third-party format crate, every derive macro, and every hand-written Deserialize impl is written against Serde's traits. Any replacement has to be a drop-in for that surface or it will never accumulate format support. That entrenchment is why the project's stability guarantees matter: a design flaw that ships becomes permanent.

Three decisions explain almost all of Serde's awkward corners.

  • One trait set for all formats. Serde serves both self-describing formats (JSON, YAML, TOML) and non-self-describing ones (postcard, bincode, protobuf). That is enormously useful, but it means format-specific features only work on some formats and you discover the mismatch at runtime. It also produces oddities: a derived struct can quietly accept a JSON array where you expected an object.
  • A fixed data model that loses information when buffering. Internally tagged enums, untagged enums, and flatten must buffer values before they know what to do with them. The buffer cannot represent everything the format knew, so error locations degrade and ecosystem extensions resort to in-band signalling — magic keys smuggled through maps.
  • Recursion on the call stack. Every nesting level consumes stack. Formats add a recursion limit, but any code path without one — writing, dynamic values — can still take down your process on deeply nested data. It also means a single deserialization cannot be paused while you wait for more bytes.

These are not bugs. They fall out of the original architecture, and the stability guarantee means they cannot be repaired without breaking every format and every hand-written impl in existence.

Three concrete failure cases

Abstractions are best judged at the edges. Consider three corners that senior Rust engineers hit in production:

  1. Internally tagged enums with serde_json's arbitrary_precision feature. Serde's data model has no slot for arbitrary-precision numbers, so serde_json encodes them as a map with a magic key. An internally tagged enum must buffer fields until it sees the tag — and the buffer does not know about the magic key. Because Cargo unifies features, any crate in your dependency graph can turn that feature on and break your enum.
  2. flatten and string-keyed maps. A struct with {"scores": {"42": 23}} deserializes fine on its own: JSON keys are always strings, and serde_json converts them to integers only when the target type asks. Once flatten buffers the value, "42" is just a string. Worse, the resulting error points at the end of the document rather than at the offending key.
  3. Adapters that cannot compose. A function cannot be passed as a type parameter, so there is no way to apply from_hex to the inside of an Option, a Vec, or a map. You write a separate function for each wrapper — and once you have from_opt_hex, the field is no longer optional unless you also remember #[serde(default)].

Each of these is a genuine reliability hazard when the input is untrusted. If your service parses large volumes of third-party JSON — ingest pipelines, webhooks, telemetry gateways — these corners are not academic. They are the difference between a bounded failure and a process that dies under adversarial nesting. That is exactly the class of problem we design for when we build high-performance software with tight latency budgets.

How the inverted model works

In Serde, a type drives deserialization: the Deserialize impl asks the deserializer for the kind of value it expects, the format calls back into a visitor, and every nested value is handled by recursion. Stack depth grows with nesting.

Deser inverts this. The format tells the type what the next value is and pushes events into a sink. When a sink reaches the start of a nested value, it does not call into it — it hands back a new sink to a driver, which keeps all state on the heap, in an arena. On the way out, emitters return their nested values instead of recursing into them. The trait design was originally modelled on miniserde.

The consequences follow directly from where state lives:

  • No stack overflows. Arbitrary nesting depth is fine. For untrusted input you enforce limits with a layer and choose a number based on your tolerance, independent of stack size.
  • Suspendable parsing. Because the state lives in the driver, deserialization can be fed input as it arrives, and it is Send, so it can move between threads while you wait on I/O — a much better fit with tokio. JSON, CBOR, and MessagePack can be parsed as streams.
  • An extensible data model. The core model is small: atoms, maps, sequences. Everything else is an extension value (DateTime, Uuid, bytes) that carries a fallback for formats that do not understand it. No magic-key signalling.
  • Lossless buffering. When a value must be buffered — say an internally tagged enum whose tag comes last — Deser records the events plus everything the format knew about them. Extension types and error locations survive.
  • Layers as middleware. A layer sits between format and types and can track paths, enforce safety limits, rename keys, or redact values without touching format code paths.
  • Native flattening that does not buffer at all.

There is also a set of ergonomic choices: enum tags can be any type, not just strings; adapters compose, so Vec<Hex> or Option<Vec<DisplayFromStr>> work as written; validators are adapters, so Check<NonEmpty, Vec<Hex>> decodes then checks; derive attributes are real Rust expressions rather than strings; duplicate keys are rejected by default with errors that point at the problem.

What does the inversion actually cost?

Nothing is free, and the honest answer is that solving Serde's structural issues costs compile time, binary size, or runtime throughput. Deser's compile times are somewhat better than Serde's, but binary bloat is noticeably worse and runtime performance is mixed — roughly comparable on average, but significantly worse on some format structures depending on which trade-off you hit. For teams optimizing cold-start time on mobile or shaving allocation pressure in a hot path, that variance matters more than the average.

The other deliberate compromise is scope. Because the format drives the type, Deser cannot support non-self-describing formats such as protobuf — they are excluded from the design on purpose. If your world is protobuf, gRPC, or a custom binary wire format, this architecture is not for you. That is the point: fixing Serde requires making different compromises, not eliminating them.

Format coverage and the XML case

Deser implements the important self-describing formats — YAML, JSON, TOML, CBOR, JSON5 — and also XML and plist, which closes a gap. XML is a good stress test because namespaces break naive name matching: names must be matched by namespace, not by the prefix a document happens to use. Attributes being Rust expressions means atom!("title") can expand to a fully qualified {http://www.w3.org/2005/Atom}title. Untagged enums buffer entries, and because the buffer is lossless, multiple creators separated by other elements still collect correctly into one Vec.

By contrast, quick-xml — the most popular XML crate for Serde — drops prefixes and ignores namespaces entirely. If you parse Atom, RSS, or SOAP with mixed vocabularies, that is a correctness issue, not a performance one.

When should you actually switch?

Probably rarely, and not because the ideas are weak. The realistic position is:

  • Stay with Serde if your formats are self-describing and simple, your input is trusted or size-bounded, and compile times are already acceptable.
  • Consider Deser if you process large volumes of untrusted, deeply nested data, need suspendable streaming deserialization, care about error locations and lossless buffering, or need namespace-correct XML.
  • Prototype before committing. Benchmark your real payloads. The performance story is mixed, and the only number that matters is the one you measure on your own schema shapes.

The deeper lesson is architectural. Three properties — where state lives, whether parsing is recursive, and whether buffering preserves format information — determine a serializer's failure modes more than any benchmark. Those same questions recur in every performance-critical Rust system: streaming protocols, event ingestion, game state replication. We apply that reasoning across our high-performance software work in Rust and Svelte, and it shows up in how we scope custom software engagements — defining data contracts and failure envelopes before writing feature code.

For teams building AI-assisted pipelines, the same reasoning matters more, not less: model outputs are untrusted, nested, and frequently malformed, so a deserializer that cannot overflow the stack and that reports precise error paths is worth real money. That is part of why we pair AI-augmented engineering with disciplined backend architecture rather than treating generation as the whole story. You can see the same priorities across our software projects and case studies, including PNYX Comm Care and Capybara Rescue, where data handling and correctness dominated the design. Mobile clients bring their own constraint — cold start and binary size — which is why our Android app development work treats serialization cost as a first-class budget line.

Actionable takeaway: audit your deserialization boundary this week. Ask three questions — is there a depth limit on every code path, including write and dynamic-value paths? Does buffering (flatten, untagged, internally tagged) lose error locations? Can any dependency silently enable a feature that changes your parsing semantics? If the answers are no, no, and yes, you have a known failure mode. Benchmark your worst real payload, then decide whether Serde's stability or Deser's guarantees serve you better.

Get an estimate for your Rust backend project →

Based on reporting by Deser: Rethinking Rust Serialization.

Share this article

blogDetail.empower

blogDetail.digitalFuture

blogDetail.hook
blogDetail.linkToServices
avatar image
16 articles

Writes about backends that are fast, lean to run and hard to copy: when Rust pays off, when JavaScript is the smarter call, and how to keep your core logic on the server where competitors cannot read it.

category
All
Subscribe to our newsletter.
Keep up with our latest news, blogs and career opportunities
View more of our blogs