How to Reduce TTFB (Time to First Byte): 2026 Speed Guide
How to reduce TTFB: separate server time from network time, then fix caching, database queries, redirects and CDN settings, with a target for each step.
Kazi Khalid Hasan Tamim · BugViso Team
15 min read
To reduce TTFB (Time to First Byte), cache HTML at the CDN, speed up database queries and server rendering, use HTTP/2 or HTTP/3 and remove redirects.
TTFB is the time from the browser's request to the first byte of the response, and Google treats 800 ms or less as good. This guide breaks it into phases and shows a fix for each, as part of Core Web Vitals explained.
How to Reduce TTFB: The 5 Micro-Phases of Server Latency
Time to First Byte (TTFB) is a foundational performance metric. It measures the time between the browser starting a navigation request and receiving the first byte of response data from the server.
| Rating | TTFB | Color |
|---|---|---|
| Good (passing) | 800 ms or less (optimal: under 200-300 ms) | Green |
| Needs improvement | Above 800 ms, up to 1800 ms | Amber |
| Poor | Above 1800 ms | Red |
TTFB is evaluated at the 75th percentile of all user navigation requests.
According to the official web.dev TTFB documentation, a good TTFB is 800 milliseconds or less at the 75th percentile of real-world visits. For static content and edge-cached assets, top-tier engineering teams aim for a TTFB below 200 milliseconds, reserving the 800ms ceiling for complex dynamic Server-Side Rendered (SSR) pages.
For SSR pages that can't get there from a single origin, edge SSR and streaming HTML covers rendering at the CDN edge and flushing HTML early.
Platform walkthroughs: Core Web Vitals on WordPress (caching plugins and hosting) and how to speed up a Shopify store.
- REDIRECT & DNS LOOKUP:
- Resolving domain name to IP address (e.g., 20ms - 120ms).
- TCP CONNECTION & TLS HANDSHAKE:
- Establishing socket connection and negotiating TLS encryption
- (e.g., 1-RTT to 2-RTT; 30ms - 250ms).
- REQUEST DISPATCH & NETWORK TRANSIT:
- HTTP request packet travels across physical fiber/cellular links
- from client device to origin server or Edge PoP.
- SERVER PROCESSING & APPLICATION RUNTIME:
- Server authenticates session, runs backend application logic,
- executes database queries, renders HTML template (50ms - 1200ms+).
- FIRST BYTE RESPONSE TRANSMISSION:
- The server emits the first packet of the HTTP response header and
- body back across the network to the browser.
- TOTAL TTFB = DNS + TLS + TCP + Request Transit + Server Work + 1st Byte
Programmatically Inspecting TTFB via Navigation Timing
Modern browsers expose precise timestamp breakdowns via the W3C Navigation Timing Level 2 specification:
const [navEntry] = performance.getEntriesByType('navigation');
if (navEntry) {
const dnsTime = navEntry.domainLookupEnd - navEntry.domainLookupStart;
const tcpTime = navEntry.connectEnd - navEntry.connectStart;
const tlsTime = navEntry.secureConnectionStart > 0 ? (navEntry.connectEnd - navEntry.secureConnectionStart) : 0;
const requestDuration = navEntry.responseStart - navEntry.requestStart;
const totalTTFB = navEntry.responseStart - navEntry.startTime;
console.table({
'1. DNS Lookup': `${dnsTime.toFixed(1)} ms`,
'2. TCP Handshake': `${(tcpTime - tlsTime).toFixed(1)} ms`,
'3. TLS Negotiation': `${tlsTime.toFixed(1)} ms`,
'4. Server Processing (Request -> ResponseStart)': `${requestDuration.toFixed(1)} ms`,
'TOTAL TTFB (Navigation Start -> First Byte)': `${totalTTFB.toFixed(1)} ms`,
});
}The Cascading Bottleneck: Why TTFB Dictates Largest Contentful Paint (LCP)
TTFB does not exist in isolation. It sets a hard baseline for every downstream loading metric, including First Contentful Paint (FCP) and Largest Contentful Paint (LCP).
- CASE A: Slow Origin Server (TTFB = 1400ms)
- 0ms ========================= 1400ms ==== 1800ms ========= 3200ms
- TTFB Silence (1400ms) HTML CSS/Fonts LCP Hero Paint
- Result: LCP = 3.2s (POOR / FAILS CORE WEB VITALS)
- CASE B: Edge Cached Origin (TTFB = 120ms)
- 0ms == 120ms ==== 500ms ================= 1400ms
- TTFB HTML CSS/Fonts LCP Hero Image Rendered
- Result: LCP = 1.4s (GOOD / PASSES CORE WEB VITALS WITH 44% BUFFER)
The browser's streaming HTML parser cannot discover critical render-blocking resources, preloaded typography, or above-the-fold hero images until the first chunk of the HTML document arrives.
$$\text{LCP} \ge \text{TTFB} + \text{HTML Download} + \text{Resource Discovery} + \text{Asset Download} + \text{Render Execution}$$
If your TTFB is 1.2 seconds, your LCP has only 1.3 seconds remaining to download stylesheets, execute JavaScript, parse the hero image, and paint pixels before exceeding Google's 2.5-second threshold.
For a deeper look at LCP mechanics, read our companion guide on how to improve Largest Contentful Paint (LCP).
Fix 1: Edge Caching and Content Delivery Network (CDN) Architecture
The single most impactful strategy to reduce TTFB for global users is moving response generation geographically closer to the user via a global Content Delivery Network (CDN) Edge Point of Presence (PoP).
- CENTRALIZED ORIGIN ARCHITECTURE (High TTFB for Global Users):
- User (London) ---- Physical Transatlantic Fiber: 140ms RTT → Server (Virginia)
- Server executes database queries (250ms)
- Response travels back (140ms)
- Total TTFB: 530ms+
- EDGE CACHING ARCHITECTURE (Sub-50ms TTFB Globally):
- User (London) ---- Local Edge Node (London PoP): 8ms RTT →
- Edge PoP returns cached HTML immediately (12ms)
- Total TTFB: 20ms
Implementing Modern Edge Caching with Cache-Control
To allow CDN edge nodes to cache dynamic HTML responses while keeping user data secure, configure the HTTP Cache-Control header using s-maxage, stale-while-revalidate, and stale-if-error.
HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8
/* Instruct browser to revalidate, but instruct CDN Edge to cache for 1 hour */
Cache-Control: public, max-age=0, s-maxage=3600, stale-while-revalidate=86400, stale-if-error=604800
Surrogate-Key: blog-post-19 page-marketing| Directive | Technical function |
|---|---|
public | Allows intermediate proxies and CDNs to store the response |
max-age=0 | Forces the client browser to revalidate on reload |
s-maxage=3600 | CDN edge serves a cached copy for 1 hour |
stale-while-revalidate | Edge serves a stale copy instantly while fetching a fresh response in the background |
stale-if-error | Edge serves a stale copy if the origin crashes |
Edge Middleware and Targeted HTML Invalidation
Modern edge platforms (such as Cloudflare Workers, Fastly Compute and Vercel Edge Middleware) can run lightweight routing, authentication checks and geolocation targeting directly on the Edge PoP. They forward only uncached requests to the central origin server.
Fix 2: Origin Server Caching and Reverse Proxies
When a request must reach the origin server, application code should never regenerate identical HTML strings or re-run expensive database queries from scratch.
- An incoming HTTP request reaches the Nginx / FastCGI / Varnish reverse proxy.
- Hit: returns the full-page HTML straight from the cache.
- Miss: forwards the request to the application runtime (FastAPI / Node.js / PHP).
- The application checks the Redis in-memory key-value store.
- Hit: returns the serialized query payload from memory.
- Miss: falls through to the primary PostgreSQL / MySQL database and executes an indexed query on disk.
Implementing In-Memory Application Caching (Redis)
Cache serialized database queries, rendered template partials, and API responses in an in-memory Redis cluster to avoid hitting disk storage on recurring visits:
import json
import redis.asyncio as redis
from fastapi import FastAPI, Request, Response
app = FastAPI()
redis_client = redis.from_url("redis://localhost:6379/0", decode_responses=True)
@app.get("/api/v1/articles/{slug}")
async def get_article_endpoint(slug: str):
cache_key = f"article:rendered:{slug}"
# 1. Attempt retrieval from ultra-fast in-memory cache
cached_payload = await redis_client.get(cache_key)
if cached_payload:
return Response(content=cached_payload, media_type="application/json", headers={"X-Cache": "HIT"})
# 2. Cache Miss: Execute database query
article_data = await fetch_article_from_database(slug)
# 3. Store in Redis with 1-hour TTL (Time To Live)
serialized = json.dumps(article_data)
await redis_client.setex(cache_key, 3600, serialized)
return Response(content=serialized, media_type="application/json", headers={"X-Cache": "MISS"})Nginx Full-Page Microcaching Configuration
For high-traffic dynamic applications, microcaching full HTML pages in Nginx RAM for just 10 seconds can absorb massive traffic spikes without sacrificing content freshness:
# Nginx FastCGI / Proxy Cache Configuration
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=PAGE_CACHE:100m inactive=60m max_size=1g;
proxy_cache_key "$scheme$request_method$host$request_uri";
server {
listen 443 ssl http2;
server_name example.com;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_cache PAGE_CACHE;
proxy_cache_valid 200 301 302 10s; # Microcache dynamic pages for 10s
proxy_cache_use_stale error timeout updating http_500 http_502 http_503;
# Add diagnostic cache header
add_header X-Cache-Status $upstream_cache_status;
}
}Fix 3: Database Query Optimization and Connection Pooling
Un-optimized database queries and serverless database connection handshakes are the leading cause of origin-level TTFB spikes.
| Configuration | Effect on query time and origin TTFB |
|---|---|
| Full table scan (unindexed) | Slowest queries; poor origin TTFB |
| B-tree indexed query | Fast queries; good origin TTFB |
| Direct connection (no pool) | Pays a connection handshake on each request |
| Connection pool (PgBouncer) | Avoids the handshake; lowest origin TTFB |
1. Eliminating Sequential N+1 Database Queries
An N+1 query problem occurs when an application executes one query to fetch a list of items, followed by $N$ individual queries to fetch related metadata. Replace sequential queries with eager joins or batch lookups.
-- BAD: 1 query for posts + 50 individual queries for author metadata (Total: 450ms)
SELECT * FROM posts WHERE status = 'published' LIMIT 50;
-- Executes 50 times: SELECT * FROM authors WHERE id = ?;
-- GOOD: Single relational JOIN executed in 8ms
SELECT p.id, p.title, p.slug, p.published_at, a.name AS author_name, a.avatar_url
FROM posts p
INNER JOIN authors a ON p.author_id = a.id
WHERE p.status = 'published'
ORDER BY p.published_at DESC
LIMIT 50;2. Implementing Serverless Connection Pooling
In serverless architectures (such as AWS Lambda, Vercel Serverless Functions, or Google Cloud Run), every function invocation can attempt to open a brand-new TCP and TLS connection to your PostgreSQL database.
Creating a new database connection adds CPU and networking overhead to every cold request.
Deploy an intermediate connection pooler (such as PgBouncer or the Supabase Connection Pooler) to maintain a warm pool of reusable connections, reducing database connection latency to under 1 millisecond.
Fix 4: Modern Network Transport Protocols (HTTP/3, QUIC, TLS 1.3)
Network negotiation overhead can add hundreds of milliseconds to TTFB before the server even receives the HTTP request header.
- TLS 1.2 (2 Round Trips Required Before Request):
- Client --- ClientHello → Server
- Client → ServerHello, Certificate --- Server
- Client --- Key Exchange, Cipher Spec → Server
- Client → Finished --- Server
- Client --- HTTP GET Request → Server (TTFB begins at RTT #3)
- TLS 1.3 (1 Round Trip / 0-RTT Resumption):
- Client --- ClientHello + Key Share → Server
- Client → ServerHello + Encrypted Extensions --- Server
- Client --- HTTP GET Request → Server (TTFB begins at RTT #2)
Upgrading to HTTP/3 and QUIC
HTTP/3 runs over QUIC (UDP) rather than traditional TCP. QUIC merges the transport handshake and cryptographic handshake into a single exchange, enabling connection establishment in 0-RTT to 1-RTT.
HTTP/3 also eliminates TCP Head-of-Line blocking. If a single packet is lost on a cellular connection, only the stream tied to that packet is delayed, so the rest of the HTML byte stream progresses unhindered.
Utilizing 103 Early Hints
The 103 Early Hints status code lets the server send an informational response with Link preload headers to the browser while the origin server is still busy rendering dynamic HTML in the background.
HTTP/1.1 103 Early Hints
Link: </assets/style.css>; rel=preload; as=style
Link: </fonts/outfit.woff2>; rel=preload; as=font; crossorigin
/* Server continues rendering SSR HTML for 200ms... */
HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8
<!DOCTYPE html>
<html>
...While the backend processes database queries, the client browser immediately initiates TLS handshakes and starts downloading critical stylesheets, effectively neutralizing server processing latency.
Fix 5: Server-Side HTML Streaming
Traditional Server-Side Rendering (SSR) buffers the entire HTML page in server memory until the closing </html> tag is rendered. Only then does it emit byte 1 to the network socket.
- TRADITIONAL BUFFERED SSR (High TTFB):
- Server executes Slow Database Query: 600ms
- Server Renders Full HTML String: 100ms
- Emits Byte 1 at 700ms Mark →
- MODERN STREAMED SSR (Near-Zero TTFB):
- Server Renders
<head>and Shell: 15ms - Emits Byte 1 (
<head>) at 15ms Mark → Browser starts CSS/Fonts - Server executes Slow Database Query: 600ms
- Streams Body Content as ReadableStream chunks
Using modern streaming architectures (such as React 18 Suspense, Next.js App Router, or Node.js ReadableStream), the server emits the document <head> and layout shell in under 20 milliseconds.
The browser parses the <head>, downloads CSS, and prepares typography while the server resolves slower backend data dependencies in parallel, streaming the remaining HTML chunks over the open connection.
How BugViso Audits TTFB and Server Responsiveness Automatically
Manual spot-checking with developer tools cannot reveal how server responsiveness fluctuates across hundreds of parameterized routes, geographical locations, and mobile network conditions.
- The target domain is submitted to a headless Chromium multi-page crawl engine.
- Four engines run:
- Performance and Core Web Vitals engine: captures TTFB via the Navigation Timing Level 2 API and measures desktop vs mobile latency.
- Speed and performance simulation engine: emulates Slow 3G (400ms RTT) and Fast 3G (150ms RTT), and calculates LCP regression against the TTFB baseline.
- Security and TLS certificate inspector: validates the TLS protocol version (TLS 1.2 / 1.3) and audits handshake latency and cipher overhead.
- Multi-page deep route crawler: audits TTFB across sitemaps, categories and archives, and surfaces slow database-heavy dynamic subpages.
- The output is a prioritized remediation playbook plus a branded PDF executive report.
When you run an automated website scan with BugViso, the backend auditing worker performs a deep-dive analysis of server responsiveness:
- High-Precision TTFB Measurement: Uses the Navigation Timing Level 2 API to capture exact server response timings (
responseStart - requestStart) across both desktop and mobile device passes. - Multi-Page Site-Wide Crawling: Rather than scanning only a fast, cached homepage, BugViso crawls your sitemap and discovered rendered links, benchmarking TTFB across database-heavy deep routes, blog archives, and product catalogs.
- Speed & Performance Simulation: Re-loads pages under CDP-throttled network profiles (Slow 3G and Fast 3G), modeling how server response latency cascades into failing LCP times on real-world mobile connections.
- TLS and Protocol Inspection: Analyzes live SSL/TLS certificates, validating protocol negotiation (flagging legacy TLS 1.0/1.1 protocols) and inspecting certificate expiration dates.
- Prioritized Remediation Playbook: Surfaces slow endpoints directly in your remediation playbook, pairing detected TTFB bottlenecks with concrete engineering fix actions.
You can see every rule BugViso applies in its Core Web Vitals checker.
Common Mistakes When Attempting to Reduce TTFB
Avoid these frequent architectural traps when optimizing server response times:
| Common Mistake | Consequence |
|---|---|
| Assuming CDN Caches by Default Missing headers leave HTML uncached | |
| Serverless Connection Churn Database handshakes add latency to every cold invocation | |
| Testing Only Cached URLs Misses slow dynamic query parameters | |
| Client-Side Fetch Band-Aids Moves server latency to client waterfall |
1. Assuming a CDN Automatically Caches Dynamic HTML
Simply pointing your DNS to a CDN provider does not automatically cache HTML pages. By default, most CDNs treat HTML as dynamic and forward every request directly to the origin server unless explicit Cache-Control headers or custom Edge Page Rules are configured.
2. Shifting Server Work to Client-Side Fetching
Some engineering teams try to fix high TTFB by serving an empty HTML shell and fetching all page data client-side via JavaScript fetch() calls. While this artificially lowers document TTFB, it pushes the data fetching waterfall into the browser, delaying LCP and hurting SEO crawlability.
Frameworks with parallel server loaders avoid that trade-off; our Remix SEO guide measures the loader waterfall and its effect on TTFB.
3. Ignoring Query Parameter Cache Splitting
If marketing campaigns append tracking parameters (?utm_source=newsletter&utm_campaign=summer), standard CDN caches may treat every unique URL as an independent cache miss, bypassing edge caching and overloading origin servers during major marketing pushes. Configure your CDN to strip non-functional query parameters from the cache key.
Frequently Asked Questions About Time to First Byte
These answers cover what readers ask most about TTFB.
What is a good Time to First Byte (TTFB) score?
According to Google's Core Web Vitals guidelines, a good TTFB is 800 milliseconds or less. Static pages and edge-cached content can respond much faster than dynamic pages. Any TTFB above 1,800ms is classified as "Poor."
Does TTFB directly affect Google search rankings?
Yes. TTFB is a foundational component of Google's Page Experience ranking signals.
Because slow TTFB directly delays Largest Contentful Paint (LCP) and First Contentful Paint (FCP), an un-optimized server response time directly prevents sites from passing the Core Web Vitals assessment.
What is the difference between TTFB and FCP?
Time to First Byte (TTFB) measures the time until the browser receives the very first byte of the HTML document from the server.
First Contentful Paint (FCP) measures the time until the browser renders the first visual DOM element (such as text, a navigation bar, or a canvas element) to the screen. FCP always occurs after TTFB.
Why is TTFB significantly higher on the first page visit than on repeat visits?
The initial navigation to a website requires performing DNS resolution, TCP handshakes, and TLS negotiation from a cold state.
On repeat visits, the browser reuses existing TCP/TLS connections, uses DNS caches, and reads cached assets directly from disk or service worker storage.
How do 103 Early Hints impact TTFB?
When a server responds with an HTTP 103 Early Hints status code, modern browser performance APIs record the arrival of the Early Hints headers as the initial response start time (responseStart). That effectively lowers the recorded TTFB while allowing the browser to preload critical resources immediately.
Summary and Action Plan
Reducing Time to First Byte requires an integrated infrastructure approach. Five moves cover it:
- Deploy edge caching with modern
Cache-Controldirectives. - Optimize database queries and implement connection pooling.
- Use in-memory Redis caching.
- Upgrade transport protocols to TLS 1.3 and HTTP/3.
- Adopt server-side HTML streaming.
Maintaining low server response times across dynamic routes requires continuous automated testing. Running an automated BugViso site scan measures server response time on every crawled route.
Written by
Kazi Khalid Hasan Tamim · BugViso Team
Kazi writes BugViso’s guides on website audits, Core Web Vitals, technical SEO, accessibility and AI search. The data in them comes from audits BugViso runs in a real Chromium browser, including our 219-site study of website health.
Summarise with AI
Open this guide in your assistant.
Follow BugViso
New guides and audit data as we publish them.
AI visibility tracker
Is your brand in AI answers?
See how often AI assistants mention you, cite your site and rank you against your competitors.
- ChatGPT
- Gemini
- Perplexity
- Claude
- AI Overviews
See where your site stands
Run a free BugViso audit for SEO, speed, accessibility and AI search readiness — with fixes you can ship today.