Skip to content

ContextDataFetcherDecorator wraps CompletionStage results through an unnecessary Reactor Mono chain #1548

Closed as not planned

Description

@joshgord

Problem

For every data fetcher that returns a CompletionStage, ContextDataFetcherDecorator.updateValue converts the stage through Reactor before handing it back:

value = ReactiveAdapterRegistryHelper.toMonoIfReactive(value);
if (value instanceof Mono<?> mono) {
    value = mono.contextWrite(snapshot::updateContext).toFuture();
}

This has two downsides for the common CompletableFuture case:

  1. Per-field allocation overhead. Each CompletionStage result allocates a Mono adapter, a MonoContextWrite wrapper, the toFuture subscription machinery, and a new CompletableFuture — for every field, on every execution. In a servlet-stack A/B harness (embedded Tomcat, Spring MVC, spring-graphql, micrometer context-propagation; 8 suspending fields per query, 30k requests) the Reactor round-trip accounted for ~141 MB of allocated objects per 30k executions (JFR ObjectAllocationSample, weighted), roughly 5% of total request allocation in the harness. A self-contained single-file benchmark (attached below in a comment) shows ~250-300 B per CompletableFuture-returning field, e.g. ~7-8 KB per execution at 32 fields.

  2. Propagation depends on the global Reactor Hooks state. With contextWrite, the snapshot only influences downstream processing when Reactor's automatic context propagation is enabled (Hooks.enableAutomaticContextPropagation()). Without it, the Mono round-trip allocates but propagates nothing, so fetchers resumed on other threads can observe missing ThreadLocal state depending on a global switch.

Additionally, when DataFetchingEnvironment.getLocalContext() returns the same GraphQLContext instance as the execution context, the decorator passes both to captureFrom, causing a duplicate full enumeration of the same context map per field.

Proposal

Wrap CompletionStage results directly: a CompletableFuture whose completion callback installs the ContextSnapshot scope while completing normally or exceptionally. Publisher results keep the Reactor path; subscription results are unchanged. This removes the per-field Mono chain and makes ThreadLocal restoration explicit and independent of the Hooks state. Also skip the duplicate captureFrom source when the local context is the same instance.

I have a PR with this change, tests, and measurements ready to link.

Activity

  1. joshgord commented on Oct 25, 2026

    @joshgord
    Author

    Superseded by #1547.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions