Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1

104 | Chapter 4: Database


Why Is Filesystem Storage So Fast?
The short answer is that web servers are optimized for throwing binary files down a
TC Psocket. And the most common thing you do with binary files is throw them down
a TCP socket.
Long answer: the secret to this performance, under Linux and various BSDs, is the kernel
sendfile()syscall (not to be confused with X-Sendfile, discussed later). Thesendfile()
function copies data quickly from a file descriptor (which represents an open file) to a
socket (which is connected to the client). This happens in kernel mode, not user mode—
the entire process is handled by the operating system. The web server doesn’t even have
to think about it. Whensendfile() is invoked, the process looks a bit like Figure 4-1.
On the other hand, Rails is necessarily involved with the whole process when reading data
from the database. The file must be passed, chunk by chunk, from the database to Rails,
which creates a response and sends the whole thing (including the file) to the web server.
The web server then sends the response to the client. Usingsendfile()would be impos-
sible here because the data does not exist as a file. The data must be buffered in memory,
and the whole operation runs in user mode. The entire file is processed several times by
user-mode code, which is a much more complicated process, as shown in Figure 4-2.

Figure 4-1. Serving files using sendfile( )


Figure 4-2. Serving files from the database


Client Linux Apache Rails

Filesystem DB

Client Linux Apache Rails

Filesystem DB
Free download pdf