Lazy bean-definition references: carry per-definition descriptors in the META-INF/micronaut entries
Feature description
Every $Definition on the class path is loaded and statically initialised at startup, but an HTTP app uses well under half of them before it serves its first request. This proposes lazy bean-definition references in two phases:
- Phase 1: processor only, additive, ready to implement. Write a small descriptor into the
META-INF/micronaut/io.micronaut.inject.BeanDefinitionReference/<name>entry that each definition already gets. That entry is empty today. - Phase 2: an
@Experimentalruntime opt-in. The context answers lookups from the descriptors and loads a definition only when it needs it.
How we found it. We were profiling micronaut-runner with its benchmark-large sample:
- The sample has 379
BeanDefinitionReferenceentries, 329 of them from dependency JARs. 378 definitions load; the 379th,JavaxProviderBeanDefinition, cannot link withoutjavax.inject. - 141 of the 378 create a bean before the first HTTP 200.
- 194 are unused before readiness. A missing class disables only 9 of those.
- The other 43 were counted as possibly used, although they create no bean: registrars, event listeners,
@Contextand method-processing definitions, and definitions whose bean class is initialised anyway.
So the cost is in enabled definitions that are not needed yet, and build-time pruning cannot remove it.
Why everything loads (5.3.x)
- The reference and the definition are one class. Since 4.4 the generated class is both. Creating a reference runs its
<clinit>, which builds the annotation metadata and resolves the Class literals (getStaticInitializer). - All references are created up front.
DefaultBeanDefinitionServicecreates every one of them on the common pool and joins (serially when common-pool parallelism ≤ 1). Its type index is keyed byClass. - Qualifier-only lookups read every reference's metadata.
getBeanDefinitions(Qualifier)runsdoesQualify(hasStereotype) on all of them.- Self-indexed stereotypes (#12993) still make that pass once per type, in
isIndexExhaustive(#13111). - benchmark-large makes 8 such lookups before readiness:
@Controller,@Endpoint×4,@ServerFilter,@ServerWebSocketand@Filter. - A reference that loads on any metadata call would therefore load everything at the first
@Controllerlookup.
Measurements
Setup. Shadow JAR, micronaut-core 5.1.15, JDK 25.0.4.1, macOS arm64 with 12 CPUs. The metric is spawn to the first HTTP 200, over 3 warm-up and then 20 paired, interleaved rounds per arm. Figures are median paired differences in ms with bootstrap 95% CIs. "2 CPUs" means -XX:ActiveProcessorCount=2; the AOT cache (-XX:AOTCache) was trained per JAR. Controls: about 535 ms, 730 ms on 2 CPUs, and 240 ms with the AOT cache.
| Arm | 12 CPUs | 2 CPUs | AOT cache |
|---|---|---|---|
| Ceiling: 194 unused entries deleted | −34.8 [−43.5, −28.4]; rerun −28.3 | −126.9 [−137.6, −112.5] | −19.9 [−33.3, −10.7]; rerun −27.2 |
| Simulation: 162 deleted, keeping the 32 that pre-readiness lookups return | −19.1 [−28.1, −9.9]; rerun −20.8 | −85.7 [−97.8, −77.8] | −20.4 [−23.7, −15.4] |
| Same, with the needed set created serially on main | +88.5 [+81.3, +94.6] | −95.8 [−98.4, −85.5] | −20.2 (parallelism 1) |
- Memory. With the cache, the ceiling cuts max RSS by 8.5 MiB (7 paired rounds; the control is 135 MiB), and the cache file shrinks from 52.0 to 46.5 MB. A Runner JAR gains the same: −29.4 / −110.2 / −15.7 ms and −9.6 MiB.
- The ceiling is only a bound. Deleting the entries breaks
/health,/infoand 404s after readiness. - The simulation is optimistic. It did not pay for the stereotype scans, or for definitions that load and are then disabled by a post-load condition. Its matching was also ambiguous: 32 exact matches, up to 47 by simple name.
ActiveProcessorCountis not a cgroup limit. - Descriptor reads. Reading 379 entries with a 212-byte test payload each took 4.6–7.1 ms cold (n=7).
- Not measured yet: 5.3.x, the simulation's memory, and real Linux cgroup limits of 1, 2 and 4 vCPU.
Proposed change
Phase 1: the descriptors.
- Format. A version and length header; a bad header falls back to the eager path.
- Content. The flags, exposed-type names and
@Indexednames; the pre-load condition records, whichcreateConditionsalready keeps separate; the full stereotype set thathasStereotypeanswers, inherited ones included; repeatable containers and qualifier values. - Plumbing.
- Add a content field to
OutputObjectDef, and a content overload toClassWriterOutputVisitorwhose default drops the content. - Use the overload at the write sites in inject-java (
BeanDefinitionInjectProcessor,TypeElementVisitorProcessor), inject-groovy (InjectTransform,TypeElementVisitorEnd), inject-kotlin and inject-python. - Implement it in the Java, Kotlin and Groovy visitors, and in
DirectoryClassWriterOutputVisitor, which also needsTRUNCATE_EXISTING.
- Add a content field to
- Compatibility. The processors stay isolating. Runtimes read only the entry names, and Shadow keeps the entry content. Shipping this first starts the recompilation clock for the modules, which supply most definitions.
Phase 2: descriptor-backed references.
- Which references are lazy. A non-empty entry with a known version becomes a lazy reference. An empty entry is loaded eagerly, so mixed class paths work.
- Conditions. Pre-load conditions go through the package-private
DefaultConditionContext. - Index. The index is keyed by name, and
isCandidateBeanruns after load. - Qualifiers.
- The stereotype, annotation and name qualifiers and
isIndexExhaustiveanswer from the descriptor. - Custom qualifiers,
beansPredicateandBeanResolutionCustomizerload the definition.
- The stereotype, annotation and name qualifiers and
- Configurations. The interface default
BeanConfiguration.isWithin(ref)callsgetBeanType(). Switch it togetBeanDefinitionName(), asAbstractBeanConfigurationalready does. - Failures. A link error at load means "not present". The first failure is kept and rethrown on later loads.
- Native. Native images keep the eager path.
- Checks. A kill switch, and an equivalence mode that compares the descriptor's answers with the loaded ones. The core suite runs in both modes.
- Defaults, decided after a prototype that pays the stereotype scans is measured under cgroup limits:
- It is opt-in through a builder flag or a system property. Launchers that run with an AOT cache, such as Micronaut's Docker images once they train one, can set it, because with the cache serial and parallel loading measured the same.
- The candidate default is "on" at common-pool parallelism ≤ 1, where the eager scan is already serial.
- Otherwise the eager parallel scan stays, and there is no background warm-up until one has been measured.
Prior art and risks
- Prior art. micronaut-aot 2.x's
serviceloading.jitpruned at build time; micronaut-projects/micronaut-aot#423 removed it. Micronaut 3's references carried the full annotation metadata; the descriptor keeps only what lookups need. - Link errors. A definition that cannot link is dropped at its first lookup, not at the scan.
- Casts.
instanceof AbstractInitializableBeanDefinitionAndReferenceappears inDefaultBeanDefinitionService(L709, L721) andRequiresCondition(L81). - Silent defeat. Public SPIs that touch every reference undo the laziness without any warning.
- Effort. About 1.5–2 weeks for phase 1 with Java, Kotlin and Groovy tests, and 3–4 weeks for phase 2 plus verification.
Related
- micronaut-runner cannot implement this itself, because
DefaultConditionContextis package-private andBeanDefinitionServiceis sealed. It adds safeguards instead:- https://github.com/alvarosanchez/micronaut-runner/issues/154 skips
BeanDefinitionReferencein its static table when any entry is non-empty. - https://github.com/alvarosanchez/micronaut-runner/issues/155 packages no prefetch at all when any merged
BeanDefinitionReferenceentry is non-empty. - https://github.com/alvarosanchez/micronaut-runner/issues/137 adds Linux CPU-limit benchmark modes.
- https://github.com/alvarosanchez/micronaut-runner/issues/154 skips
- #13389 must carry entry content, or leave
BeanDefinitionReferenceto the scan.
Source: micronaut-projects/micronaut-core