http HEAD vs GET performance

Asterius picture Asterius · May 14, 2013 · Viewed 89.7k times · Source

I am setting-up a REST web service that just need to answer YES or NO, as fast as possible.

Designing a HEAD service seems the best way to do it but I would like to know if I will really gain some time versus doing a GET request.

I suppose I gain the body stream not to be open/closed on my server (about 1 millisecond?). Since the amount of bytes to return is very low, do I gain any time in transport, in IP packet number?

Thanks in advance for your response!

Edit:

To explain further the context:

  • I have a set of REST services executing some processes, if they are in an active state.
  • I have another REST service indicating the state of all these first services.

Since that last service will be called very often by a very large set of clients (one call expected every 5ms), I was wondering if using a HEAD method can be a valuable optimization? About 250 chars are returned in the response body. HEAD method at least gain the transport of these 250 chars, but what is that impact?

I tried to benchmark the difference between the two methods (HEAD vs GET), running 1000 times the calls, but see no gain at all (< 1ms)...

Answer

Andre D picture Andre D · May 21, 2013

A RESTful URI should represent a "resource" at the server. Resources are often stored as a record in a database or a file on the filesystem. Unless the resource is large or is slow to retrieve at the server, you might not see a measurable gain by using HEAD instead of GET. It could be that retrieving the meta data is not any faster than retrieving the entire resource.

You could implement both options and benchmark them to see which is faster, but rather than micro-optimize, I would focus on designing the ideal REST interface. A clean REST API is usually more valuable in the long run than a kludgey API that may or may not be faster. I'm not discouraging the use of HEAD, just suggesting that you only use it if it's the "right" design.

If the information you need really is meta data about a resource that can be represented nicely in the HTTP headers, or to check if the resource exists or not, HEAD might work nicely.

For example, suppose you want to check if resource 123 exists. A 200 means "yes" and a 404 means "no":

HEAD /resources/123 HTTP/1.1
[...]

HTTP/1.1 404 Not Found
[...]

However, if the "yes" or "no" you want from your REST service is a part of the resource itself, rather than meta data, you should use GET.