Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

v3: Improve performance of Adaptor Middleware #3078

Merged
merged 4 commits into from
Jul 18, 2024
Merged

Conversation

gaby
Copy link
Member

@gaby gaby commented Jul 17, 2024

Description

Improve performance of the Adaptor middleware by using sync.Pool to re-use fasthttp.RequestCtx objects.

Overall Percent Change

  • Execution Time: Reduced by ~47.57%
  • Memory Usage: Reduced by ~89.97%
  • Allocations: Reduced by ~68.75%

Summary of Results

Run 1 (Current main branch):

  • 100KB: 1056 ns/op, 2644 B/op, 16 allocs/op
  • 500KB: 1061 ns/op, 2644 B/op, 16 allocs/op
  • 1MB: 1080 ns/op, 2646 B/op, 16 allocs/op
  • 5MB: 1093 ns/op, 2654 B/op, 16 allocs/op
  • 10MB: 1044 ns/op, 2665 B/op, 16 allocs/op
  • 25MB: 1069 ns/op, 2706 B/op, 16 allocs/op
  • 50MB: 1137 ns/op, 2734 B/op, 16 allocs/op

Run 2 (This pull request)

  • 100KB: 588.6 ns/op, 254 B/op, 5 allocs/op
  • 500KB: 562.9 ns/op, 248 B/op, 5 allocs/op
  • 1MB: 629.7 ns/op, 267 B/op, 5 allocs/op
  • 5MB: 540.3 ns/op, 254 B/op, 5 allocs/op
  • 10MB: 533.1 ns/op, 258 B/op, 5 allocs/op
  • 25MB: 540.7 ns/op, 289 B/op, 5 allocs/op
  • 50MB: 554.6 ns/op, 298 B/op, 5 allocs/op

Type of change

  • Performance improvement (non-breaking change which improves efficiency)

@gaby gaby requested a review from a team as a code owner July 17, 2024 04:02
@gaby gaby requested review from sixcolors, ReneWerner87 and efectn and removed request for a team July 17, 2024 04:02
Copy link
Contributor

coderabbitai bot commented Jul 17, 2024

Walkthrough

The changes focus on optimizing the adaptor middleware for improved performance and efficiency. Key enhancements include reduced response times, lower memory usage, and fewer memory allocations. These improvements are achieved through the introduction of a sync.Pool for managing fasthttp.RequestCtx instances and better handling of HTTP requests and responses between net/http and fasthttp contexts, leading to a more reliable and capable service.

Changes

File/Path Summary of Changes
docs/whats_new.md Updated summary of changes highlighting significant performance optimizations in the adaptor middleware.
middleware/adaptor/adaptor.go Added sync.Pool for managing fasthttp.RequestCtx instances, refactored HTTP request/response handling, and optimized context management.

Poem

In the realm where code does dance,
Middleware now takes a chance.
Fast and light, like the breeze,
Memory freed with utmost ease.
Response swift, a rabbit's delight,
Efficiency shines, day and night. 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@gaby gaby changed the title v3: Improve Adaptor Middleware Performance v3: Improve performance of Adaptor Middleware Jul 17, 2024
Copy link

codecov bot commented Jul 17, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 83.14%. Comparing base (58d07f0) to head (d5f7648).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3078      +/-   ##
==========================================
+ Coverage   83.10%   83.14%   +0.03%     
==========================================
  Files         115      115              
  Lines        8321     8328       +7     
==========================================
+ Hits         6915     6924       +9     
+ Misses       1076     1075       -1     
+ Partials      330      329       -1     
Flag Coverage Δ
unittests 83.14% <100.00%> (+0.03%) ⬆️

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.

@gaby gaby added this to the v3 milestone Jul 17, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 58d07f0 and 5e58210.

Files selected for processing (2)
  • docs/whats_new.md (1 hunks)
  • middleware/adaptor/adaptor.go (5 hunks)
Additional comments not posted (7)
middleware/adaptor/adaptor.go (5)

17-21: Approved the introduction of sync.Pool for managing fasthttp.RequestCtx instances.

The use of sync.Pool is a good practice for reducing memory allocations and improving performance. Ensure that fasthttp.RequestCtx objects are properly reset before reuse to avoid any side effects.


169-173: Approved the use of ctxPool in handlerFunc for acquiring and releasing fasthash.RequestCtx.

The implementation correctly utilizes the pool to manage fasthttp.RequestCtx instances, which should help in reducing memory allocations and improving performance. Verify that contexts are correctly acquired and released.


