HTTP/2 improves communication between clients and servers by allowing multiple requests to share a single connection. This reduces connection overhead and makes it possible to handle several operations concurrently without establishing a separate connection for every request. For applications handling a large number of API calls, this can provide meaningful performance benefits.
However, HTTP/2 also introduces additional complexity in connection and stream management. A single client connection can contain multiple independent streams, and errors can occur at different levels of the connection. A client might disconnect while a request is being processed, send invalid protocol data, cancel an individual stream, or close a session unexpectedly.
These situations are normal possibilities in a networked application. The problem begins when the server does not handle them correctly.
In Node.js, an unhandled error event can terminate the process. This means that an HTTP/2 client causing a stream or session error can potentially bring down the entire Node.js application if the corresponding error event is not handled.
For an API server, this is more than a request failure. If the Node.js process exits, every request being handled by that process may be interrupted, including requests from completely unrelated clients.
The solution is not to prevent clients from disconnecting or to ignore every protocol error. A reliable HTTP/2 server must handle errors at the correct level, isolate failures to the affected stream or session, and apply resource limits so that one connection cannot consume an unreasonable amount of server capacity.
Understand How HTTP/2 Handles Connections and Streams
Before handling HTTP/2 errors, it is important to understand the difference between a connection, a session, and a stream.
In HTTP/1.1, applications commonly associate a request with an individual connection, although keep-alive and pipelining can change that relationship. HTTP/2 uses a different model. Multiple requests can be sent over a single connection, with each request represented by an independent stream.
Consider an application receiving three requests from the same browser:
Client
|
| HTTP/2 Connection
|
+------ Stream 1: GET /users
|
+------ Stream 3: GET /orders
|
+------ Stream 5: GET /products
|
Server
All three streams belong to the same HTTP/2 session. If the client cancels the /orders request, the server should normally terminate that stream without affecting the other two requests.
This separation is important because HTTP/2 defines different error-handling scopes.
A stream-level error affects an individual request. For example, a client may cancel a request that it no longer needs. The server receives a stream-related event and should release the resources associated with that request.
A session-level error affects the HTTP/2 connection. It may happen because of a protocol violation or an internal session failure. When a session becomes unusable, its streams may also be affected because they share the same connection.
A server-level error is associated with the HTTP/2 server itself rather than one individual client session.
Node.js exposes these different events through its node:http2 API. Developers need to handle them separately instead of assuming that a single error handler will cover every possible failure.
Why an Unhandled HTTP/2 Error Can Crash Node.js
Node.js uses an event-driven programming model. Objects such as HTTP/2 sessions, streams, and servers extend EventEmitter and communicate failures through events.
One important EventEmitter behavior is that emitting an error event without a registered listener can cause the error to be thrown and terminate the process.
Consider a simplified HTTP/2 server:
import { createSecureServer } from 'node:http2';
import { readFileSync } from 'node:fs';
const server = createSecureServer({
key: readFileSync('./server-key.pem'),
cert: readFileSync('./server-cert.pem')
});
server.on('stream', (stream, headers) => {
stream.respond({
':status': 200,
'content-type': 'application/json'
});
stream.end(
JSON.stringify({ message: 'Request completed' })
);
});
server.listen(8443);
This example demonstrates a basic HTTP/2 response, but it does not include explicit error handling.
Now imagine a client disconnecting while the server is processing a request. The stream or its associated session may emit an error. If the corresponding object does not have an error listener, Node.js may treat it as an unhandled error.
The important detail is that attaching a listener to the server does not automatically mean that every stream and session error has been handled.
For this reason, production applications should understand which object emits each error and attach listeners at the appropriate level.
Handle Stream Errors Independently
The first step is to handle errors associated with individual HTTP/2 streams.
A stream represents one request, so an error in that stream should not automatically affect other requests sharing the same session.
Consider the following implementation:
import { createSecureServer } from 'node:http2';
import { readFileSync } from 'node:fs';
const server = createSecureServer({
key: readFileSync('./server-key.pem'),
cert: readFileSync('./server-cert.pem')
});
server.on('stream', (stream, headers) => {
const method = headers[':method'];
const path = headers[':path'];
stream.on('error', (error) => {
console.error('HTTP/2 stream error:', {
streamId: stream.id,
errorCode: error.code,
message: error.message
});
});
stream.on('close', () => {
console.log('Stream closed:', stream.id);
});
try {
stream.respond({
':status': 200,
'content-type': 'application/json'
});
stream.end(JSON.stringify({
method,
path,
message: 'Request processed'
}));
} catch (error) {
console.error('Unable to process stream:', error.message);
if (!stream.destroyed) {
stream.close();
}
}
});
server.listen(8443);
The stream's error listener handles failures associated with that request. The close event provides a useful place to observe when the stream has been destroyed.
There are two important considerations here.
First, the error listener should be attached as soon as the stream is received. If application code performs asynchronous work before registering the listener, an error could occur before the handler is attached.
Second, do not assume that every stream error means the entire HTTP/2 connection is unusable. A client may cancel one request while other requests continue normally.
The server should release resources associated with the failed request, stop unnecessary processing, and allow unrelated streams to continue.
Handle Session Errors at the Server Level
Stream-level error handling is only one part of the solution. HTTP/2 sessions can also emit errors.
Node.js provides a sessionError event on the HTTP/2 server. This event is emitted when an error event occurs on an HTTP/2 session associated with that server.
This is useful because developers can observe session-level failures centrally without attaching a separate logging mechanism to every session.
For example:
server.on('sessionError', (error, session) => {
console.error('HTTP/2 session error:', {
errorCode: error.code,
message: error.message,
destroyed: session.destroyed
});
});
This handler provides information about the failed session and allows the application to record the incident.
The server also exposes a session event whenever a new HTTP/2 session is created. You can use it to attach session-specific monitoring and lifecycle handlers.
server.on('session', (session) => {
console.log('New HTTP/2 session established');
session.on('error', (error) => {
console.error('Session error:', error.code);
});
session.on('close', () => {
console.log('HTTP/2 session closed');
});
session.on('goaway', (errorCode, lastStreamID) => {
console.log('Received GOAWAY:', {
errorCode,
lastStreamID
});
});
});
The sessionError event and the session's own error event are related. Choose a clear monitoring strategy so that the same failure is not unnecessarily logged twice.
A practical implementation often uses the server's sessionError event for centralized error reporting and the session event for lifecycle monitoring, connection limits, and session-specific behavior.
Also register an error listener on the HTTP/2 server itself:
server.on('error', (error) => {
console.error('HTTP/2 server error:', error);
});
This covers errors emitted by the server object. It does not replace stream or session error handling.
Limit the Number of Concurrent Streams
Handling errors correctly protects the process from unhandled exceptions, but it does not prevent a client from consuming excessive resources.
HTTP/2 allows multiple streams to share a connection. If the server accepts an unrestricted number of concurrent streams, a client can create substantial pressure on memory, CPU, and application-level resources.
The server can advertise a maximum number of concurrent streams through the HTTP/2 settings.
const server = createSecureServer(
{
key: readFileSync('./server-key.pem'),
cert: readFileSync('./server-cert.pem'),
settings: {
maxConcurrentStreams: 100,
initialWindowSize: 65535
}
}
);
The maxConcurrentStreams setting controls how many concurrent streams the server allows the remote peer to create within a session.
The value of 100 is an example, not a universal production recommendation. The appropriate limit depends on request duration, memory usage, application workload, and available infrastructure.
For example, an API that performs quick database lookups may tolerate more concurrent streams than an endpoint that generates large reports or performs CPU-intensive document processing.
A lower limit can reduce resource pressure, but setting it too low may unnecessarily restrict legitimate clients. Measure the behavior of the application under realistic workloads before deciding on a production value.
Protect the Server With Session Memory Limits
HTTP/2 sessions maintain internal state for streams, headers, queued data, and protocol frames. These resources consume memory even when application code is not actively processing a request.
Node.js provides the maxSessionMemory option to limit the memory budget associated with an HTTP/2 session.
For example:
const server = createSecureServer(
{
key: readFileSync('./server-key.pem'),
cert: readFileSync('./server-cert.pem'),
maxSessionMemory: 10,
settings: {
maxConcurrentStreams: 100
}
}
);
The maxSessionMemory value is expressed in megabytes. Its default is 10 MB.
This is a credit-based limit rather than a strict measurement of every byte allocated by the process. It accounts for resources such as open streams, header compression tables, queued outbound data, retained inbound data, and unacknowledged protocol frames.
When the limit is exceeded, Node.js applies backpressure by stopping reads from the socket until the application consumes queued data. New streams may be rejected while the session remains above the limit.
This helps control resource consumption, but it does not replace operating-system memory limits or application-level workload controls. A server with thousands of sessions can still consume substantial total memory even when each session has an individual limit.
Configure Header and Invalid Frame Limits
HTTP/2 headers can also consume resources, particularly when clients send large or excessive header collections.
Node.js provides options such as maxHeaderListPairs and maxSessionInvalidFrames to help control certain forms of protocol input.
For example:
const server = createSecureServer(
{
key: readFileSync('./server-key.pem'),
cert: readFileSync('./server-cert.pem'),
maxSessionMemory: 10,
maxHeaderListPairs: 64,
maxSessionInvalidFrames: 100,
settings: {
maxConcurrentStreams: 100
}
}
);
maxHeaderListPairs controls the maximum number of header entries accepted. It should be selected based on the application's legitimate request requirements.
maxSessionInvalidFrames controls how many invalid frames a session will tolerate before it is closed. The default is 1,000.
These settings should not be reduced arbitrarily. Some applications legitimately require more headers because of authentication metadata, tracing information, or gateway-generated request context.
The goal is to reject unreasonable input without breaking normal clients.
Build a More Resilient HTTP/2 Server
The following example combines the main techniques into one server implementation. It handles server, session, and stream errors separately while applying basic resource limits.
import {
createSecureServer
} from 'node:http2';
import {
readFileSync
} from 'node:fs';
const server = createSecureServer({
key: readFileSync('./server-key.pem'),
cert: readFileSync('./server-cert.pem'),
maxSessionMemory: 10,
maxHeaderListPairs: 64,
maxSessionInvalidFrames: 100,
settings: {
maxConcurrentStreams: 100
}
});
server.on('error', (error) => {
console.error('Server error:', {
code: error.code,
message: error.message
});
});
server.on('sessionError', (error, session) => {
console.error('Session error:', {
code: error.code,
destroyed: session.destroyed
});
});
server.on('session', (session) => {
session.on('close', () => {
console.log('Session closed');
});
session.on('goaway', (errorCode, lastStreamID) => {
console.log('GOAWAY received:', {
errorCode,
lastStreamID
});
});
});
server.on('stream', (stream, headers) => {
stream.on('error', (error) => {
console.error('Stream error:', {
streamId: stream.id,
code: error.code
});
});
stream.on('close', () => {
console.log('Stream closed:', stream.id);
});
const path = headers[':path'];
try {
stream.respond({
':status': 200,
'content-type': 'application/json'
});
stream.end(JSON.stringify({
message: 'Request processed successfully',
path
}));
} catch (error) {
console.error('Request processing failed:', error.message);
if (!stream.destroyed) {
stream.close();
}
}
});
server.listen(8443, () => {
console.log('HTTP/2 server listening on port 8443');
});
This implementation provides a foundation for handling HTTP/2 failures, but it is not a complete production server. Real applications must also handle asynchronous exceptions inside request handlers, validate incoming headers and payloads, enforce authentication and authorization, and manage graceful shutdown.
The most important architectural decision is that a failure in one request should not unnecessarily affect other requests or the entire server process.
Test Client Disconnects and Protocol Errors
A server that works with normal browser requests is not necessarily resilient to unexpected client behavior. HTTP/2 error handling should be tested deliberately.
One useful test is to create an HTTP/2 client, open a request, and cancel the stream before the server completes its response.
For example:
import { connect } from 'node:http2';
const client = connect('https://localhost:8443', {
rejectUnauthorized: false
});
client.on('error', (error) => {
console.error('Client session error:', error.message);
});
const request = client.request({
':path': '/large-report',
':method': 'GET'
});
request.on('error', (error) => {
console.error('Client stream error:', error.message);
});
request.on('response', (headers) => {
console.log('Response status:', headers[':status']);
});
request.end();
setTimeout(() => {
request.close();
client.close();
}, 100);
The rejectUnauthorized: false option is shown only to simplify testing with a self-signed local certificate. Do not use it in production because it disables normal certificate verification.
When the client closes the request, the server should release the resources associated with that stream. Other requests using the same session should continue to work.
Additional tests should cover clients that disconnect during request-body transmission, malformed requests, excessive headers, and repeated connection attempts. Run these tests while monitoring process memory, CPU usage, active sessions, and error rates.
A successful test is not simply one in which the server does not crash. It should also demonstrate that resources are released, other clients continue receiving responses, and the server remains responsive under repeated failures.
Common Mistakes in HTTP/2 Error Handling
One common mistake is attaching an error listener only to the HTTP/2 server. Server, session, and stream objects have separate event lifecycles. An error listener on one object does not automatically handle an unhandled error emitted by another object.
Another mistake is treating every stream cancellation as a server failure. Clients regularly cancel requests because users navigate away, browsers abandon unnecessary downloads, or upstream services enforce their own timeouts. These events should be handled as part of normal request lifecycle management.
Developers also sometimes catch synchronous exceptions but forget asynchronous operations. An HTTP/2 request handler may call a database, an external API, or a file-processing service. Errors from those operations must be handled with try/catch around awaited operations or an equivalent rejection-handling strategy.
Finally, developers may focus on error listeners while ignoring resource limits. A server can remain alive and still become unavailable because too many sessions, streams, or expensive operations consume its resources. Error handling, flow control, concurrency limits, and infrastructure-level protections must work together.
Best Practices for Production HTTP/2 Servers
Use the appropriate error listeners on the HTTP/2 server, session, and stream objects. Attach stream listeners immediately when a stream is created, and make sure asynchronous request-processing code handles rejected promises.
Set realistic limits for concurrent streams, session memory, and header processing. Review these values using actual application traffic rather than selecting them arbitrarily.
Monitor session creation and closure, stream failures, request cancellations, memory consumption, and connection counts. Repeated protocol errors from the same source may indicate a misbehaving client or an attack and should be investigated.
Finally, keep Node.js updated and place additional protections at the infrastructure layer. Reverse proxies, load balancers, connection limits, request timeouts, and container resource limits can help protect the application from traffic patterns that exceed what the Node.js process should handle alone.
Summary
HTTP/2 allows multiple requests to share a single connection, but this also means that errors can occur at different levels of the communication lifecycle. A client disconnecting or sending invalid data should not automatically bring down the entire Node.js server.
The most important protection is to handle errors at the correct level. Register listeners for server errors, use the sessionError event for session failures, and attach error handlers to individual streams. Combine this with limits on concurrent streams, session memory, and header processing to control resource consumption.
A resilient HTTP/2 server does not need to prevent every client error. It needs to handle those errors without allowing one failed request or connection to interrupt unrelated users. That is the difference between an HTTP/2 application that works under normal conditions and one that remains reliable when clients behave unexpectedly.
Join the conversation! Your thoughts help the community grow.