Skip to content

fix: Node.path takes a lot of time on deep construct trees#2873

Merged
cdklabs-automation merged 2 commits into
aws:10.xfrom
ulrokx:memoize-node-path
Jul 20, 2026
Merged

fix: Node.path takes a lot of time on deep construct trees#2873
cdklabs-automation merged 2 commits into
aws:10.xfrom
ulrokx:memoize-node-path

Conversation

@ulrokx

@ulrokx ulrokx commented Jul 15, 2026

Copy link
Copy Markdown
Contributor

Every construct has a Node, and Node.path and Node.scopes are computed on every access by
walking the full scope chain up to the root and joining the component ids.

These values never change once the construct is created, so we can just eagerly
calculate them instead. The lazy work was predicated on the assumption
that they might only rarely be read, but in practice CDK synthesis reads
both properties contstantly, and recalculating them incurs a heft cost
on deep construct trees.

The
most impactful case is the aspect invocation loop in aws-cdk-lib
(invokeAspectsV2), which recurses the whole tree until it stabilizes and
uses node.path as a per-node dedup-map key on every visit. On a large tree
(~5,500 stacks) this was measured at hundreds of millions of path reads in a
single synth, dominating both CPU and GC.

This had a pretty nice performance benefit on a CDK package of ours, the synthesis times went from around 15 minutes to 8 minutes.

Testing

yarn test (full jest suite) passes.

Every construct has a `Node`, and `Node.path` is computed on every access
by walking the full scope chain up to the root and joining the ids. For
most constructs this chain never changes once the construct is created:
`scope` and `id` are readonly and there is no reparenting API.

Callers that read `path` repeatedly - notably the aspect invocation loop
in aws-cdk-lib, which uses it as a per-node dedup key - therefore recompute
the same string over and over. On a large tree (~5.5k stacks) this was
measured at hundreds of millions of `path` reads in a single synth.

Cache the computed value on first access. This is safe because the path is
immutable once the scope chain is established, and it produces identical
output while removing the repeated scope-chain walk.
@ulrokx
ulrokx marked this pull request as ready for review July 15, 2026 18:47
@rix0rrr rix0rrr changed the title fix: cache Node.path to save time on large trees fix: Node.path takes a lot of time on deep construct trees Jul 20, 2026
@cdklabs-automation
cdklabs-automation added this pull request to the merge queue Jul 20, 2026
Merged via the queue into aws:10.x with commit 857a94f Jul 20, 2026
12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants