Skip to content

Conversation

@ljluestc
Copy link

What type of PR is this?

/kind feature

What this PR does / why we need it:
Performance improvement for create deployment.

Currently, updateResourceStatus in pkg/controllers/status/common.go performs a direct API Get and Update on the resource status for every Work status update. This bypasses the controller-runtime cache, leading to higher latency and increased load on the API server, especially when creating a large number of deployments concurrently.

This PR optimizes updateResourceStatus to attempt fetching the resource from the informer cache first.

  1. It tries to get the object from the InformerManager.
  2. If found, it calculates the new status and attempts to update the resource status via the API server.
  3. If the update succeeds, it returns.
  4. If the update fails with a conflict (optimistic locking failure) or if the object wasn't found in the cache, it falls back to the original behavior: fetching the latest object directly from the API server and retrying the update.

This "optimistic cache fetch" strategy significantly reduces the number of read operations against the API server during normal operation, improving performance for high-concurrency scenarios.

Which issue(s) this PR fixes:

Fixes #4225

Special notes for your reviewer:

Verified with go test ./pkg/controllers/status/.... The retry logic ensures data consistency even if the cache is stale.

Does this PR introduce a user-facing change?:

NONE

@karmada-bot karmada-bot added do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. kind/feature Categorizes issue or PR as related to a new feature. labels Jan 25, 2026
@karmada-bot
Copy link
Contributor

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:
Once this PR has been reviewed and has the lgtm label, please assign zhzhuang-zju for approval. For more information see the Code Review Process.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@karmada-bot karmada-bot requested a review from Poor12 January 25, 2026 05:59
@gemini-code-assist
Copy link

Summary of Changes

Hello @ljluestc, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a significant performance optimization for resource status updates, particularly impacting deployment creation. By leveraging an informer cache for initial resource fetches, it aims to reduce the load on the API server and decrease latency. A robust fallback mechanism ensures data consistency by retrying updates directly from the API server in cases of cache misses or conflicts.

Highlights

  • Performance Optimization: Implemented an "optimistic cache fetch" strategy in the updateResourceStatus function to prioritize fetching resources from the informer cache, significantly reducing direct API server calls.
  • Robust Fallback Mechanism: Introduced a fallback to directly query the API server if the initial cache fetch fails or if an update attempt results in a conflict, ensuring data consistency.
  • Reduced API Server Load: The new strategy aims to decrease the load on the API server and lower latency, especially during high-concurrency scenarios like creating many deployments.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@karmada-bot karmada-bot added the size/M Denotes a PR that changes 30-99 lines, ignoring generated files. label Jan 25, 2026
Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a valuable performance optimization by leveraging an informer cache to fetch resources before updating their status, which should effectively reduce the load on the API server. The overall implementation is sound, with a fallback mechanism to ensure correctness. However, I've identified a few areas for improvement concerning code maintainability and minor correctness issues. My review includes suggestions to refactor for better readability and to fix an issue with event recording. Addressing these points will enhance the robustness and long-term maintainability of the code.

Comment on lines +191 to +217
newObj, err := interpreter.AggregateStatus(resource, bindingStatus.AggregatedStatus)
if err != nil {
klog.Errorf("Failed to aggregate status for resource template(%s/%s/%s), Error: %v", gvr, resource.GetNamespace(), resource.GetName(), err)
return err
}

oldStatus, _, _ := unstructured.NestedFieldNoCopy(resource.Object, "status")
newStatus, _, _ := unstructured.NestedFieldNoCopy(newObj.Object, "status")
if reflect.DeepEqual(oldStatus, newStatus) {
klog.V(3).Infof("Ignore update resource(%s/%s/%s) status as up to date.", gvr, resource.GetNamespace(), resource.GetName())
return nil
}

