API Reference: Drain HTTP Server Plugin
Using the plugin
In the examples below, we use top-level
await
calls to start our server asynchronously. Check out our Getting Started guide to see how we configured our project to support this.
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:
1import { ApolloServer } from '@apollo/server';
2import { expressMiddleware } from '@apollo/server/express4';
3import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer';
4import express from 'express';
5import http from 'http';
6import cors from 'cors';
7import { typeDefs, resolvers } from './schema';
8
9interface MyContext {
10 token?: String;
11}
12
13const app = express();
14// Our httpServer handles incoming requests to our Express app.
15// Below, we tell Apollo Server to "drain" this httpServer,
16// enabling our servers to shut down gracefully.
17const httpServer = http.createServer(app);
18
19const server = new ApolloServer<MyContext>({
20 typeDefs,
21 resolvers,
22 plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
23});
24await server.start();
25
26app.use(
27 '/graphql',
28 cors<cors.CorsRequest>(),
29 express.json(),
30 expressMiddleware(server, {
31 context: async ({ req }) => ({ token: req.headers.token }),
32 }),
33);
34
35await new Promise<void>((resolve) =>
36 httpServer.listen({ port: 4000 }, resolve),
37);
38
39console.log(`🚀 Server ready at http://localhost:4000/graphql`);
Options
Name / Type |
Description |
---|---|
| The server to drain; required. |
| How long to wait before forcefully closing non-idle connections. Defaults to 10_000 (ten seconds). |