Wednesday, March 15, 2017

What's the difference between Unix socket and TCP/IP socket when setting up PHP-FPM?

What's the difference between Unix socket and TCP/IP socket when setting up PHP-FPM?

A UNIX socket is an inter-process communication mechanism that allows bidirectional data exchange between processes running on the same machine.

IP sockets (especially TCP/IP sockets) are a mechanism allowing communication between processes over the network. In some cases, you can use TCP/IP sockets to talk with processes running on the same computer (by using the loopback interface).

UNIX domain sockets know that they’re executing on the same system, so they can avoid some checks and operations (like routing); which makes them faster and lighter than IP sockets. So if you plan to communicate with processes on the same host, this is a better option than IP sockets.

Edit: As per Nils Toedtmann's comment: UNIX domain sockets are subject to file system permissions, while TCP sockets can be controlled only on the packet filter level.
===
When you are using TCP, you are also using the whole network stack. Even if you are on the same machine, this implies that packets are encapsulated and decapsulated to use the network stack and the related protocols.

If you use unix domain sockets, you will not be forced to go through all the network protocols that are required otherwise. The sockets are identified solely by the inodes on your hard drive.
===
I believe that UNIX domain sockets in theory give better throughput than TCP sockets on the loopback interface, but in practice the difference is probably negligible.

Data carried over UNIX domain sockets don't have to go up and down through the IP stack layers.

re: Alexander's answer. AFAIK you shouldn't get any more than one context switch or data copy in each direction (i.e. for each read() or write()), hence why I believe the difference will be negligble. The IP stack doesn't need to copy the packet as it moves between layers, but it does have to manipulate internal data structures to add and remove higher-layer packet headers.

unix domain socket (UDS) work like system pipes and it send ONLY data, not send checksum and other additional info, not use three-way handshake as TCP sockets.
===
Unix sockets can have owners - users and groups, TCP sockets cannot. Therefore, Unix sockets are more secure - but you cannot separate your webserver (eg, NginX) from your PHP application server (eg. PHP5-FPM) across the network.
===

Reference:

http://serverfault.com/questions/124517/whats-the-difference-between-unix-socket-and-tcp-ip-socket

http://stackoverflow.com/questions/257433/postgresql-unix-domain-sockets-vs-tcp-sockets/257479#257479

http://unix.stackexchange.com/questions/91774/performance-of-unix-sockets-vs-tcp-ports

https://www.reddit.com/r/webhosting/comments/2mgyzg/unix_domain_socket_vs_tcp_can_someone_explain_and/

No comments: