Skip to content

fix: node.addDependency between stacks is quadratic in number of resources - #38522

Closed
dgandhi62 wants to merge 2 commits into
mainfrom
fix-dependency-quadratic
Closed

dgandhi62 wants to merge 2 commits into
mainfrom
fix-dependency-quadratic

Conversation

@dgandhi62

@dgandhi62 dgandhi62 commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

This pr is a reimplementation of #38314

Previously, node.addDependency between stacks expanded all resources on both sides into a Cartesian product, calling addResourceDependency for each pair, making it O(n*m) per dependency. Every pair ultimately resolved to the same single stack-to-stack dependency, making the work redundant.

This pr retains the lazy nature of dependency resolution. Before we go down the cartesian expansion, we add a check. If source and target are under different top-level stacks, we apply the dependency once between stacks using a representative resource from each side, skipping the cartesian product entirely. This makes the overall time complexity of cross-stack dependency resolution from quadratic to constant.


By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license

@github-actions github-actions Bot added beginning-contributor [Pilot] contributed between 0-2 PRs to the CDK effort/medium Medium work item – several days of effort p0 labels Aug 10, 2026
@aws-cdk-automation
aws-cdk-automation requested a review from a team August 10, 2026 00:54
@mergify mergify Bot added the contribution/core This is a PR that came from AWS. label Aug 10, 2026

@aws-cdk-automation aws-cdk-automation left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The pull request linter fails with the following errors:

❌ Fixes must contain a change to an integration test file and the resulting snapshot.

If you believe this pull request should receive an exemption, please comment and provide a justification. A comment requesting an exemption should contain the text Exemption Request. Additionally, if clarification is needed, add Clarification Request to a comment.

@dgandhi62 dgandhi62 removed the beginning-contributor [Pilot] contributed between 0-2 PRs to the CDK label Aug 10, 2026
@dgandhi62
dgandhi62 force-pushed the fix-dependency-quadratic branch from e39baf8 to e5d4cae Compare August 10, 2026 15:07
@dgandhi62
dgandhi62 marked this pull request as ready for review August 10, 2026 15:07
@dgandhi62
dgandhi62 requested a review from a team as a code owner August 10, 2026 15:07
@dgandhi62
dgandhi62 force-pushed the fix-dependency-quadratic branch from a0b7ccd to 017b66e Compare August 10, 2026 19:45
@dgandhi62 dgandhi62 changed the title fix: cross-stack node.addDependency leads to quadratic expansion fix: node.addDependency between stacks is quadratic in number of resources Aug 10, 2026
… expansion

Previously, node.addDependency between stacks expanded all resources on
both sides into a Cartesian product, calling addResourceDependency for
each pair — O(n*m) per dependency. Every pair ultimately resolved to the
same single stack-to-stack dependency, making the work redundant.

This change short-circuits the cross-top-level-stack case: if source and
target are under different top-level stacks, we apply the dependency once
using a representative resource from each side. The same-stack path
(including nested stacks) remains unchanged, preserving the correct
nested-stack boundary behavior via resourceInCommonStackFor in deps.ts.

This is a safer re-landing of the performance improvement from #38314
(reverted in #38417 due to #38406). The original PR moved dependency
resolution to eager dispatch and accidentally lost the nested stack
boundary check. This approach keeps the existing synth-time resolution
and only optimizes the provably-redundant cross-stack expansion.

Closes #38406
@github-actions

Copy link
Copy Markdown
Contributor

⚠️ This pull request description does not follow the correct template structure.

PRs without a linked issue will receive lower priority for review and merging. Please update the description to follow the PR template and include a line like Closes #123 in the Issue section. If no existing issue matches your change, create one first.

@rix0rrr rix0rrr left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You need to clarify why #38314 got reverted, and what the differences are between this implementation and the other one.

If I would have to guess it's the removal of "obtainResourceDependencies", that I posited shouldn't have been exposed in the first place, but people were calling it and so they complained and we had to revert because of that?

The other one also had code cleanup and call chain streamlining in there that I'm seeing fully missing from this one. I'd like that back please.

@github-actions

Copy link
Copy Markdown
Contributor

Comments on closed issues and PRs are hard for our team to see.
If you need help, please open a new issue that references this one.

@github-actions github-actions Bot locked as resolved and limited conversation to collaborators Aug 19, 2026
mekza pushed a commit to mekza/aws-cdk that referenced this pull request Aug 19, 2026
…8597)

> This is a re-roll of aws#38314 which had to be reverted in aws#38417 because of a regression caused by recursing resource dependencies INTO nested stacks. This reintroduces the original change but fixes that bug. This PR also closes aws#38522 -- thanks Dhyan but I like the additional cleanup of dependency handling code in the original PR that your fix doesn't have.

`source.node.addDependency(target)` is used to confer dependencies between all resources under `source` to all resources under `target`.

The way this was done is to first expand the two sets into a Cartesian product, and then apply the dependency individually for each pair. The applied dependency can lead to a CloudFormation `DependsOn` relationship between the target resource (or the Nested Stack containing it), or a Stack-to-Stack dependency if the resources are in different stacks.

However, if this method of adding dependencies is applied to Stacks, we would first make all pairs of resources from `(sourceStack, targetStack)`, apply the dependency, and find out that each of those dependencies would ultimately just lead to a single stack-to-stack dependency. This method of applying dependencies is quadratic in the size of the stack, whereas it should be linear in the number of stack-to-stack dependencies applied.

In this PR, we rework the dependencies mechanism to remove the quadraticness if `node.addDependency` is used to add dependencies between stacks: we resolve the constructs that should be involved in the dependency operation first, and only expand to the cartesian product of individual resources if we end up inside the same Stack (in which case the construct groups are on the order of single digits). This makes the cross-stack case a *lot* faster.

(Note: I'm saying "superlinear" in the body because although it seems like the work should be quadratic, from testing it seems to be a lot worse than quadratic -- perhaps even exponential. In any case anything worse than linear is baaaaaddd so that's what I'm writing it down as 😉 )

Because there are multiple ways of adding dependencies, renamed some of them to make the distinction more clear:

- `construct.node.addDependency(construct)`: add a construct-level description of a dependency that will get reified at synthesis time.
  - That functionality gets a `removeDependency` here: aws/constructs#2872
- `stack.addStackDependency(stack)`, `resource.addResourceDependency(resource)`: directly applies a dependencies between stacks or resources.
  - These used to be called `stack.addDependency` and `resource.addDependency`, which is confusing because now  `stack.addDependency` and `stack.node.addDependency` look very similar but do very different things. So I renamed them.
  - Unfortunately `resource.addResourceDependency` also performs for cross-stack dependencies, which I'd much prefer it hadn't so it could stay simple and predictable, but we can't take this away anymore.
- Because we need to account for resource dependencies leading to stack dependencies (grr), we need to make a distinction between public API and mutation API, which are now under `_addStackDependency`, `_addResourceDependency` etc.

The flow is now this:

```
┌───────────────────┐       ┌───────────────────┐      ┌───────────────────┐
│                   │       │stack.addStackDepen│      │resoure.addResource│
│node.addDependency │       │       dency       │      │    Dependency     │
│                   │       │                   │      │                   │
└───────────────────┘       └───────────────────┘      └───────────────────┘
          │                           │                          │
   (at synth time)              (immediately)              (immediately)
          └───────────────────────────┼──────────────────────────┘
                                      │
                                      ▼
                    ┌───────────────────────────────────┐
                    │                                   │
                    │    dispatchDependencyOperation    │
                    │                                   │
                    └───────────────────────────────────┘
                                      │
                                      │
                        ┌─────────────┴────────────┐
                        │                          │
                        │                          │
                        ▼                          ▼
              ┌───────────────────┐      ┌───────────────────┐
              │stack._addStackDepe│      │resoure._addResourc│
              │      ndency       │      │    eDependency    │
              │                   │      │                   │
              └───────────────────┘      └───────────────────┘
```

Everything dispatches through the same code so that the behavior is the same regardless of the entry API that is chosen.

----

*By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
Swathi-Karanth pushed a commit to Swathi-Karanth/aws-cdk that referenced this pull request Aug 20, 2026
…8597)

> This is a re-roll of aws#38314 which had to be reverted in aws#38417 because of a regression caused by recursing resource dependencies INTO nested stacks. This reintroduces the original change but fixes that bug. This PR also closes aws#38522 -- thanks Dhyan but I like the additional cleanup of dependency handling code in the original PR that your fix doesn't have.

`source.node.addDependency(target)` is used to confer dependencies between all resources under `source` to all resources under `target`.

The way this was done is to first expand the two sets into a Cartesian product, and then apply the dependency individually for each pair. The applied dependency can lead to a CloudFormation `DependsOn` relationship between the target resource (or the Nested Stack containing it), or a Stack-to-Stack dependency if the resources are in different stacks.

However, if this method of adding dependencies is applied to Stacks, we would first make all pairs of resources from `(sourceStack, targetStack)`, apply the dependency, and find out that each of those dependencies would ultimately just lead to a single stack-to-stack dependency. This method of applying dependencies is quadratic in the size of the stack, whereas it should be linear in the number of stack-to-stack dependencies applied.

In this PR, we rework the dependencies mechanism to remove the quadraticness if `node.addDependency` is used to add dependencies between stacks: we resolve the constructs that should be involved in the dependency operation first, and only expand to the cartesian product of individual resources if we end up inside the same Stack (in which case the construct groups are on the order of single digits). This makes the cross-stack case a *lot* faster.

(Note: I'm saying "superlinear" in the body because although it seems like the work should be quadratic, from testing it seems to be a lot worse than quadratic -- perhaps even exponential. In any case anything worse than linear is baaaaaddd so that's what I'm writing it down as 😉 )

Because there are multiple ways of adding dependencies, renamed some of them to make the distinction more clear:

- `construct.node.addDependency(construct)`: add a construct-level description of a dependency that will get reified at synthesis time.
  - That functionality gets a `removeDependency` here: aws/constructs#2872
- `stack.addStackDependency(stack)`, `resource.addResourceDependency(resource)`: directly applies a dependencies between stacks or resources.
  - These used to be called `stack.addDependency` and `resource.addDependency`, which is confusing because now  `stack.addDependency` and `stack.node.addDependency` look very similar but do very different things. So I renamed them.
  - Unfortunately `resource.addResourceDependency` also performs for cross-stack dependencies, which I'd much prefer it hadn't so it could stay simple and predictable, but we can't take this away anymore.
- Because we need to account for resource dependencies leading to stack dependencies (grr), we need to make a distinction between public API and mutation API, which are now under `_addStackDependency`, `_addResourceDependency` etc.

The flow is now this:

```
┌───────────────────┐       ┌───────────────────┐      ┌───────────────────┐
│                   │       │stack.addStackDepen│      │resoure.addResource│
│node.addDependency │       │       dency       │      │    Dependency     │
│                   │       │                   │      │                   │
└───────────────────┘       └───────────────────┘      └───────────────────┘
          │                           │                          │
   (at synth time)              (immediately)              (immediately)
          └───────────────────────────┼──────────────────────────┘
                                      │
                                      ▼
                    ┌───────────────────────────────────┐
                    │                                   │
                    │    dispatchDependencyOperation    │
                    │                                   │
                    └───────────────────────────────────┘
                                      │
                                      │
                        ┌─────────────┴────────────┐
                        │                          │
                        │                          │
                        ▼                          ▼
              ┌───────────────────┐      ┌───────────────────┐
              │stack._addStackDepe│      │resoure._addResourc│
              │      ndency       │      │    eDependency    │
              │                   │      │                   │
              └───────────────────┘      └───────────────────┘
```

Everything dispatches through the same code so that the behavior is the same regardless of the entry API that is chosen.

----

*By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*

This branch was previously deployed

1 inactive deployment
automation — e9c1f4e3 Deployed Aug 12, 2026 by dgandhi62 via validate-pr #360848
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

contribution/core This is a PR that came from AWS. effort/medium Medium work item – several days of effort p0

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants