Skip to content

Conversation

edvardsanta
Copy link
Contributor

@edvardsanta edvardsanta commented Aug 12, 2025

Description

This PR refactors the timeout middleware to properly enforce request timeouts by:

  1. Wrapping the handler execution in a goroutine.
    2 Using a select statement to handle three possible outcomes:

    • Handler completes successfully.
    • Handler panics (panic is propagated).
    • Timeout occurs, triggering cfg.OnTimeout if set, or returning fiber.ErrRequestTimeout..

This change guarantees that:

  • The timeout is respected in real time.
  • Handlers have the opportunity to observe context cancellation if needed.
  • Panics are safely propagated without losing stack traces.

Fixes #3671

Changes introduced

List the new features or adjustments introduced in this pull request. Provide details on benchmarks, documentation updates, changelog entries, and if applicable, the migration guide.

  • Benchmarks: Describe any performance benchmarks and improvements related to the changes.
  • Documentation Update: Detail the updates made to the documentation and links to the changed files.
  • Changelog/What's New: Include a summary of the additions for the upcoming release notes.
  • Migration Guide: If necessary, provide a guide or steps for users to migrate their existing code to accommodate these changes.
  • API Alignment with Express: Explain how the changes align with the Express API.
  • API Longevity: Discuss the steps taken to ensure that the new or updated APIs are consistent and not prone to breaking changes.
  • Examples: Provide examples demonstrating the new features or changes in action.

Type of change

Please delete options that are not relevant.

  • New feature (non-breaking change which adds functionality)
  • Enhancement (improvement to existing features and functionality)
  • Documentation update (changes to documentation)
  • Performance improvement (non-breaking change which improves efficiency)
  • Code consistency (non-breaking change which improves code reliability and robustness)

Checklist

Before you submit your pull request, please make sure you meet these requirements:

  • Followed the inspiration of the Express.js framework for new functionalities, making them similar in usage.
  • [] Conducted a self-review of the code and provided comments for complex or critical parts.
  • Updated the documentation in the /docs/ directory for Fiber's documentation.
  • Added or updated unit tests to validate the effectiveness of the changes or new features.
  • Ensured that new and existing unit tests pass locally with the changes.
  • Verified that any new dependencies are essential and have been agreed upon by the maintainers/community.
  • Aimed for optimal performance with minimal allocations in the new code.
  • Provided benchmarks for the new code to analyze and improve upon.

Commit formatting

Please use emojis in commit messages for an easy way to identify the purpose or intention of a commit. Check out the emoji cheatsheet here: CONTRIBUTING.md

Copy link
Contributor

coderabbitai bot commented Aug 12, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. 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.

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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>, please review it.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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

@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.

Summary of Changes

Hello @edvardsanta, 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 addresses a critical bug in the Fiber framework's timeout middleware where it failed to properly enforce timeouts, particularly when request handlers blocked indefinitely or panicked after the timeout period. The changes refactor the middleware to execute handlers concurrently, enabling reliable timeout detection and robust panic recovery for both the main handler and custom timeout callbacks. This ensures that the application consistently responds with a Request Timeout status when a handler exceeds its allocated time, significantly improving the middleware's reliability and resilience.

Highlights

  • Concurrent Handler Execution: The timeout middleware now executes the wrapped handler in a separate goroutine. This allows the middleware to effectively monitor the handler's execution time independently and enforce timeouts even if the handler blocks indefinitely.
  • Improved Timeout Enforcement: The middleware now uses a select statement to wait for one of three events: the handler completing successfully, the handler panicking, or the context timing out. This ensures that timeouts are reliably enforced and appropriate fiber.ErrRequestTimeout responses are returned.
  • Enhanced Panic Handling: Robust panic recovery has been implemented for both the main handler and the custom OnTimeout callback. If either panics, the middleware catches the panic and ensures that a fiber.ErrRequestTimeout is returned, preventing application crashes.
  • Expanded Test Coverage: Comprehensive new test cases have been added to cover various challenging scenarios, including handlers that block forever, handlers that panic, and situations where the custom OnTimeout callback itself panics.
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 in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

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 issue 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.

Copy link
Contributor

@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 correctly refactors the timeout middleware to use a goroutine and a select statement, which properly enforces timeouts. This fixes a fundamental bug in the previous implementation. The new test suite also adds valuable coverage for edge cases. My main feedback is regarding panic handling. The current implementation swallows panics from the handler and returns a timeout error, which can hide critical bugs. I've suggested re-panicking instead to let the framework's standard error handling take over.

Comment on lines 40 to 41
case _ = <-panicChan:
return fiber.ErrRequestTimeout
Copy link
Contributor

Choose a reason for hiding this comment

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

high

Handling a panic by returning fiber.ErrRequestTimeout hides the original panic and its stack trace, which is crucial for debugging. A panic typically indicates a critical server-side issue that should result in a 500 Internal Server Error, not a 408 Request Timeout. It's better to re-panic to allow Fiber's default panic handling mechanism to take over.

Suggested change
case _ = <-panicChan:
return fiber.ErrRequestTimeout
case p := <-panicChan:
panic(p)

@edvardsanta
Copy link
Contributor Author

Hello, @ReneWerner87, @gaby ,@own2pwn, @sixcolors.

I’m exploring some edge cases around the Timeout middleware and would like your thoughts on expected behavior. Specifically, I’m wondering how Fiber should behave when a panic occurs in the handler. I have written two tests cases:
Handler panics after timeout:

handler: func(_ fiber.Ctx) error {
      time.Sleep(50 * time.Millisecond)
      panic("panic after timeout")
}

Custom OnTimeout handler panics:

handler: func(_ fiber.Ctx) error {
		time.Sleep(50 * time.Millisecond)
		return nil
	},
	config: Config{
		Timeout: 10 * time.Millisecond,
		OnTimeout: func(_ fiber.Ctx) error {
			panic("custom panic on timeout")
		},
},

My questions:

  1. In the case of a panic after the timeout has already triggered, should Fiber still return a 408 Request Timeout, or should the panic propagate?

  2. For a panic inside a custom OnTimeout handler, do we have an expected status code, or should the panic be allowed to crash the app?

  3. Any recommendations on handling these panics safely in production while maintaining the correct timeout semantics?

I’m not sure what the “correct” behavior should be here, so I’d like to align it first before to open the pr

@gaby
Copy link
Member

gaby commented Aug 17, 2025

@edvardsanta

  1. Return 408
  2. Probably 408 too
  3. Add tests for them, testify has a way of testing these

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.

🐛 [Bug]: timeout is not actually enforced
2 participants