_, err = dynamicClient.Resource(gvr).Namespace(resource.GetNamespace()).UpdateStatus(ctx, newObj, metav1.UpdateOptions{})
if err == nil {
eventRecorder.Event(resource, corev1.EventTypeNormal, events.EventReasonAggregateStatusSucceed, "Update Resource with AggregatedStatus successfully.")
klog.V(3).Infof("Update resource(%s/%s/%s) status successfully.", gvr, resource.GetNamespace(), resource.GetName())
return nil
}

if !apierrors.IsConflict(err) {
klog.Errorf("Failed to update resource(%s/%s/%s), Error: %v", gvr, resource.GetNamespace(), resource.GetName(), err)
return err
}
// If conflict happens, we will retry to fetch the latest resource from apiserver and update again.
klog.V(3).Infof("Conflict updating resource(%s/%s/%s) from cache, falling back to API server.", gvr, resource.GetNamespace(), resource.GetName())
}

Choose a reason for hiding this comment

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

medium

There is significant code duplication between the new optimistic update path (from cache, lines 191-209) and the fallback path within retry.RetryOnConflict (lines 236-256). The logic for aggregating status, comparing statuses, and updating the resource is repeated.

To improve maintainability and reduce redundancy, consider refactoring the common logic into a helper function. This would make the code cleaner and less error-prone for future modifications.

Comment on lines +204 to +209
_, err = dynamicClient.Resource(gvr).Namespace(resource.GetNamespace()).UpdateStatus(ctx, newObj, metav1.UpdateOptions{})
if err == nil {
eventRecorder.Event(resource, corev1.EventTypeNormal, events.EventReasonAggregateStatusSucceed, "Update Resource with AggregatedStatus successfully.")
klog.V(3).Infof("Update resource(%s/%s/%s) status successfully.", gvr, resource.GetNamespace(), resource.GetName())
return nil
}

Choose a reason for hiding this comment

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

medium

The event is being recorded on the resource object, which is the state of the object before the status update. The UpdateStatus function returns the updated object, and it's a best practice to use this returned object for event recording to ensure the event is associated with the most recent version of the object.

This issue also exists in the retry.RetryOnConflict block on line 254. Please apply a similar fix there.

Suggested change
_, err = dynamicClient.Resource(gvr).Namespace(resource.GetNamespace()).UpdateStatus(ctx, newObj, metav1.UpdateOptions{})
if err == nil {
eventRecorder.Event(resource, corev1.EventTypeNormal, events.EventReasonAggregateStatusSucceed, "Update Resource with AggregatedStatus successfully.")
klog.V(3).Infof("Update resource(%s/%s/%s) status successfully.", gvr, resource.GetNamespace(), resource.GetName())
return nil
}
updatedObj, err := dynamicClient.Resource(gvr).Namespace(resource.GetNamespace()).UpdateStatus(ctx, newObj, metav1.UpdateOptions{})
if err == nil {
eventRecorder.Event(updatedObj, corev1.EventTypeNormal, events.EventReasonAggregateStatusSucceed, "Update Resource with AggregatedStatus successfully.")
klog.V(3).Infof("Update resource(%s/%s/%s) status successfully.", gvr, resource.GetNamespace(), resource.GetName())
return nil
}

@codecov-commenter
Copy link

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

❌ Patch coverage is 12.90323% with 27 lines in your changes missing coverage. Please review.
✅ Project coverage is 46.52%. Comparing base (437e37e) to head (13ec904).

Files with missing lines Patch % Lines
pkg/controllers/status/common.go 6.89% 24 Missing and 3 partials ⚠️
❗ Your organization needs to install the Codecov GitHub app to enable full functionality.
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #7128      +/-   ##
==========================================
- Coverage   46.54%   46.52%   -0.02%     
==========================================
  Files         700      700              
  Lines       48134    48163      +29     
==========================================
+ Hits        22403    22410       +7     
- Misses      24045    24065      +20     
- Partials     1686     1688       +2     
Flag Coverage Δ
unittests 46.52% <12.90%> (-0.02%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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

Labels

do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. kind/feature Categorizes issue or PR as related to a new feature. size/M Denotes a PR that changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Performance improvement for create deployment

3 participants