Video in progress

Why is Java serialization hardly used today for exchanging data between services?

Java serialization is readable only by Java, very sensitive to class changes, slow and bulky. Most importantly, deserializing from an untrusted source can lead to remote code execution. JSON, Protobuf and Avro are used instead.

📖 Answer

Let's go through the problems one at a time.

Platform lock-in. A service in Go or Python can't read the ObjectOutputStream format. In microservices that is an immediate blocker.

Versioning. The class name, package and fields all go into the bytes. Refactor the package and old data becomes unreadable. Protobuf works with field numbers, so you can rename things freely.

Security. During deserialization the classes' readObject methods run. If there are "gadget" chains on the classpath (the old Commons Collections example is famous), an attacker can send crafted bytes and execute commands on the server. This is not theory: many real CVEs come from this.

The choice usually looks like this:

  • REST API, configuration, anything a human has to read: JSON (Jackson);
  • high-load service-to-service traffic, gRPC: Protobuf;
  • Kafka with a schema registry: Avro or Protobuf.

Java serialization still works quietly in some places: old session replication, RMI, the default setting of some cache libraries. Switching the serializer to JSON in Spring Session or the Redis cache is a typical improvement.