title | api_reference |
---|---|
API Reference: Drain HTTP Server Plugin |
true |
import TopLevelAwait from "../../shared/top-level-await.mdx"
This article documents the options for the ApolloServerPluginDrainHttpServer
plugin, which you can import from @apollo/server/plugin/drainHttpServer
.
This plugin is designed for use with expressMiddleware
and other framework integrations built on top of Node http.Server
s. We highly recommend using this plugin to ensure your server shuts down gracefully.
You do not need to use this plugin with the
startStandaloneServer
function; it automatically handles server draining.
When you use this plugin, Apollo Server will drain your HTTP server when you call the stop()
method (which is also called for you when the SIGTERM
and SIGINT
signals are received, unless disabled with the stopOnTerminationSignals
constructor option).
Specifically, it will:
- Stop listening for new connections
- Close idle connections (i.e., connections with no current HTTP request)
- Close active connections whenever they become idle
- Wait for all connections to be closed
- After a grace period, if any connections remain active, forcefully close them.
This plugin is exported from the @apollo/server
package. Here's a basic example of how to use it with Express:
import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@apollo/server/express4';
import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer';
import express from 'express';
import http from 'http';
import cors from 'cors';
import { typeDefs, resolvers } from './schema';
interface MyContext {
token?: String;
}
const app = express();
// Our httpServer handles incoming requests to our Express app.
// Below, we tell Apollo Server to "drain" this httpServer,
// enabling our servers to shut down gracefully.
const httpServer = http.createServer(app);
const server = new ApolloServer<MyContext>({
typeDefs,
resolvers,
plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
});
await server.start();
app.use(
'/graphql',
cors<cors.CorsRequest>(),
express.json(),
expressMiddleware(server, {
context: async ({ req }) => ({ token: req.headers.token }),
}),
);
await new Promise<void>((resolve) =>
httpServer.listen({ port: 4000 }, resolve),
);
console.log(`🚀 Server ready at http://localhost:4000/graphql`);
Name / Type |
Description |
---|---|
The server to drain; required. |
|
|
How long to wait before forcefully closing non-idle connections. Defaults to |