Are there server performance benefits to fetching only specific fields when querying the REST API?

I understand that having less data being downloaded improves the experience to the end user, but my question is related to the actual server performance, would the response be faster?

Would adding _fields[]=id&_fields[]=title, etc… to the above url improve server performance?

No it would not, and for several reasons.

When you ask for a post it fetches the entire post row in the database, and it also fetches any post meta and terms so that they’re fetched all at once in bulk rather than lots of inefficient smaller queries.

So when you ask for only a subset of those fields, you don’t save any database time or memory, and you add a tiny amount of processing to filter it just to the parts you want.

On top of this, you’re asking for a bespoke couture one of a kind response specific just to you. This means we can’t cache the result and reuse it hundreds or thousands of times. As a result, our scalability can be significantly reduced, as well as potential new queries to grab the data we filtered out because they’re now needed on the client side.

There are savings in bandwidth at the server end, but the server end will be in a data centre with a fat network pipe, so this advantage is negligible in comparison to CPU savings.

Steps can be taken to mitigate this, such as making sure that the client can only request a small number of unique queries so that caching is feasible.

Otherwise, there’s a very real risk that the time/speed savings of a smaller network transfer to the client are dwarfed by the extra time taken at the server to generate the response. A larger cached response may take more time to transfer, but that transfer can begin immediately, and the browser can process it while it’s downloading.

So take real life measurements and compare.

But what if I built custom endpoints that made optimised database calls?

Still no, even if you hardcode the response so that no database queries are happening, the server still has to load WordPress. It can never compete with a dedicated cache such as Varnish, or caching options that load early and exit before WP can fully load such as Batcache.

Likewise, you would also miss out on all the benefits of object caching. When WP fetches posts terms and meta, they’re put in WP_Cache so that they aren’t fetched multiple times in the same request. If an object cache is present, then this cache persists across multiple requests in main memory, speeding things up even more. A site with such a cache may make no database calls because the data is already fetched.

Leave a Comment