How to Reduce Time to First Byte
Cut time to first byte: remove origin work before the first byte, stream the response, and use caching and connection reuse in front of the server.
On this page
Introduction
Time to first byte is the delay between a client sending a request and receiving the first byte of the response. It is the floor under every later metric: a page cannot start rendering until the first byte arrives, and an API client cannot begin parsing until the body starts. A large TTFB almost always means the server is waiting for something before it can respond, and the fix is to find that wait and shorten or move it.
This tutorial breaks TTFB into its phases, shows how to start the response sooner by streaming and avoiding whole-body buffering, how caching and connection reuse remove upstream stalls, and how to test a first-byte budget. The examples use a Node.js server, but the reasoning is universal.
Measure the phases before optimising
TTFB is the sum of several phases: the client’s network round trip to reach the server, any time queued at a load balancer, connection and TLS setup if the connection is new, and the server’s application time until it emits the first byte. Measure each separately, because optimising the wrong phase wastes effort: a fast application behind a queue is still slow, and a fast network in front of a slow database is still slow.
Instrument the server to record the time from request receipt to first byte written, and compare it to the total TTFB the client sees. The difference is the network and queueing, which you fix with caching, connection reuse, and placement. The server-side time is what you fix with the application. This split tells you which set of changes to make.
function firstByteTimer(server) {
server.on('request', (req) => { req.start = process.hrtime.bigint(); });
server.prependListener('response', (res) => {
res.once('finish', () => {});
const origWrite = res.write.bind(res);
res.write = (chunk, ...rest) => {
if (!res._ttfbLogged) {
res._ttfbLogged = true;
const ms = Number(process.hrtime.bigint() - res.req.start) / 1e6;
metrics.observe('server.ttfb_ms', ms); // time to first byte, server side
}
return origWrite(chunk, ...rest);
};
});
}
Start the response before the body is ready
A server that computes the whole body before writing anything cannot send the first byte until the last computation finishes. Send the headers and the first chunk as soon as they are available, and stream the rest. For a template-rendered page, write the head and a loading state early, then the content. For an API, stream the first records while the query is still producing rows.
Avoid compression that buffers the whole response before sending. A one-shot gzip of the entire body delays the first byte until the body is complete; a streaming compressor emits compressed chunks as input arrives, so the first byte goes out sooner. Similarly, avoid a middleware chain that accumulates the full response; send early and stream the remainder.
import { createServer } from 'node:http';
createServer(async (req, res) => {
// start the response with headers and a shell before the slow work completes
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
res.write('<!doctype html><p>Loading…</p>'); // first byte out early
const data = await loadSlowData(); // the slow part happens after
res.write('<div>' + render(data) + '</div>');
res.end();
}).listen(3000);
Remove upstream stalls with cache and reuse
If the first byte is delayed by the request never reaching the server promptly, the fix is in front of the server. A cache can answer without the origin at all, so the first byte comes from an edge close to the client. Connection reuse means the client does not pay a TCP and TLS handshake per request, so the first byte arrives sooner on the second and later requests.
Keep the server close to the users, or serve from an edge. A server an ocean away adds a network round trip that no application change can remove. Combine placement with caching so most requests are answered nearby and only cache misses pay the distance. For a dynamic response that cannot be cached whole, cache the parts that can be, such as a shared layout or reference data, so the application starts with less work.
// an edge or reverse proxy answers cacheable requests; the origin streams the rest
res.setHeader('Cache-Control', 'public, max-age=30, stale-while-revalidate=60');
// a cache hit returns the first byte from the edge, not the origin
Cut the application wait in front of the first byte
Within the application, the first byte is delayed by whatever runs before the response starts. A synchronous database call, a cache miss, a downstream fetch, or an authentication lookup all sit in that path. Move work that is not needed for the first byte to after it: render a shell first, then load the slow data. Warm the caches that gate the response, and resolve the session from a fast store rather than a slow one.
Parallelize what you can. If the response needs two independent lookups, start both at once rather than sequentially. If a downstream is slow, set a short timeout and a fallback so the first byte is not held hostage by an unresponsive dependency. The principle is that nothing on the path to the first byte should wait for something that is not required to send it.
// two independent lookups in parallel, not sequentially
const [user, settings] = await Promise.all([loadUser(id), loadSettings(id)]);
res.writeHead(200).end(render(user, settings));
// a sequential version would double the wait before the first byte
Test a first-byte budget
Measure TTFB from a client under load and assert it stays under a budget for the endpoints that matter. Add a test that a response starts streaming before its slow work completes, by asserting bytes arrive before the work finishes. Track server-side time to first byte as a metric and alert on a regression, because a new middleware or a template change can add a wait that moves the metric without failing any functional test.
# client-observed TTFB
curl -s -o /dev/null -w 'ttfb=%{time_starttransfer}s total=%{time_total}s\n' http://localhost:3000/page
# under load, assert ttfb stays under the budget
seq 1 500 | xargs -P 100 -I{} curl -s -o /dev/null -w '%{time_starttransfer}\n' http://localhost:3000/page \
| awk '{s+=$1; n++} END {print "avg ttfb=" s/n}'
Common pitfalls
Buffering the whole response before sending, one-shot compressing the entire body so the first byte waits, doing slow lookups sequentially on the first-byte path, computing a response that a cache could have answered, and never measuring TTFB so a regression is invisible are the recurring mistakes. Streaming the response, parallelising and deferring work, caching and connection reuse, and a TTFB metric and test address them.
Conclusion
Time to first byte is the floor under every later metric. Measure its phases, start the response before the body is ready by streaming, cut the application wait by parallelising and deferring, and remove upstream stalls with caching and connection reuse. Self-check by asserting a first-byte budget under load and that streaming starts before the slow work finishes. Then the client gets its first byte early even when the full body takes longer.
Sources: MDN: Time to first byte (TTFB), MDN: HTTP connection management, web.dev: TTFB and server response time.
FAQ
- What exactly is time to first byte?
- It is the time from the client sending the request to receiving the first byte of the response body. It folds in the network round trip, any queueing, connection setup, and the server's time to begin responding. A large TTFB usually means the server waits for something before it can start, such as a database call.
- Does streaming help TTFB?
- Yes. If the server can send the first part of a response before computing the rest, the client receives bytes sooner. Buffering the whole response, or compressing it in one pass before sending, delays the first byte until everything is ready.
Report a problem with this articleOpens a pre-filled issue on GitHub.