Hosting & Servers

Reducing server response time (TTFB) — a practical guide

Boost your website speed by reducing TTFB. Learn common causes of high TTFB, accurate measurement methods, and practical solutions for caching, database, and PHP optimization.

Hosting & Servers

What is Reducing TTFB and Why Does It Matter?

Time to First Byte (TTFB) is one of the most important server performance metrics. TTFB measures the duration from when a browser sends a request to when it receives the first byte of the response from the server. The lower this number, the faster users see your website content. Reducing TTFB has a direct impact on user experience and search engine rankings.

High TTFB is usually caused by three main factors: incorrect server configuration, slow database, or lack of caching. In this article, we will examine each of these factors and provide practical solutions to address them.

Accurate TTFB Measurement

Before taking any action, you need to measure TTFB correctly. Several tools are available for this purpose:

  • Online tools: GTmetrix, Pingdom Tools, and WebPageTest
  • Command-line tools: The curl command on Linux
  • Browser tools: Chrome DevTools (Network tab)

To measure accurately with curl, use the following command:

curl -o /dev/null -s -w "time_namelookup: %{time_namelookup}\ntime_connect: %{time_connect}\ntime_starttransfer: %{time_starttransfer}\ntime_total: %{total}\n" https://example.com

The output of this command includes various parts of the response time. The time_starttransfer value is your TTFB. A good TTFB for typical websites is under 200 milliseconds, and for heavy websites, under 500 milliseconds.

Common Mistake: Measuring from the Wrong Location

Many people measure TTFB from only one geographic location. If your server is in Iran and users access your site from abroad, their TTFB will be much higher. Always test from multiple locations.

Optimizing PHP to Reduce TTFB

PHP is one of the most common server-side programming languages, and incorrect configuration can significantly increase TTFB.

PHP-FPM Settings

If you are using PHP-FPM, check the following settings in the php-fpm.conf or www.conf file:

pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35
pm.max_requests = 500

Adjust the above values based on your server resources. If pm.max_children is too low, requests will queue up and TTFB will increase. To calculate the appropriate value:

  1. Determine the amount of RAM available for PHP (e.g., 2 GB)
  2. Find the average RAM consumption per PHP process using the command ps aux | grep php (usually 30-50 MB)
  3. Allowed number = Available RAM / Consumption per process

Enable OPcache

OPcache stores compiled PHP code in memory and prevents recompilation on every request. To enable it, add the following lines to php.ini:

opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=10000
opcache.revalidate_freq=60

After applying the changes, restart the PHP-FPM service:

sudo systemctl restart php8.1-fpm

Optimizing the Database to Reduce TTFB

A slow database is one of the main causes of high TTFB. If your site uses MySQL or MariaDB, follow the steps below.

Identifying Slow Queries

Enable the slow query log to see which queries take a long time:

SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 2;
SET GLOBAL slow_query_log_file = '/var/log/mysql/slow-queries.log';

Then check the log file:

sudo tail -f /var/log/mysql/slow-queries.log

Proper Indexing

For large tables, indexing is essential. Example: Suppose you have an orders table with 500,000 records and frequently search by user_id:

CREATE INDEX idx_user_id ON orders(user_id);

To check existing indexes, use the following command:

SHOW INDEX FROM orders;

MySQL Settings

Edit the my.cnf file. For a server with 4 GB of RAM, the following settings are suitable:

[mysqld]
innodb_buffer_pool_size = 2G
innodb_log_file_size = 512M
query_cache_type = 1
query_cache_size = 128M
max_connections = 150

Important note: innodb_buffer_pool_size should be about 50-70% of total RAM. If it is too low, the database will have to constantly read from disk, which increases TTFB.

Caching to Reduce TTFB

Caching is one of the most effective methods for reducing TTFB. By caching, you store ready-made responses and avoid reprocessing.

Browser Caching

By setting HTTP headers, you can force the browser to cache static files. In the .htaccess file (for Apache) or Nginx configuration:

# Apache
<FilesMatch "\.(css|js|jpg|png|gif)$">
Header set Cache-Control "max-age=2592000, public"
</FilesMatch>
# Nginx
location ~* \.(css|js|jpg|png|gif)$ {
    expires 30d;
    add_header Cache-Control "public, immutable";
}

Server-Side Caching with Redis or Memcached

For dynamic websites, using object caching is very effective. WordPress easily utilizes this feature with plugins like Redis Object Cache. Installing Redis:

sudo apt install redis-server php8.1-redis
sudo systemctl enable redis
sudo systemctl start redis

Then, in WordPress settings, activate the Redis Object Cache plugin. This can reduce TTFB by up to 50%.

Full Page Cache

For WordPress sites, plugins like WP Rocket or W3 Total Cache offer full page caching. These plugins store ready HTML versions of pages and serve them to users without involving PHP or the database.

DNS and Network Optimization

TTFB is not limited to the web server. DNS time is also part of TTFB.

Using Fast DNS

Use fast DNS services like Cloudflare DNS (1.1.1.1) or Google DNS (8.8.8.8). If you are using ServerNet's own DNS service, ensure that A and CNAME records are correctly configured.

Enabling HTTP/2 or HTTP/3

HTTP/2 and HTTP/3 improve TTFB by reducing the number of connections and multiplexing requests. To enable in Nginx:

server {
    listen 443 ssl http2;
    # SSL settings
}

Common Mistakes in Reducing TTFB

Here are a few common mistakes to avoid:

  • Focusing on only one factor: Reducing TTFB requires a comprehensive approach. If you only enable caching but the database is slow, you won't achieve the desired result.
  • Overusing caching: Caching everything can cause users to see outdated content. Set appropriate expiration times.
  • Ignoring CDN: If your users are in different regions, using a CDN can dramatically reduce TTFB. ServerNet offers CDN services with domestic nodes, which is very beneficial for Iranian users.
  • Lack of continuous monitoring: TTFB can change with increased traffic or site changes. Measure it periodically.

Summary

Reducing TTFB is a multi-layered process that requires attention to PHP, database, caching, and network. By implementing the solutions provided in this article, you can bring your site's TTFB below 200 milliseconds and provide a better user experience. Remember that every millisecond reduction in TTFB can increase conversion rates and improve your site's ranking in search results.

To get started, first measure your current TTFB, then choose one of the problematic areas and implement the relevant solutions. After each change, measure again to see its impact.

ServerNet Support

ServerNet engineering & editorial team — specialists in infrastructure, networking and web hosting.

Contact
Share:

Comments 0

No comments yet — be the first!

Leave a comment