Skip to main content

dawdler-kryo-optimization

Module Introduction​

A Kryo registration optimization module for entities transferred over RPC. It automatically registers entity classes implementing java.io.Serializable in the scanned packages with Kryo, replacing the cost of carrying the full class name in every message and calling Class.forName on the deserialization side.

1. Adding the dependency in pom​

<groupId>club.dawdler</groupId>
<artifactId>dawdler-kryo-optimization</artifactId>

It must be added on both the client (WEB-INF/lib of the web application) and the server (the lib directory of the deploy). Just adding the dependency is enough; no configuration is required.

2. How it works​

The module provides KryoRegistrationInjector (an SPI implementation of CustomComponentInjector) and integrates with dawdler's component scan-and-inject mechanism:

  • Server: at deployment time it runs CustomComponentOperator.scanAndInject over the package-paths of services-conf.xml; whenever an entity class implementing Serializable is scanned, the inject method is called
  • Client: at web application startup WebListener performs the same scan-and-inject over the package-paths of web-conf.xml

The match rule is any class implementing java.io.Serializable (including implementations inherited through non-Java parent classes/interfaces), e.g.:

public class User implements Serializable

Registrations are submitted through KryoSerializer.applyDynamicRegistrations and marked with a version number, taking effect uniformly for existing and subsequently created Kryo instances (platform-thread ThreadLocal instances, virtual-thread striped pool instances). Each instance is rebuilt on demand the next time it is used, without blocking request threads.

inject only reads Class type information and never instantiates entities (the injector declares requireInstantiation()=false), so entities without a no-arg constructor (records, immutably constructed objects with an all-args constructor) do not cause deployment failures.

When a deploy is unloaded / retired during hot replacement, the framework releases the static caches keyed by class loader for that deploy through the single manifest DeployClassLoader.releaseCaches. This module's uncommitted registration buffer is released along the same chain via KryoRegistrationBufferReleaser (an SPI implementation of ClassLoaderCacheReleaser), preventing stale Class objects from pinning the class loader after unload and leftover registrations from interfering with the id-collision detection of later deployments. KryoRegistrationCleaner (an SPI implementation of ComponentLifeCycle) performs cleanup by TCCL as an idempotent fallback.

3. How registration ids are derived​

Registration ids are derived from the class name via a 32-bit FNV-1a hash:

id = 1000000 + (fnv1a_32(binary class name) & 0x0FFFFFFF) % (268435455 - 1000000 + 1) // falls in [1000000, 268435455]

Dynamic registrations occupy the reserved range [1000000, 268435455] (starting at KryoDynamicRegistration.DYNAMIC_ID_BASE; validated at construction, and values below the lower bound are rejected outright), which is structurally disjoint from KryoClassRegistrar's static registration range [10, 999999]: static registrations must not exceed 1000000, and an accidental overrun that collides with a dynamic id is explicitly rejected at application time by the collision check, which names both conflicting parties.

Sequential ids based on class-name ordering are deliberately not used: if the class sets scanned by the client and the server differ at all (e.g. the server also scans an implementation package), every entity id is shifted and the reader resolves an id to the wrong class, causing silent mis-decoding. A class-name hash id depends only on the class name itself and is independent of the scanned set and discovery order, so both sides always derive the same id for a class of the same name. A set difference only results in "a class registered on one side but not the other" (failing explicitly with Encountered unregistered class ID on read) rather than mutual misalignment.

A hash id takes 3-4 bytes as a varint on the wire (4 bytes in the vast majority of cases), which is still more than a 6x size saving compared with the full class name (25-40 characters on average), and avoids the CPU cost of reading the class name and calling Class.forName. Ultra-high-frequency classes that want a 1-byte id (envelope classes such as RequestBean/ResponseBean) are already statically registered by the framework modules through KryoClassRegistrar and are unaffected by this module.

The probability of two different class names colliding on the same id is roughly n²/535 million (n is the number of entities; about 0.002% for 100 entities). On collision deployment fails explicitly and names the two conflicting classes. Kryo silently overwrites ids on collision; this module detects it proactively at application time and blocks it to avoid online mis-decoding.

4. Usage constraints​

  1. Entity classes transferred over RPC must fall within the scanned package paths on both sides: e.g. if the server scans club.dawdler.user (including the entity package), the client's web-conf.xml must also scan the path containing that entity package; otherwise one side writes the registration id and the other cannot recognize it, and deserialization fails with Encountered unregistered class ID. It is recommended that both sides scan the same entity packages.
  2. New entities must be released on both sides together: ids of existing classes are unaffected (the hash depends only on the class name), but new entities cannot be recognized by a peer that has not been upgraded. This matches the "client and server must be upgraded together" requirement of KryoClassRegistrar static registration; release during off-peak hours is recommended.
  3. When the Kryo allowlist is enabled (it is enabled by default and can be disabled with -Ddawdler.serializer.kryo.secure.enabled=false): classes registered by this module are no longer subject to SecureClassResolver's class-name validation when read by registration id, i.e. entity classes in the scanned packages are effectively allowlisted. Make sure only trusted code is placed inside the scan package paths.
  4. Every Serializable class in the scan packages is registered (including those not actually transferred over RPC), and each Kryo instance builds about 2KB of serializers per registered class. Put classes that do not need registration outside the scan packages.

5. Observability​

Both registration and cleanup are logged:

  • New registration: Kryo dynamic registration: club.dawdler.user.entity.User -> id 123456789
  • Deploy unload cleanup: Removed kryo dynamic registrations loaded by ...

To troubleshoot id misalignment, simply check whether the ids for the same class name match in the peer's logs.