Skip to content

🐛 Fix limiter middleware not counting fiber.NewErrorf responses as failed requests#3623

Merged
ReneWerner87 merged 5 commits intomainfrom
copilot/fix-3622
Jul 28, 2025
Merged

🐛 Fix limiter middleware not counting fiber.NewErrorf responses as failed requests#3623
ReneWerner87 merged 5 commits intomainfrom
copilot/fix-3622

Conversation

Copy link
Contributor

Copilot AI commented Jul 27, 2025

The limiter middleware was not properly counting requests that return fiber.NewErrorf(...) as failed requests when SkipSuccessfulRequests: true and SkipFailedRequests: false.

Problem

When a handler returns fiber.NewErrorf(fiber.StatusInternalServerError, "Error"), the limiter middleware would check c.Response().StatusCode() to determine if the request should be skipped. However, at this point the error hasn't been processed by Fiber's error handler yet, so c.Response().StatusCode() returns 200 instead of the expected 500 status code from the error.

This caused failed requests to be incorrectly skipped when SkipSuccessfulRequests: true, breaking rate limiting for error responses.

Example

app.Use(limiter.New(limiter.Config{
    Max:                    1,
    Expiration:             60 * time.Second,
    LimiterMiddleware:      limiter.SlidingWindow{},
    SkipSuccessfulRequests: true,
    SkipFailedRequests:     false,
}))

app.Get("/", func(c fiber.Ctx) error {
    return fiber.NewErrorf(fiber.StatusInternalServerError, "Error")
})

Before: Repeated requests would all return 500 (not rate limited)
After: First request returns 500, subsequent requests return 429 (properly rate limited)

Solution

Added a getEffectiveStatusCode() helper function that:

  1. Checks if the returned error is a *fiber.Error using errors.As()
  2. If so, uses the error's Code field as the status code
  3. Otherwise, falls back to c.Response().StatusCode()

Both sliding window and fixed window limiters now use this helper to properly determine the effective status code for skip logic.

Testing

  • Added comprehensive tests demonstrating the bug and verifying the fix
  • Manual testing confirmed the original issue scenario now works correctly
  • All existing limiter tests continue to pass

Fixes #3622.

Warning

Firewall rules blocked me from connecting to one or more addresses

I tried to connect to the following addresses, but was blocked by firewall rules:

  • exampleretry.com
    • Triggering command: /tmp/go-build1721103930/b273/client.test -test.paniconexit0 -test.v=test2json -test.timeout=10m0s -test.count=1 -test.shuffle=on (dns block)
    • Triggering command: /tmp/go-build65591961/b271/client.test -test.testlogfile=/tmp/go-build65591961/b271/testlog.txt -test.paniconexit0 -test.timeout=1m0s -test.failfast=true (dns block)
    • Triggering command: /tmp/go-build2682536009/b273/client.test -test.paniconexit0 -test.v=test2json -test.timeout=10m0s -test.count=1 -test.shuffle=on (dns block)

If you need me to access, download, or install something from one of these locations, you can either:


💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

Copilot AI and others added 3 commits July 27, 2025 15:37
…nted by limiter

Co-authored-by: ReneWerner87 <7063188+ReneWerner87@users.noreply.github.com>
…s failed requests

Co-authored-by: ReneWerner87 <7063188+ReneWerner87@users.noreply.github.com>
Co-authored-by: ReneWerner87 <7063188+ReneWerner87@users.noreply.github.com>
Copilot AI changed the title [WIP] 🐛 [Bug]: limiter middleware does not count fiber.NewErrorf responses as failed when SkipSuccessfulRequests: true 🐛 Fix limiter middleware not counting fiber.NewErrorf responses as failed requests Jul 27, 2025
Copilot AI requested a review from ReneWerner87 July 27, 2025 15:54
@codecov
Copy link

codecov bot commented Jul 27, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.14%. Comparing base (c0b2617) to head (693f271).
⚠️ Report is 97 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3623      +/-   ##
==========================================
+ Coverage   91.13%   91.14%   +0.01%     
==========================================
  Files         112      112              
  Lines       11296    11310      +14     
==========================================
+ Hits        10295    10309      +14     
  Misses        744      744              
  Partials      257      257              
Flag Coverage Δ
unittests 91.14% <100.00%> (+0.01%) ⬆️

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.

@ReneWerner87
Copy link
Member

@copilot please fix the linting

Co-authored-by: ReneWerner87 <7063188+ReneWerner87@users.noreply.github.com>
Copy link
Contributor Author

Copilot AI commented Jul 27, 2025

@copilot please fix the linting

Fixed the linting issues in commit 2ae3c5b. Addressed formatting problems and renamed unused parameters in test functions from c to _.

@ReneWerner87 ReneWerner87 marked this pull request as ready for review July 27, 2025 20:31
Copilot AI review requested due to automatic review settings July 27, 2025 20:31
@ReneWerner87 ReneWerner87 requested a review from a team as a code owner July 27, 2025 20:31
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 27, 2025

Important

Review skipped

Bot user detected.

To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


🪧 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>, please review it.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @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.

Support

Need help? Join our Discord community for assistance with any issues or questions.

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 using 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 generate sequence diagram to generate a sequence diagram of the changes in this 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.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

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.

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR fixes a bug in the limiter middleware where fiber.NewErrorf responses were not being properly counted as failed requests when SkipSuccessfulRequests: true and SkipFailedRequests: false. The issue occurred because the middleware was checking the response status code before Fiber's error handler processed the error, causing failed requests to be incorrectly skipped.

  • Added a getEffectiveStatusCode() helper function that checks for *fiber.Error types and uses their code
  • Updated both sliding window and fixed window limiters to use the new status code detection logic
  • Added comprehensive tests to verify the fix works for both limiter types

Reviewed Changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.

File Description
middleware/limiter/limiter.go Adds the getEffectiveStatusCode() helper function to properly detect status codes from fiber errors
middleware/limiter/limiter_sliding.go Updates sliding window limiter to use the new status code detection for skip logic
middleware/limiter/limiter_fixed.go Updates fixed window limiter to use the new status code detection for skip logic
middleware/limiter/limiter_test.go Adds test cases to verify the bug fix for both sliding and fixed window limiters

package limiter

import (
"errors"
Copy link

Copilot AI Jul 27, 2025

Choose a reason for hiding this comment

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

[nitpick] The import should be grouped with standard library imports. Add a blank line after this import to separate it from the third-party imports below.

Copilot uses AI. Check for mistakes.
@ReneWerner87 ReneWerner87 merged commit 8444880 into main Jul 28, 2025
15 checks passed
@ReneWerner87 ReneWerner87 deleted the copilot/fix-3622 branch July 28, 2025 07:21
@ReneWerner87 ReneWerner87 added this to the v3 milestone Aug 26, 2025
@ReneWerner87 ReneWerner87 added this to v3 Aug 26, 2025
@efectn efectn moved this to Done in v3 Jan 23, 2026
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.

🐛 [Bug]: limiter middleware does not count fiber.NewErrorf responses as failed when SkipSuccessfulRequests: true

4 participants