Optimizing TTFB: from 1.2 s to 150 ms in a week
Recently, an e-commerce store owner approached us with a complaint about slow loading — TTFB was 1.2 seconds on the homepage. After a comprehensive audit, we implemented full page cache, configured Nginx FastCGI cache, optimized database queries, and connected Redis. Result: TTFB dropped to 150 ms, LCP improved by 40%, and conversion increased by 12%. In this article, we break down exactly which steps led to this effect.
TTFB (Time to First Byte) is the time from sending a request to receiving the first byte of the response. It consists of DNS resolution, connection setup (TCP+TLS), request transmission, server processing, and response generation. The most manageable part is server processing. That's exactly what we optimize. According to Google's Web Vitals documentation, TTFB directly affects LCP and INP.
Why TTFB is critical for Core Web Vitals?
Google uses TTFB as a measure of first response. If the server takes longer than 600 ms, even perfect frontend won't save LCP. We've seen this on dozens of projects: reducing TTFB from 1 s to 200 ms improved LCP by 40%. Additionally, a slow server delays processing of user requests, worsening INP (Interaction to Next Paint).
How to diagnose TTFB using Chrome DevTools and WebPageTest?
- Chrome DevTools (Network tab): measure Waiting (TTFB) for each request. Filter by document type.
- WebPageTest: provides a detailed waterfall showing DNS, TCP, TLS, first byte. Indicates how long the server took.
- Lighthouse: overall assessment with recommendations.
- RUM solutions (Yandex.Metrica, Google Analytics): show real TTFB values for users.
We always start with RUM data to get an objective picture.
Caching — the main tool
Full Page Cache at the application level
The most effective way is to cache ready HTML for all unauthenticated users. Here's a middleware for Laravel:
class FullPageCache
{
private const TTL = 300; // 5 minutes
public function handle(Request $request, Closure $next): Response
{
if (!$this->isCacheable($request)) {
return $next($request);
}
$key = $this->cacheKey($request);
if (Cache::has($key)) {
return response(Cache::get($key))
->header('X-Cache', 'HIT')
->header('Content-Type', 'text/html; charset=UTF-8');
}
$response = $next($request);
if ($response->getStatusCode() === 200) {
Cache::put($key, $response->getContent(), self::TTL);
}
return $response->header('X-Cache', 'MISS');
}
private function isCacheable(Request $request): bool
{
return $request->isMethod('GET')
&& !auth()->check()
&& !$request->hasCookie(session()->getName());
}
private function cacheKey(Request $request): string
{
return 'fpc:' . sha1($request->fullUrl());
}
}
This approach gives TTFB < 50 ms for cached pages. The key is to properly configure invalidation when content changes. We use events (Model events) to clear the cache of corresponding URLs.
Nginx FastCGI Cache — faster than PHP+Redis
Cache at the nginx level works before PHP generation, which gives an additional 10-20 ms gain:
fastcgi_cache_path /var/cache/nginx/fcgi
levels=1:2
keys_zone=LARAVEL:10m
inactive=60m
max_size=1g;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
server {
location ~ \.php$ {
fastcgi_cache LARAVEL;
fastcgi_cache_valid 200 5m;
fastcgi_cache_valid 404 1m;
fastcgi_cache_bypass $cookie_laravel_session $http_authorization;
fastcgi_no_cache $cookie_laravel_session $http_authorization;
add_header X-Fastcgi-Cache $upstream_cache_status;
fastcgi_pass unix:/run/php/php8.2-fpm.sock;
}
}
For invalidation we use the ngx_cache_purge module — send a PURGE request to the URL.
Database query optimization
Slow queries are the second most common cause of high TTFB. A typical mistake is the N+1 problem:
// Slow
$products = Product::all();
foreach ($products as $product) {
echo $product->category->name;
}
// Fast
$products = Product::with(['category', 'images', 'brand'])->get();
We profile all queries via DB::listen and log those that take longer than 100 ms. We add indexes, replace nested loops with single queries using JOINs.
Redis for data caching
Cache results of frequent queries — category tree, top products, counters:
$categories = Cache::remember('categories:tree', 3600, function () {
return Category::with('children')->whereNull('parent_id')->orderBy('sort_order')->get();
});
$stats = Cache::remember('product:stats:' . $productId, 300, function () use ($productId) {
return [
'views' => ProductView::where('product_id', $productId)->count(),
'sales' => OrderItem::where('product_id', $productId)->sum('quantity'),
'wishlist' => WishlistItem::where('product_id', $productId)->count(),
];
});
Other optimizations
DNS and network
Use <link rel="preconnect"> for third-party resources to reduce DNS+TCP time. Enable CDN (Cloudflare, Vercel) — they reduce latency through geographically distributed servers.
OPcache for PHP
Production settings:
opcache.enable=1
opcache.memory_consumption=256
opcache.max_accelerated_files=20000
opcache.validate_timestamps=0
opcache.jit=tracing
opcache.jit_buffer_size=64M
JIT compilation speeds up PHP script execution by 20-50%, directly reducing TTFB.
Comparison of caching methods
| Method | TTFB (typical) | Implementation complexity | Invalidation |
|---|---|---|---|
| Full Page Cache (PHP) | < 50 ms | Medium | By events |
| Nginx FastCGI Cache | < 30 ms | Medium | PURGE request |
| Redis data cache | 1-5 ms (per query) | Low | TTL or keys |
| CDN + static | 10-50 ms (on origin) | Low | By URL |
What's included in our work
- Audit — measure TTFB on all page types, analyze caching structure, profile database.
- Design — choose caching strategy for the specific stack.
- Implementation — deploy full page cache, nginx cache, optimize queries, set up Redis.
- Testing — A/B tests before/after, verify correct invalidation.
- Documentation — caching scheme for the development team.
- Audit after six months — monitor degradation.
Approximate timeline
- Diagnostics and quick wins (OPcache, indexes): 1-2 days.
- Full page cache + Nginx cache: 2-3 days.
- Deep DB optimization and Redis: 3-5 days.
- CDN and fine tuning: 1-2 days.
Final timeline — from 2 business days to 2 weeks depending on complexity.
Target TTFB values by page type
| Page type | With cache | Without cache |
|---|---|---|
| Homepage | < 50 ms | < 300 ms |
| Catalog | < 50 ms | < 400 ms |
| Product page | < 50 ms | < 200 ms |
| API endpoints | — | < 100 ms |
We guarantee reducing TTFB to 500 ms on all pages and improving LCP by 30-50%. Clients save up to 40% on hosting due to caching, and optimization investments pay back in 3-6 months. Contact us for a free audit of your site. Get a consultation on TTFB optimization — we'll analyze your project and suggest specific steps.







