views:

218

answers:

2

Is there a performance difference between TCP connections to:

  • localhost / 127.0.0.1
  • a domain which resolves to the local machine

Or more specifically, do the latter connections go through the loopback device, or over the actual network?

The reason I'm asking is I'm thinking about changing database settings in many PHP apps so they use a full domain instead of localhost. That way we could more easily move the database to a different server, if the need arises.

A: 

that depends on how the names are resolved. the procedure is typically /etc/hosts first, DNS if that fails. if localhost is in your /etc/hosts, putting whatever.wherever in the file as well will make it resolve with the same speed.

just somebody
+5  A: 

This is implementation and operating system dependent. On Windows, anything connecting to a local IP address, even if it is an outside-facing IP, will go over loopback. This is a documented problem for applications such as packet sniffers, because you can't sniff the loopback. (Windows doesn't treat loopback as a "device" -- it is handled at the network level.) However, in this case it would work in your favor.

Linux, in contrast, will follow whatever you have in your routing table, so packets that are destined to your local machine will go to your local machine over the network if the routing table isn't properly configured. However, in 99% of the cases the routing will be configured properly. Your packets won't go over the loopback device, but the TCP/IP stack will know that you are contacting a local IP and it will virtually go out and back in the proper ethernet device.

In a properly configured environment, the only bottleneck for using a domain name would be DNS resolution time. Contacting an outside DNS can add additional latency into your configuration. However, if you add in the domain name into your /etc/hosts file (C:\Windows\System32\drivers\etc\hosts on Windows), your system will skip the DNS resolution phase and obtain an IP directly, making this time cost moot.

David Pfeffer
Regarding the DNS resolution time, doesn't the cache solve that?
Bart van Heukelom
Also, I guess I could make it go through loopback by overriding database.mynetwork.com to point to 127.0.0.1 in the hosts file?
Bart van Heukelom
DNS caches are implementation dependent, but usually cached DNS refers not to a local cache on your computer, but a cache on the remote DNS so it doesn't have to contact the root name server and then the name server of the foreign domain. In your case, that doesn't apply since it is a local domain name anyway. You definitely could just override database.mynetwork.com to point to 127.0.0.1 (**or** you could point to the outside IP of your interface, whichever you prefer) in the hosts file.
David Pfeffer
Excellent answer
Pekka