How to Improve Your Time to First Byte (TTFB)

Abstract image used to represent How to Improve Your Time to First Byte (TTFB)
Image by Frankie Lopez.

In Brief

TTFB is the wait before the first byte of HTML comes back, so the useful checks sit before the browser starts rendering. Look at DNS, redirects, hosting, server resources, cache hits, database work, and application code first. If the origin response is slow, front end changes are usually the wrong place to begin.

In a previous post I've talked about just how crucial having a low Time To First Byte (or TTFB) is when you're trying to have a site that ranks well and provides a good user experience for visitors. In this post, I'll look at how you can improve this, and discuss a couple of the best ways I've found to bring your TTFB down.


How Do You Improve It?

Start by finding where the wait occurs. A browser's network timing breakdown can separate redirects, DNS lookup and connection setup from waiting for the server's response. Then compare cached and uncached requests and check the origin's application and database timings. Those checks tell you whether the next step belongs in the network, hosting or application code.

Things like how optimised and wellwritten the code is can certainly make a difference, but you will also be able to make huge improvements by thinking about fundamental aspects of your website and its architecture; what software is the server running? What database system are you using? How is that data laid out across the database (or databases)?

The Brawn.

Let's start off with the hardware. A great guitarist needs the loudest amp, the best race drivers drive the fastest cars, and the most successful websites sit on the most powerful servers. You'll notice that my analogies here aren't strictly true (my guitar amp only goes up to 10½), hopefully, that significance won't be lost as I explain how this is one possible influence...

Fundamentally, your server needs to be powerful enough to stay up and running when your site is getting traffic. If you don't have the CPU or RAM to stay afloat, you'll start seeing issues such as slow loading (and slow Time To First Byte), or even worse your site may go down if the traffic spike is significant or prolonged enough.

When it comes to this type of issue, you have a few choices. Realistically if you find your server isn't meeting your website needs then the best thing to do is upgrade it and invest in your hardware. Many hosts now offer dynamic scaling for your server where the virtual machine your website sits upon can increase resources (specifically CPU RAM, or storage) automatically as the website requires. This means you can save money by paying for a lowerspec server that has some surge protection in place, allowing the server to increase in RAM and CPU power when it needs to.

I have worked with setups where scaling did not kick in quickly enough for a sudden traffic spike, leaving the website struggling in the meantime. Short bursts of extra capacity also proved expensive compared with provisioning more capacity from the start. That experience makes me cautious, but I would check the scaling behaviour and costs of the actual service before choosing either approach.

One thing we have seen a lot of over the last year, especially with online groceries when the country went into various lockdowns and people were forced online for their weekly shops, was queuing systems. These balance the load on the site by forcing additional visitors to queue virtually rather than risk the entire site being compromised for everybody.

It is often a surprise when you see a larger brand promoting a marketing push to then be faced with this outdatedfeeling solution, however, this helps to prevent your server from going down from being way too overloaded and helps to keep costs down by reducing hardware and hosting costs. Obviously, however, it does prevent users from immediately reaching your site and may drive them away. Not ideal, but definitely friendly on the wallet. This sort of thing tends to work best if you are selling something hugely in demand like lockdown grocery delivery slots, or the latest PlayStation, or (attempting to) stream the latest from Glastonbury.

If measurements show that the server is running out of resources under the expected load, invest in enough capacity to serve those users. Extra hardware can help with that bottleneck; it will not fix a redirect chain, a distant origin or an unnecessarily expensive query by itself.

The Brains.

Now, moving on to solutions that we as developers have more control over, and which don't hit the wallet quite as hard... There are two things to discuss here: the architecture and infrastructure side of things, and the code side of things.

Photograph of black and white sewing pins appearing like a distributed network diagram by Munro Studio on Unsplash.

The Infrastructure.

I have talked at length about static site generators before. Generating HTML ahead of time removes the rendering and database work needed to produce that HTML on each request. It does not remove network, connection or fileserving delays, and any data fetched later in the browser has its own loading cost. Where the page needs fresh or personalised data, measure the work required before its first byte can be sent.

Traditionally, chances were high that you would be running with MySQL on a LAMP stack, but you might well be using MongoDB, Amazon RDS, Postgres, or any number of other software and systems to handle your data.

Each database system has different strengths and operational costs. MySQL is a familiar choice for a LAMP application, but familiarity alone does not tell you whether it suits your workload. Look at the queries, the data they need and the response times you are actually seeing before considering a replacement.

A slow query does not necessarily mean the whole database has become too large. Inspect its execution plan, indexes and the amount of data it reads or returns. Repeated queries and unsuitable joins can be expensive too. Fixing the access pattern may be much more useful than moving the same query to another database.

A CDN can serve cacheable HTML from a server closer to the visitor, avoiding the trip to the origin and the work of generating that response on a cache hit. If no cached response is available, the request still needs the origin. Decide what may be shared, how long it can remain fresh and how updates invalidate it; a personalised page must not accidentally be served to somebody else. Minification is a separate optimisation, not an automatic consequence of using a CDN.

Photograph of a person holding a magnifying glass against a computer screen of graphs and code by Sajad Nori on Unsplash.

The Code.

So onto the final section; the actual fleshandbones of your website.

Time To First Byte can be heavily influenced by the way your website is built, and just how much is going on when a user visits it. I'm using a generic WordPress website as an example here to explore how the TTFB can be affected and improved. Whilst it's not a tech stack I tend to work in, WordPress accounts for around 40% of all websites online and there is a lot of scope for improvement for a generic WordPress site (!), so there is value in exploring it...

First things first: plugins. A WordPress plugin can add database queries or other serverside work before the HTML response begins, but the cost depends on what it does. Profile that work and remove or improve the expensive parts. Counting plugins alone will not tell you which one is delaying the response.

Next up, caching. Reusing a readymade response can avoid repeated queries and rendering work, sometimes making a substantial difference to TTFB. Check whether requests actually hit the cache and whether the cached content is safe to reuse. The benefit depends on the work avoided and the visitor's route to the cache; it is not a guaranteed improvement of any particular size.

Thirdly, separate the HTML request from the assets it discovers. Extra JavaScript, CSS and image requests can slow the page after the first byte has arrived, but requests discovered from that HTML cannot delay an earlier first byte. Serverside calls made before sending the response can affect TTFB. Reduce unnecessary assets for the wider loading experience, and use request timings to identify the cause of the initial wait.


Wrapping Up

TTFB is a useful place to start investigating a slow page, but it does not identify the cause on its own. Find the slow phase, make the smallest change that addresses it, and measure again. That might mean removing a redirect, bringing a cache closer to visitors, improving a query or adding capacity when the server is overloaded.

My hardware experiences are a reason to check capacity carefully, not a reason to buy a larger server before looking at the timings.


Need a senior engineer involved?

I can work directly in the codebase, review the architecture, or support the team through delivery when the work needs more than extra hands.