191-191: Approved the response conversion in handlerFunc.

The conversion from fasthttp.RequestCtx to net/http response is implemented correctly. Verify that all headers and status codes are correctly transferred to ensure a seamless client experience.


137-137: Verify error handling in handlerFunc.

Ensure that errors during the request body copying are correctly handled and that appropriate HTTP error responses are sent to the client.

Also applies to: 152-152

Verification successful

The error handling in handlerFunc is correctly implemented.

  • If an error occurs during the body copying process, an HTTP 500 error response is sent to the client.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify error handling in `handlerFunc`.

# Test: Search for error handling patterns in the function.
rg --type python -A 5 $'handlerFunc'

Length of output: 66


Script:

#!/bin/bash
# Description: Verify error handling in `handlerFunc`.

# Test: Search for the handlerFunc definition and inspect error handling.
rg --type go -A 10 'func handlerFunc' middleware/adaptor/adaptor.go

Length of output: 438


Script:

#!/bin/bash
# Description: Verify error handling in `handlerFunc`.

# Test: Search for the complete error handling in handlerFunc.
rg --type go -A 20 'func handlerFunc' middleware/adaptor/adaptor.go

Length of output: 717


93-98: Verify the handling of HTTP headers and context in middleware.

Ensure that HTTP headers are not overwritten unintentionally and that the context copying from http.Request to fiber.Ctx is done efficiently.

Verification successful

Verified the handling of HTTP headers and context in middleware.

The HTTPMiddleware function correctly handles the setting of HTTP method, URI, and headers from the http.Request to the fiber.Ctx, ensuring that headers are not unintentionally overwritten and context is copied efficiently.

  • middleware/adaptor/adaptor.go lines 93-98
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the handling of headers and context in middleware.

# Test: Search for the function usage and check for potential header overwrites.
rg --type python -A 5 $'HTTPMiddleware'

Length of output: 69


Script:

#!/bin/bash
# Description: Verify the handling of headers and context in middleware.

# Test: Search for the function usage and check for potential header overwrites.
rg --type go -A 5 HTTPMiddleware

Length of output: 1380


Script:

#!/bin/bash
# Description: Extract the full implementation of the HTTPMiddleware function to review header handling.

# Extract the HTTPMiddleware function implementation.
ast-grep --lang go --pattern $'func HTTPMiddleware($_) $_ {
    $$$
}'

Length of output: 1839

docs/whats_new.md (2)

257-284: Impressive documentation on Adaptor middleware improvements.

The documentation clearly outlines the significant performance improvements in the Adaptor middleware, including detailed metrics. This aligns well with the PR objectives and provides users with a clear understanding of the benefits.

  • Execution Time: The improvements are consistently above 40%, which is a great enhancement.
  • Memory Usage: The reductions are impressive, nearly 90% in most cases.
  • Allocations: The reduction to 5 allocs/op from 16 is substantial.

This section is well-documented and provides valuable information to the users about the improvements. It's also good to see the detailed metrics for different payload sizes, which helps in understanding the scalability of the improvements.


Line range hint 1-284: General Documentation Review: Comprehensive and Informative

Overall, the documentation is comprehensive and covers a wide range of changes and improvements in Fiber v3. The migration guides are detailed, providing users with clear instructions on how to adapt their existing applications to the new version. The use of caution labels in draft sections is a good practice, ensuring that users are aware these sections are not finalized.

Here are a few suggestions for improvement:

  1. Ensure all draft sections are completed before the final release to provide users with full information.
  2. Consider adding more examples where significant changes are introduced, especially in areas like the new routing and middleware registration methods, to help users better understand the new patterns.

The documentation effectively communicates the enhancements and changes, making it easier for users to transition to the new version.

Tools
LanguageTool

[grammar] ~287-~287: Do not use the singular ‘a’ before the plural noun ‘conditions’.
Context: ...ache management, allowing you to define a custom conditions for invalidating cache entries. ### CO...

(VB_A_JJ_NNS)

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 5e58210 and d5f7648.

Files selected for processing (1)
  • docs/whats_new.md (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • docs/whats_new.md

@ReneWerner87 ReneWerner87 merged commit 091a594 into main Jul 18, 2024
17 checks passed
@gaby gaby deleted the improve-adaptor branch July 21, 2024 20:17
gaby added a commit that referenced this pull request Jul 25, 2024
* Improve performance of adaptor middleware by over 50%

* Update whats_new documentation

* Remove fasthttp.Request pool

* Update whats_new.md
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

None yet

3 participants