fiber icon indicating copy to clipboard operation
fiber copied to clipboard

πŸ› [Bug]: Request Context Cancelled on Graceful Shutdown

Open abanoub-fathy opened this issue 8 months ago β€’ 11 comments

πŸ“ Bug Description

When using graceful shutdown with Fiber, if there's a long-running request in progress (e.g. a database query), the request's context.Context is immediately canceled once app.Shutdown() is called. This leads to the request failing with a 500 Internal Server Error with error failed to get user: context canceled, even though the user initiated the request before the shutdown started.

This behavior creates a poor user experience, especially in production environments where graceful termination of active connections is expected. πŸ™

πŸ” How to Reproduce

  • Start a Fiber app with a handler that simulates a slow operation (e.g. sleep + DB call).
  • Send a request to that handler.
  • While the request is still processing, trigger a graceful shutdown via app.Shutdown().
  • Observe that the request fails with a 500 due to context cancellation with this error failed to get user: context canceled.

Here is a simple example

func main() {
	app := fiber.New(fiber.Config{
		ReadTimeout:  time.Second * 30,
		WriteTimeout: time.Second * 20,
	})

	app.Get("/", func(c *fiber.Ctx) error {
		// Simulate a long-running request
		time.Sleep(time.Second * 10)

		// This DB call will fail if context is canceled
		user, err := getUser(c.Context())
		if err != nil {
			return err // results in 500 if shutdown started
		}

		return c.JSON(user)
	})

	go func() {
		if err := app.Listen(":8080"); err != nil {
			log.Panic(err)
		}
	}()

	// Wait for interrupt signal
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, syscall.SIGTERM)
	<-c

	fmt.Println("Gracefully shutting down...")
	_ = app.Shutdown() // This cancels the context of in-flight requests
	fmt.Println("Cleanup done.")
}

// getUser simulates a DB query that respects context
func getUser(ctx context.Context) (*models.User, error) {
	var user models.User
	if err := db.GetContext(ctx, &user, `SELECT * FROM users LIMIT 1`); err != nil {
		return nil, fmt.Errorf("failed to get user: %w", err)
	}
	return &user, nil
}

πŸ’₯ Expected Behavior

  • Ongoing requests should be allowed to complete before shutdown fully proceeds.
  • Context should not be canceled immediately upon calling Shutdown() if the request is already in progress.

βœ… Suggested Fix

It would be great if Fiber could delay context cancellation for in-flight requests or provide a mechanism to wait for active requests to finish before finalizing the shutdown process. This would better align with typical graceful shutdown behavior seen in other Go HTTP frameworks.

Fiber Version

v2.52.6

Checklist:

  • [x] I agree to follow Fiber's Code of Conduct.
  • [x] I have checked for existing issues that describe my problem prior to opening this one.
  • [x] I understand that improperly formatted bug reports may be closed without explanation.

abanoub-fathy avatar May 02 '25 05:05 abanoub-fathy

Thanks for opening your first issue here! πŸŽ‰ Be sure to follow the issue template! If you need help or want to chat with us, join us on Discord https://gofiber.io/discord

welcome[bot] avatar May 02 '25 05:05 welcome[bot]

app.Get("/", func(c *fiber.Ctx) error { time.Sleep(time.Second * 10)

// Use context.Background() instead of c.Context()
user, err := getUser(context.Background()) 
if err != nil {
    return err
}
return c.JSON(user)

})

RajaSunrise avatar May 05 '25 16:05 RajaSunrise

app.Get("/", func(c *fiber.Ctx) error { time.Sleep(time.Second * 10)

// Use context.Background() instead of c.Context()
user, err := getUser(context.Background()) 
if err != nil {
    return err
}
return c.JSON(user)

})

from what I know we should use the request context so if the user cancel the request the processing should stop that's what I am trying to do while achieving graceful shutdown

abanoub-fathy avatar May 06 '25 17:05 abanoub-fathy

@gofiber/maintainers

Anyone πŸ“’ could help in this please
this bug πŸ› should be considered as critical πŸ›‘ bug

abanoub-fathy avatar May 16 '25 02:05 abanoub-fathy

@abanoub-fathy I'm assuming this is related to your other question? https://github.com/gofiber/fiber/issues/3430

gaby avatar May 16 '25 03:05 gaby

Hey @gaby, thanks again for your help! πŸ™

In the other question (#3430), I wasn’t able to find a way to detect when the request context is canceled if the user cancels the request.

But this issue is a bit different. What’s happening here is that when the server receives a graceful shutdown signal, all the contexts β€” c.Context() and c.UserContext() β€” are immediately cancelled.

and I received

failed to get user: context canceled

even though the user initiated the request before the shutdown started.

Just to clarify β€” this doesn’t normally happen with standard HTTP frameworks. Usually, active requests are allowed to finish before shutdown completes. But in this case, the context is getting canceled right away, which interrupts the request handling unexpectedly.

abanoub-fathy avatar May 16 '25 05:05 abanoub-fathy

If nobody fix it in the past days, assign to me@abanoub-fathy

krisdiano avatar May 29 '25 13:05 krisdiano

I try reproducing it, but I found the latest version is what you want. @abanoub-fathy

krisdiano avatar Jun 03 '25 06:06 krisdiano

@krisdiano

which version did you try it?

I tried it with latest v2 version which is v2.52.8 but still have the same issue

Did you try to reproduce it with v2 or v3 ?

abanoub-fathy avatar Jun 04 '25 04:06 abanoub-fathy

v3

Get Outlook for Androidhttps://aka.ms/AAb9ysg


From: Abanoub Fathy @.> Sent: Wednesday, June 4, 2025 12:12:38 PM To: gofiber/fiber @.> Cc: krisdiano @.>; Mention @.> Subject: Re: [gofiber/fiber] πŸ› [Bug]: Request Context Cancelled on Graceful Shutdown (Issue #3431)

[https://avatars.githubusercontent.com/u/95833413?s=20&v=4]abanoub-fathy left a comment (gofiber/fiber#3431)https://github.com/gofiber/fiber/issues/3431#issuecomment-2938405737

@krisdianohttps://github.com/krisdiano

which version did you try it?

I tried it with latest v2 version which is v2.52.8 but still have the same issue

Did you try to reproduce it with v2 or v3 ?

β€” Reply to this email directly, view it on GitHubhttps://github.com/gofiber/fiber/issues/3431#issuecomment-2938405737, or unsubscribehttps://github.com/notifications/unsubscribe-auth/ALFKFGNIJLSHOU7J3NGVZP33BZW3NAVCNFSM6AAAAAB4JHV3VWVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDSMZYGQYDKNZTG4. You are receiving this because you were mentioned.Message ID: @.***>

krisdiano avatar Jun 04 '25 04:06 krisdiano

Is there a working v2 version where this isn't a problem?

Tay-Day avatar Oct 16 '25 18:10 Tay-Day