-
Notifications
You must be signed in to change notification settings - Fork 40.8k
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
Allow the embedded web server to be shut down gracefully #4657
Comments
We currently stop the application context and then stop the container. We did try to reverse this ordering but it had some unwanted side effects so we're stuck with it for now at least. That's the bad news. The good news is that you can actually get a graceful shutdown yourself if you're happy to get your hands a bit dirty. The gist is that you need to pause Tomcat's connector and then wait for its thread pool to shutdown before allowing the destruction of the application context to proceed. It looks something like this: package com.example;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class Gh4657Application {
public static void main(String[] args) {
SpringApplication.run(Gh4657Application.class, args);
}
@RequestMapping("/pause")
public String pause() throws InterruptedException {
Thread.sleep(10000);
return "Pause complete";
}
@Bean
public GracefulShutdown gracefulShutdown() {
return new GracefulShutdown();
}
@Bean
public EmbeddedServletContainerCustomizer tomcatCustomizer() {
return new EmbeddedServletContainerCustomizer() {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
if (container instanceof TomcatEmbeddedServletContainerFactory) {
((TomcatEmbeddedServletContainerFactory) container)
.addConnectorCustomizers(gracefulShutdown());
}
}
};
}
private static class GracefulShutdown implements TomcatConnectorCustomizer,
ApplicationListener<ContextClosedEvent> {
private static final Logger log = LoggerFactory.getLogger(GracefulShutdown.class);
private volatile Connector connector;
@Override
public void customize(Connector connector) {
this.connector = connector;
}
@Override
public void onApplicationEvent(ContextClosedEvent event) {
this.connector.pause();
Executor executor = this.connector.getProtocolHandler().getExecutor();
if (executor instanceof ThreadPoolExecutor) {
try {
ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor;
threadPoolExecutor.shutdown();
if (!threadPoolExecutor.awaitTermination(30, TimeUnit.SECONDS)) {
log.warn("Tomcat thread pool did not shut down gracefully within "
+ "30 seconds. Proceeding with forceful shutdown");
}
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
}
} I think it makes sense to provide behaviour like this out of the box, or at least an option to enable it. However, that'll require a bit more work as it'll need to work with all of the embedded containers that we support (Jetty, Tomcat, and Undertow), cope with multiple connectors (HTTP and HTTPS, for example) and we'll need to think about the configuration options, if any, that we'd want to offer: switching it on or off, configuring the period that we wait for the thread pool to shutdown, etc. |
Thank you for your advice. What do you thing, will it be possible in future to shut down a spring boot application more gracefully? |
Yes. As I said above "I think it makes sense to provide behaviour like this out of the box, or at least an option to enable it". I'm going to re-open this issue as we'll use it to track the possible enhancement. |
+1 on this request. We ran into a similar problem when load testing and dropping a node from the test. @wilkinsona in your example, I was thinking of using an implementation of smartlifecylce so I can insure the connector is shutdown first. You said you ran into issues shutting down tomcat first? |
I think the right order is:
so we do it as follows:
|
This issue is actually a bit more complicated. I know that SmartLifeCycle can be used to set the order in which beans are notified of life cycle events. However, there is no generalized way for a service to know it should startup/shutdown before another service. Consider the following: A sprint boot application is running an embedded servlet container and is also producing/consuming JMS messages. On the close event, the servlet container really needs to pause the connector first, process its remain working (any connections that have already been establish.) We need to insure this is the FIRST thing that happens, prior to the JMS infrastructure shutting down because the work done inside tomcat may rely on JMS. The JMS infrastructure has a similar requirement: it must stop listening for messages and chew through any remaining messages it has already accepted. I can certainly implement a SmartLifeCycle class that sets the phase "very high"....and I could even create two instances, one for embedded servlet container and one for JMS and insure the correct order. But in the spirit of Spring Boot, if I add a tomcat container, its my expectation that when the application shuts down, it will gracefully stop accepting connections, process remaining work, and exit. It would be helpful if there was a mechanism to allow ordering to be expressed relative to other services "JMS must start before tomcat", "tomcat must close before JMS". This would be similar to the AutoConfigureBefore/AutoConfigureAfter annotations that are used in Spring boot. One way to approach this might be to create an enum for the generalized services (This is not ideal, but I can't think of another way without introducing artificial, compile time dependencies.): EMBEDDED_CONTAINER For now, its up to the developer to explicitly define the shutdown order of services via "SmartLifeCycle" instances...which can get a bit messy and seems like extra work for something that should really work out of the box. |
@tkvangorder You don't need to use Beyond this, Spring Framework already has support for closing things down in the correct order. For example you can implement |
@wilkinsona is the order of shutdown anyway guaranteed ? Is spring boot always going to shutdown application context first? we are trying to implement what you said, but was not sure if this will change in the future. |
Yes. When you're using an embedded container, it's the application context being shut down that triggers the shutdown of the container. |
I want to report back on how to setup this correctly using Jetty and springboot , use this class instead of public class HttpConfig {
private static final Logger log = LoggerFactory.getLogger(HttpConfig.class);
private static volatile Server server;
// Jetty HTTP Server
//
// see [1] on how to implement graceful shutdown in springboot.
// Note that since use jetty, we need to use server.stop(), also StatisticsHandler must be
// configured, for jetty graceful shutdown to work.
//
// [1]: https://github.com/spring-projects/spring-boot/issues/4657
@Bean
@Autowired
public JettyEmbeddedServletContainerFactory jettyEmbeddedServletContainerFactory(HttpSetting httpSetting) {
JettyEmbeddedServletContainerFactory factory = new JettyEmbeddedServletContainerFactory();
factory.setPort(httpSetting.getPort());
log.info("Jetty configured on port: " + httpSetting.getPort());
factory.addServerCustomizers(new JettyServerCustomizer() {
@Override
public void customize(Server server1) {
server = server1;
log.info("Jetty version: " + server.getVersion());
// Configure shutdown wait time.
if (httpSetting.getShutdownWaitTime() > 0) {
// Add StatsticsHandler, in order for graceful shutdown to work.
StatisticsHandler handler = new StatisticsHandler();
handler.setHandler(server.getHandler());
server.setHandler(handler);
log.info("Shutdown wait time: " + httpSetting.getShutdownWaitTime() + "s");
server.setStopTimeout(httpSetting.getShutdownWaitTime());
// We will stop it through JettyGracefulShutdown class.
server.setStopAtShutdown(false);
}
}
});
return factory;
}
@Bean
public JettyGracefulShutdown jettyGracefulShutdown() { return new JettyGracefulShutdown(); }
// Springboot closes application context before everything.
private static class JettyGracefulShutdown implements ApplicationListener<ContextClosedEvent>{
private static final Logger log = LoggerFactory.getLogger(JettyGracefulShutdown.class);
@Override
public void onApplicationEvent(ContextClosedEvent event) {
if (server == null) {
log.error("Jetty server variable is null, this should not happen!");
return;
}
log.info("Entering shutdown for Jetty.");
if (!(server.getHandler() instanceof StatisticsHandler)) {
log.error("Root handler is not StatisticsHandler, graceful shutdown may not work at all!");
} else {
log.info("Active requests: " + ((StatisticsHandler) server.getHandler()).getRequestsActive());
}
try {
long begin = System.currentTimeMillis();
server.stop();
log.info("Shutdown took " + (System.currentTimeMillis() - begin) + " ms.");
} catch (Exception e) {
log.error("Fail to shutdown gracefully.", e);
}
}
}
} |
The tomcat version didn't work as-is for me because |
@clanie: Can you post the code you did for that? We're running into a similar problem and I'd like to see a working solution if you have one. |
I found this article. |
Hi, forgive me if i am mistaken. isnt it simpler... to just count the number of requests (From Filter) ? and then when the number is 0 just signal for grceful shutdown ? Thanks! |
No, not really. You need to stop accepting new requests, wait for any active requests to complete, and then gracefully shut everything down. If you just wait for the number of active requests to reach 0 there's then a race condition between new requests being accepted and the shutdown completing. |
@wilkinsona thanks for your response ! ... i would like to regard. You said:
Solution: public class LimitFilter implements Filter {
public static AtomicBoolean isRunning = true;
public int count;
private Object lock = new Object();
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
try {
if (isRunning) {
// let the request through and process as usual
synchronized (lock) {
count++;
}
try{
chain.doFilter(request, response);
}finaly{
synchronized (lock) {
count--;
}
}
} else {
//return server unavailable http status 503
}
} finally {
synchronized (lock) {
if(count==0 && !isRunning)
AppSingleton.signalSafeShutdown();
}
}
} now from shutdown hook:
Description: i would be happy if someone sees any problem with this kind of approach rather than trying complex solution of reverting the shutdown order and handling container specific complex code.... ? thanks. |
@AvishayHirsh Thanks for your efforts, but you are over-simplifying the problem. Firstly, your solution does not stop accepting requests, instead it accepts them and then responds with a 503. We need to pause the container's connectors so that they stop allowing clients to connect at all. Secondly, your mechanism for counting active requests means that all requests briefly become single threaded. That will have an unacceptable impact on performance. |
A snapshot containing the new functionality is now available from https://repo.spring.io/snapshot. |
Thanks for working on this @wilkinsona I find the documentation a bit confusing, specifically "Jetty, Reactor Netty, and Tomcat will stop accepting requests at the network layer."
Most of our applications run on AWS Elastic Container Service (ECS). They are primarily behind two different types of load-balancers: AWS Application Load Balancer (ALB): AWS Network Load Balancer (NLB) Right now, we use custom application logic (in a Filter) to discover when the LB deregistration process begins, and we start sending Framework support for gracefully closing existing connections after in-flight requests complete (once the app receives SIGTERM) would be very helpful in this scenario. |
Thanks for taking a look, @joedj.
We're making as much use as possible of each container's built-in capabilities, which often aren't documented or consider the exact behaviour to be an implementation detail and this is one area where the containers vary. For example, Tomcat will close idle connections such that a new request cannot be made on it.
I don't believe that any of the containers distinguish between this scenario and the scenario above. As above, the exact behaviour varies from container to container.
There's an awkward balance for us to strike here. The currently described difference (rejected requests at the network layer versus them being accepted and then responded to with a 503) is within our control but, beyond that, the subtleties are container-specific and are often undocumented implementation details. I can only assume that's because the users of each container haven't needed to know the precise details to make use of the feature. If we documented things more precisely we'd be running the risk of our documentation becoming out of date as a container made a change to its behaviour. We could, perhaps, document what we do in terms of API calls as that is within our control.
At the time of writing, Tomcat and Undertow do not. When an in-flight request completes successfully after graceful shutdown has begun, both respond with a
The container will be shutting down gracefully if you've configured
It sounds like the time that you've been given to handle outstanding in-flight requests is of fixed duration. For example, if you're being given 30 seconds to finish handling in-flight requests, shutdown will take at least 30 seconds even if those requests complete after 1 second. With graceful shutdown, you should be able to configure a deregistration delay of 0 seconds so that
While Tomcat will not send
I'd like to understand why sending |
Hey @wilkinsona, thanks for the response. I'll just answer your last question, for now, until I hopefully get a chance to play around:
(This is specifically in relation to shutting down gracefully while using NLB, which will continue to send requests on existing connections up until they are closed) Because we don't currently have a nice way to gracefully shut down the container upon receiving SIGTERM (and some other internal legacy reasons that mean we currently only have a max of 30sec after SIGTERM), we instead perform the graceful connection draining before the actual app shutdown process begins. To do this, we use the LB Deregistration Delay functionality. For NLB, this controls the duration between when the app will stop receiving new TCP connections, and when the app will receive SIGTERM. For our app to discover that it has changed state in the LB from "healthy" to "draining" (signalling that the Deregistration Delay period has started), it polls the AWS APIs. This happens once per minute - any more frequent than that, and we often hit API rate limits. So, the Deregistration Delay needs to be at least 1min or so, for us to be sure we have even seen the state change. Once we notice the state change, there are additional delays:
...but those additional delays also exist if we start draining in response to SIGTERM, rather than in response to an LB state change. So really, using the Spring support for graceful shutdown in response to SIGTERM would only allow us to save that initial 60sec delay while polling the LB state (edit: and also, as you accurately pointed out in your earlier response, it would also mean that shutdown completes when all the in-flight requests are finished, rather than waiting for the fixed Deregistration Delay period - in practice, this could reduce the container shutdown time from 3min+ to mere seconds (or 60sec, i.e. the idle timeout we need to wait for any new requests on existing connections, assuming the web container we're using supports this and doesn't close those idle connections immediately when graceful shutdown begins). ...and it would also allow us to delete all that supporting code and get rid of the unreliable scheduled polling. |
Standalone Jetty will, by default, include a Connection: close header in all responses once graceful shutdown has begun. Previously, the way in which we were shutting Jetty down did not cause this to happen. This commit updates JettyGracefulShutdown to shut down each connector. This causes Jetty to send the Connection: close header, aligning its behaviour more closely with what it does when used standalone. The tests have also been updated to verify this behaviour and to ensure that the correct port is used for requests even once the connector is no longer bound and the web server no longer knows its ephemeral port. See gh-4657
On kubernetes we have a different requirement when shutting down gracefully when doing rolling updates or scaling a deployment down. According to this blog post and to our own experience you need to wait for a couple of seconds after receiving the |
Thanks, @ractive. What you've described matches our experience too. Rather than implementing the wait in Spring Boot, our recommendation is to use a pre-stop hook configured to run something like |
This is correct. Its also documented in the book : Kubernetes in Action (ISBN: 9781617293726), under Chapter 17. Best practices for developing apps. I think the sleep based configuration would be good enough in our case (infact we did the same thing in our application). I expect that the configuration Thanks for taking this up. |
Hi, I have a spring-boot app with HTTP endpoints and Kafka consumers. I have tested this graceful shutdown implementation and it looks like the whole shutdown is delayed waiting for HTTP with Thread.sleep(), so no other components are notified. This means I need 2*n graceful period if I wanted to give HTTP and Kafka n seconds to finish their thing. @wilkinsona I saw your comment about not needing SmartLifecycle just for tomcat, but have you considered other components needing graceful shutdown as well? In my case, I would like to leave some time for both @controllers and Kafka Listeners to be able to finish already started processing -- which in some cases can make external calls with exponential backoff, so I would also like to be able to check in retry loops if shutdown was initiated. I'm thinking about such logic:
Would you consider changing the above logic, or recommend a custom implementation instead? |
@gnagy Even in our deployment, we have HTTP endpoints and Kafka consumers. So we want to stop Kafka consumers from consuming the messages and processes already consumed messaged within the grace period. |
I no longer have access to that project but if I remember correctly Spring Kafka integration already supported stop()-ing the listener container when the application context is shutting down, we just had to make sure our custom RetryTemplates in the consumers got notified as well. |
@gnagy Thanks. I saw spring-Kafka has stop() method on application context shutdown. |
Now there is the graceful shutdown feature (https://docs.spring.io/spring-boot/docs/current/reference/html/web.html#web.graceful-shutdown), but this feature uses a timeout, and only waits within the timeout. But sometimes I want to wait till all the requests are processed, without a timeout. Could you please support this? |
@zdaccount what would happen if one of those outstanding requests is blocked and never finishes? The application instance would then stay up for ever? |
Yes, sometimes I want that. If the application instance hangs, then I may force kill it, but sometimes I don't want the instance itself to do this. I think that this is like how the web server processes requests. When the web server process a request, there is no timeout on the process logic (I assume this, but I may be wrong, since I am new to Spring Boot). If this is the case, then it is also reasonable to have no timeout for the last requests. |
I don’t think it’s reasonable to have no timeout at all. For one, it is highly unlikely that any network connection will survive indefinitely so the server will be unable to send a response. Instead, I would recommend configuring a timeout that’s slightly greater than the maximum time that you would wait before manually killing the application instance. |
But there is no timeout on the ordinary processing of requests, right? If this is the case, then it seems also reasonable to have no timeout on the processing of last requests. |
Requests that have the potential to be long-running should be async and will then be subject to the async request timeout. This timeout is in addition to timeouts at the network level. In a Spring MVC app, a request can be made async by returning |
When I am testing, I am seeing the container (Tomcat) getting shutdown before the application context / beans have shutdown. From logs, the order is:
Which is problematic for me: I have some async threads running some computations, and the server is publishing metrics/health of that computation via its API. When shutdown is triggered, I want the computations to gracefully exit, but keep the server running and accepting connections to have metrics/health during that shutdown period. I can wait for the computation to finish in Application context or Predestroy hooks, but the tomcat server shuts down anyways. Any solution that would allow the server to stay up while the async thread is finishing its computation? |
You'll have to implement If you have any further questions, please follow up on Stack Overflow. As mentioned in the guidelines for contributing, we prefer to use GitHub issues only for bugs and enhancements. |
Follow up, for those reading this thread in the future |
We are using spring-boot and spring-cloud to realize a micro service archtecture. During load tests we are facing lots of errors such as "entitymanager closed and others" if we shut the micro service down during load.
We are wondering if there is an option to configure the embedded container to shut its service connector down and waits for an empty request queue before shutting down the complete application context.
If there is no such option, I did not find any, then it would be great to extend the shutdownhook of spring to respect such requirements.
The text was updated successfully, but these errors were encountered: