iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🌐

Understanding the Mechanics of Web Servers

に公開

Even when developing web applications, I think there are few cases where detailed knowledge about web servers is required. Although web apps still run on top of web servers, in this modern era where they are often run on managed cloud services, someone with little experience like me can't easily imagine cases where such knowledge is necessary. Bottlenecks in web apps are often at a slightly higher layer, and I believe it's more efficient to study those areas if the goal is performance improvement.

That being said, when developing web apps, you can't help but wonder how web servers work. I certainly do. In particular, I had no idea how a web server handles multiple requests. Also, I couldn't really imagine how web servers interact with web apps or what other components are necessary in a web service besides the web server.

This post is a summary of what I researched about how web servers work, compiled for my own understanding.

What is a Web Server?

A web server is software or hardware that receives requests and returns some kind of data as a response. This data includes HTML pages, images, CSS stylesheets, JavaScript files, JSON, etc., and the server returns these in response to requests.

Modern web servers need to process requests from multiple clients concurrently. It's easy to imagine processing requests one by one—blocking other requests until one is finished. However, in reality, it becomes complex because concurrent processing is performed.

There are as many web server architectures as there are methods for concurrent processing, and understanding the details requires stepping into the realm of system programming. Architectures include multi-process, multi-thread, event-driven, hybrid, and green threads. To understand the details of these architectures, knowledge of system programming, such as how I/O is handled, is necessary.

Overview of Network Programming

The area of system programming important for understanding how web servers work is network communication. After a web server accepts a request from a client through the network, it receives data from the client or sends data to the client.

Basic Knowledge

First, I will explain the basic knowledge that serves as a prerequisite for network programming.

System Calls

In this context, programming that utilizes system calls is referred to as system programming.

A system call is a method for an application to call the functions of the OS kernel. In modern CPUs, user mode and kernel mode are distinguished for security. Kernel mode allows unrestricted operations, but user mode has restrictions. The OS provides processes that operate in kernel mode as system calls, allowing applications to execute operations in kernel mode through these system calls.

Representative system calls include open, read, write, and close, which perform file operations. Those related to sockets used in network communication, which I will discuss later, include socket, bind, listen, accept, and connect. Other important ones for network communication include system calls for I/O event notification, such as select and epoll (kqueue).

Sockets

In network communication, an interface called a socket is used.

A socket is a data model representing an endpoint in communication, including:

  • Local IP address
  • Local TCP port
  • Remote IP address
  • Remote TCP port

For example, when a client and a web server are communicating, the socket on the web server side contains the web server's own information in the local IP address and TCP port, and the destination client's information in the remote IP address and TCP port.

In network communication, you can use sockets to receive data from a client or send data to a client. Specifically, you receive data by reading from a socket and send data by writing to a socket.

File Descriptors

Sockets are referenced by integers called file descriptors.

A file descriptor is an integer used to refer to a file within a process in Unix, and various resources are referenced by this in Unix. Besides files and sockets, there are also connected keyboards and terminals, which are virtual devices. A file descriptor is an integer that is unique within a process, but not necessarily across processes.

These file descriptors are managed by data called open file descriptions that exist inside the OS. Within an open file description, which information is referenced is determined by the process ID and the file descriptor.

This philosophy of Unix is called "Everything is a file," allowing any resource to be handled with a unified interface. For example, reading/writing files and reading/writing sockets can be performed using the same system calls.

Standard input, standard output, and standard error, which are often seen in web development, are also assigned file descriptors, namely 0, 1, and 2 respectively. Outputting to the screen can be achieved by executing a file-write system call against file descriptor 1, which is standard output.

Overview of the Request Processing Flow

To process a request as a web server using sockets, you need to call several system calls related to sockets. The flow of processing a request is as follows:

  1. Create a socket (socket)
  2. Assign an address to the socket (bind)
  3. Wait for requests (listen)
  4. Accept a request (accept)
  5. Process the request...
  6. Close the socket (close)

Writing this using Ruby's socket library looks like this:

require 'socket'

server = Socket.new(:INET, :STREAM) # Create a socket
addr = Socket.pack_sockaddr_in(4481, '0.0.0.0')
server.bind(addr) # Assign an address
server.listen(5) # Wait for requests

connection, _ = server.accept # Accept a request
# Process the request...
connection.close # Close the socket

Socket.accept blocks subsequent processing until a request arrives, and when a request does arrive, it creates a socket connected to the client. accept releases the block once a connection is established between the client and the web server via a TCP handshake.

You can exchange data with the client by reading from and writing to the socket created by this accept. Since the socket created by accept contains the web server's IP address and TCP port as local information, and the client's IP address and TCP port as remote information, it can be used for communication with the client.

Also, in Ruby's socket library, you can implement the request processing loop as follows:

require 'socket'

Socket.tcp_server_loop(4481) do | connection |
  # Process the request...
  connection.close
end

Socket I/O Models

In this section, I will explain the I/O models related to sockets.

Blocking I/O

One way to read from and write to sockets is Blocking I/O.

Blocking I/O is I/O where waiting may occur before an I/O operation, potentially blocking subsequent processing. For example, read or write when the socket is not in non-blocking mode falls into this category. In the case of blocking I/O, read blocks processing until the data is ready to be read, and write blocks processing until the system is ready to write. read may also block until it receives an EOF or a minimum number of bytes.

Code using blocking I/O looks like this:

require 'socket'

Socket.tcp_server_loop(4481) do | connection |
  request = connection.read
  connection.write request

  connection.close
end

Non-blocking I/O

Another way to read from and write to sockets is Non-blocking I/O.

Non-blocking I/O is I/O that returns from the function immediately if a wait is likely to occur before an I/O operation. For example, read or write when the socket is in non-blocking mode falls into this category. In the case of non-blocking I/O, the function returns immediately if the I/O operation is not ready.

Example code using non-blocking I/O is as follows:

require 'socket'

Socket.tcp_server_loop(4481) do | connection |
  loop do
    begin
      # Calls read internally
      puts connection.read_nonblock(4096)
    rescue Errno::EAGAIN
      retry
    rescue EOFError
      break
    end
  end

  connection.close
end

It retries when the read is still in preparation, but this doesn't seem to be very meaningful. Since Errno::EAGAIN is issued when it is in preparation, it keeps calling read until preparation is complete. Although read no longer blocks, it still results in a loop, appearing no different from blocking I/O.

I/O Multiplexing

The true value of non-blocking I/O is demonstrated when used in conjunction with I/O Multiplexing. This will be explained in detail later in the Event-driven section of Web Server Architecture.

I/O multiplexing refers to managing multiple file descriptors within a single process and single thread using the select system call. select is a system call for monitoring I/O event notifications, but because it's not very efficient, the more efficient epoll or kqueue are used in modern systems. Although the interfaces are different, they are system calls that achieve similar things, so I will explain it using select here.

select is a system call that monitors multiple file descriptors and returns those for which I/O operations are ready. For example, if a web server is connected to multiple clients, passing those sockets to select will return the sockets that are ready for I/O operations. select blocks subsequent processing until there is a ready socket or a timeout occurs.

Code for I/O multiplexing using IO.select, which uses the select system call, looks like this:

connections = [<TCPSocket>, <TCPSocket>, <TCPSocket>]

loop do
  ready = IO.select(connections)

  readable_connections = ready[0]
  readable_connections.each do | conn | 
    data = conn.readpartial(4096)
    process(data)
  end
end

Here, three sockets are passed as the first argument to IO.select, and the data for sockets ready for reading is contained in the first element of the array returned by IO.select. readpartial is a Ruby function that immediately returns available data, but it blocks if the reading is not ready. Since it has returned from select, the I/O is ready, so we use it here.

IO.select can take an array of IO objects to read from as the first argument and an array of IO objects to write to as the second argument. Internally, the select system call is called, and an array of file descriptors to monitor for reading and writing is passed.

Asynchronous I/O

There is also Asynchronous I/O as a method for reading from and writing to sockets.

In asynchronous I/O, when an I/O operation is issued, it returns from the function immediately, and the I/O operation is executed in the background. What is currently popular in Linux is io_uring, which implements asynchronous I/O as a Linux-specific system call.

The asynchronous I/O mentioned here is strictly asynchronous I/O at the system call level. Programming languages and libraries can implement application-level asynchronous I/O without directly using such system calls. Application-level asynchronous I/O can be seen as a method of achieving this through functions provided by the language or library rather than through system calls.

For example, libuv, a library for asynchronous I/O used in Node.js, does not use system-call-level asynchronous I/O. For network I/O, it uses non-blocking I/O + I/O multiplexing instead of asynchronous I/O, and for file I/O where I/O multiplexing cannot be used, it uses multi-threading + blocking I/O instead of asynchronous I/O.

Web Server Architecture

In this section, I will explain web server architectures classified by the methods web servers use to handle multiple requests. These architectures are based on the method of processing a single request.

The names of the architectures are not necessarily standard terminology.

Multi-process

The multi-process architecture is an architecture that achieves concurrent request processing using multiple processes. One process handles one request, and multiple instances of these processes are created.

There are two ways this architecture works: creating a process after receiving a request, and using pre-created processes. Here, I will call the former the on-demand type (a coined term) and the latter the prefork type.

On-demand type is an architecture that creates a process after receiving a request. The processing flow can be thought of as follows:

  1. The main server process accepts a request (accept)
  2. The main server process forks a child process (worker process)
  3. The child process handles the request, while the main process returns to step 1.

The main process holds a socket for accepting requests and calls fork after calling accept. Since fork copies the file descriptors of the parent process to the child process, the socket created by accept can be operated on in the child process.

The on-demand type has the advantage of being able to process multiple requests concurrently with a simple implementation, but since calling fork for every request is wasteful, architectures that pre-create processes are more commonly used. Additionally, with a large number of requests, the number of processes can become enormous, potentially leading to a system crash.

Prefork type is an architecture where child processes are created in advance, and those child processes accept requests. The processing flow can be thought of as follows:

  1. The main server process creates a socket to wait for requests.
  2. The main server process forks a specified number of child processes.
  3. The child processes accept and handle requests using the socket created in step 1.

The main process creates a socket for waiting in advance, and multiple child processes use that socket to accept requests. When forked, the socket is shared between parent, child, and siblings, and when a request arrives, only one of the processes responds.

The prefork type has the advantage of not needing to pay the cost of fork for every request, but it has the disadvantage of consuming a lot of memory because it creates multiple processes. Also, in the example above, performance drops if there are more requests than pre-created processes.

A web server software that uses the prefork type is Apache MPM prefork, which is commonly used with PHP.

Multi-thread

The multi-thread architecture is an architecture that achieves concurrent request processing using multiple threads. One thread handles one request, and multiple threads are created.

This architecture also has two versions: one that creates a thread after receiving a request, and one that uses pre-created threads. Here, I will call the former the on-demand type (a coined term) and the latter the thread pool type.

This architecture is similar to multi-process, but there are some differences between processes and threads. Processes have higher isolation than threads and do not share memory between processes, whereas threads do share memory. On the other hand, processes have higher creation costs because they copy memory, while threads have lower creation costs because they share it.

On-demand type is an architecture that creates a thread after receiving a request. The processing flow can be thought of as follows:

  1. The main server thread accepts a request (accept)
  2. The main server thread creates a thread
  3. The thread handles the request, while the main thread returns to step 1

Since threads share the process, the socket created by accept can be used within the thread. Unlike processes, memory is not copied, so you must be careful as saving the socket created by accept in a global area allows other threads processing different requests to access it.

The multi-thread on-demand type has the same advantages and disadvantages as the multi-process on-demand type. The difference from processes is that threads have lower isolation and creation costs.

Thread pool type is an architecture where threads are created in advance, and those threads accept requests. The processing flow can be thought of as follows:

  1. The main server thread creates a socket to wait for requests
  2. The main server thread creates a specified number of threads
  3. The threads accept and handle requests using the socket created in step 1

The main process creates a waiting socket in advance, and multiple threads use that socket to accept requests. Since threads share the process, they can share the socket, and when a request arrives, only one of the threads responds.

This also has the same advantages and disadvantages as the multi-process prefork type. The differences between processes and threads are the same as in the on-demand type.

Event-driven

The event-driven architecture is an architecture that processes requests concurrently using an event loop operating on a single thread. A single thread handles multiple requests. Generally, non-blocking I/O and I/O multiplexing are used.

The processing flow for event-driven can be thought of as follows. The following assumes select, but the same applies to the more efficient epoll (kqueue).

  1. The server creates and monitors a socket to wait for connections (select).
  2. When a connection is made, it adds that socket to the list of monitored sockets.
  3. The server monitors the connections from steps 1 and 2.
  4. When notified that a monitored connection is ready for reading, it reads a certain size and calls the associated callback.
    • If reading is completed to the end, it is removed from the monitoring list; otherwise, it continues to be monitored.
  5. When notified that a monitored connection is ready for writing, it writes a certain size.
    • When writing is finished, it is removed from the monitoring list; otherwise, it continues to be monitored.

This architecture monitors and processes I/O event notifications such as "ready for reading" or "ready for writing" using select within a loop called an event loop. Non-blocking I/O is used for I/O operations like reading and writing, and data is processed in fixed sizes rather than all at once.

In this architecture, the following sockets are managed by a single thread via I/O multiplexing:

  • One socket waiting for connections from clients
  • Multiple sockets whose reading is to be monitored
  • Multiple sockets whose writing is to be monitored

The socket waiting for connections is created and monitored when the server starts, and sockets created by accepting connections are also monitored together. accept is performed on the socket created at startup, and each time a connection is established via accept, the created socket is added to the monitoring list.

Reading in step 4 includes reading request data from the client, and the "associated callback" includes processing that request. Within this callback, some processing is executed when all the request data is ready, and then written to the response. If the data could not be read to the end (EOF), reading is resumed upon the next notification.

Writing in step 5 includes writing response data to the client. If the data could not be written to the end, writing is resumed upon the next notification.

The advantage of the event-driven architecture is that it is not affected by the cost or upper limit of process or thread creation. While the on-demand multi-process/multi-thread models had issues where performance degraded due to creation costs or massive numbers of instances, this architecture is unaffected because it uses a single process and a single thread. It also avoids the problem of having to pre-determine the number of processes or threads as in prefork or thread pool models. These kinds of problems are sometimes referred to as the C10K problem, and event-driven can be said to solve it.

The disadvantage of the event-driven architecture is that if you write code that blocks during request processing, the entire thread will be blocked. For example, if you write code that performs an infinite loop within the callback mentioned in step 4 of the flow above, the server will no longer be able to accept any requests. This is a problem that is less likely to occur in multi-process/multi-thread architectures.

Processing in computers can be classified into CPU-bound processing and I/O-bound processing based on the factors that limit performance. Processing where performance is limited by the CPU is CPU-bound, such as data encryption or image processing. Processing where performance is limited by I/O is I/O-bound, such as database operations or calling external APIs.

Event-driven architecture can demonstrate high performance in cases with many I/O-bound tasks, but it may fail to do so in cases with many CPU-bound tasks. However, it might be possible to make CPU-bound tasks I/O-bound by offloading them to external APIs.

Additionally, event-driven has the disadvantage that it is difficult to extract the full performance of the CPU. Since this architecture operates on a single thread, even if the number of CPU cores increases, the cores other than the one processing that single thread will go to waste.

Event-driven is used in Node.js (libuv).

Hybrid

An architecture that partially combines elements of the various architectures mentioned above is called a hybrid architecture. Examples include architectures that are multi-process and multi-threaded, multi-process and event-driven, or multi-threaded and event-driven.

Here, let's look at what kind of architectures actual web server software use.

Nginx can be described as a multi-process and event-driven architecture. This involves pre-creating processes using prefork and having each process handle requests concurrently using an event-driven approach. Unlike the standard multi-process architecture, it is not one request per process, but it does create multiple processes to handle request processing.

Nginx overcomes the disadvantage of the event-driven model, which is the difficulty in drawing out CPU performance. Since the event-driven model is used within multiple processes, one server utilizes multiple processes, allowing it to reap the benefits of multi-core CPUs. While the default is one process, it is recommended to create the same number of processes as there are CPU cores.

Apache MPM event can be described as a multi-process and multi-threaded + event-driven architecture. This features a listener thread and multiple worker threads within multiple processes; since actual request processing is performed by worker threads, it is close to a multi-threaded architecture. However, the listener thread that accepts requests uses an event-driven approach, allowing it to handle multiple request acceptances concurrently. In addition to accepting requests, when waiting for a new request after sending a response on a keep-alive connection, a worker thread passes the socket to the listener thread, which then waits for the request using an event-driven approach. It could be said that the event-driven model is used specifically for network I/O with the client.

Unlike Nginx, Apache MPM event only partially uses the event-driven architecture, but I believe there is no significant difference in performance. Although I don't know the details since I haven't measured it myself, it has been shown that it could deliver equivalent or better performance as of 2012.

Green Threads

The green thread architecture is an architecture that handles requests concurrently using green threads, which are lightweight threads managed in userland. One green thread processes one request, and multiple green threads are created.

Generally, modern green threads follow what is known as the M:N model. This is a model where M green threads are executed by N native threads. It can leverage multi-core CPUs more effectively than running multiple green threads on a single native thread.

Green threads are lighter than native threads, and the costs for creation and context switching are low. As a result, they can be created in large numbers with fewer resources compared to processes or threads, making them a viable solution for the C10K problem.

Examples of this architecture in use include Rust's tokio and Go's goroutines.

Interaction between Web Servers and Web Apps

While I've introduced web server architectures, in a web service, the web server and the web application must collaborate. There are several ways for this interaction, and various technologies have been employed over time, such as CGI, FastCGI, embedded modules, and language-specific interfaces. Furthermore, some languages allow for the implementation of high-performance web servers using only their standard libraries, where the web server and the web application are essentially integrated.

Let's briefly examine the methods for interaction between web servers and web applications.

CGI (Common Gateway Interface) is a method of communicating with a web app using standard input/output. In response to a request, a CGI program (web app) is launched, data is passed to the program via standard input or environment variables, and the data output to standard output is sent to the client. CGI program files often include a Shebang that specifies the interpreter to load the script, which is used to execute the file. For PHP, it would be like the web server executing php script.php. CGI is a legacy mechanism that incurs high overhead because a process is created for every request.

FastCGI is a version of CGI that pools and reuses processes in advance. Upon receiving a request, it is processed by a waiting process, and data is exchanged with the web server using sockets. PHP's FPM is an implementation of FastCGI, and Nginx often uses this php-fpm. In this setup, Nginx acts as the FastCGI client receiving the request, and php-fpm acts as the FastCGI server acquiring and processing the request. While embedded modules (discussed later) were frequently used for PHP, some operating systems have deprecated them, and FastCGI has become more common recently.

Embedded modules are modules used to integrate a language directly into the Apache HTTP Server. Upon receiving a request, the web application is executed directly within the web server's Apache process to handle the request. These modules are implemented for each language, such as mod_php, mod_python, or mod_ruby. However, for languages other than PHP, web servers implemented in the same language as the web app (as discussed later) are used instead of Apache, so I believe mod_php is the only one still widely used.

Language-specific interfaces refer to interfaces specific to each language for connecting web servers and web apps. Examples include Python's WSGI and ASGI, and Ruby's Rack, which allow for the interaction between compatible web servers and web apps. These interfaces were created to improve compatibility across multiple web servers and web application frameworks. There seems to have been a background where it was a burden for developers to support multiple web servers during an era when a massive number of web frameworks were emerging.

Additionally, web servers built with the same language as the web app are sometimes used for optimization. This is particularly famous in Python and Ruby; for Python, there are Gunicorn, which implements WSGI, and Uvicorn, which implements ASGI. For Ruby, Puma is a common choice that uses Rack.

Integrated Web Server and Web App is a case often seen in languages where a high-performance web server can be implemented using only the standard library. For example, Go and Node.js can implement high-performance web servers with just their standard libraries, so there is less need for dedicated web server software. While Rust doesn't have this in its standard library, it is possible to implement a high-performance web server using asynchronous runtime libraries.

Reverse Proxies and Load Balancers

As the scale of a web service grows, you might need a reverse proxy or a load balancer between the client and the web server. If the web server accepts requests directly, it may not be able to handle a large volume of requests.

A reverse proxy is a service that sits between the client and the web server and performs various pre- and post-processing tasks. While the narrow definition is a service that receives requests from clients and forwards them to a web server, the term "reverse proxy" often implies various pre- and post-processing tasks. Reverse proxies are placed in front of web servers to increase control points and optimize resources for the entire web service.

Examples of processing performed by a reverse proxy include URL rewriting and static file delivery. URL rewriting allows for flexible changes to externally visible URLs without modifying the system. Additionally, by delivering static files from a reverse proxy, it is possible to concentrate web server resources on dynamic content processing.

Although the need for reverse proxies for static file delivery has decreased, there is still a benefit to increasing the system's control points. Nowadays, CDNs are widely used for static file delivery, reducing the necessity of reverse proxies for this specific purpose. However, placing a reverse proxy in front of a web server allows you to increase the control points of the system. This makes it easier to respond to issues and increases the possibility of solving problems without modifying the web app itself.

A load balancer is a service that distributes requests among multiple web servers to balance the load. In some cases, a reverse proxy also functions as a load balancer. Even if the load increases and it becomes difficult to handle requests, a load balancer allows you to increase the number of web servers behind it and scale the system. To eliminate the need to issue SSL certificates for each web server, SSL can also be terminated at the load balancer.

I feel that load balancers have become a more important component as the practice of arranging web servers horizontally has increased with the development of virtualization technology. One reason for the increase in horizontal scaling is that virtualization technology has enabled flexible adjustment of the number of web servers. Another reason is likely that costs have decreased because multiple web servers can now run on a single physical server.

As a result of the increased instances of horizontal alignment, the performance of a single web server has become less critical than before. Consequently, the C10K problem, which was briefly mentioned in the web server architecture section, is considered to have less impact than it did back then. If a single web server cannot handle the requests, you can simply increase the number of web servers, which is easier to do now than in the past.

Conclusion

I have summarized the mechanisms and related components of web servers.

Modern web apps often utilize the cloud, and in web app development, I think it is becoming less important how each individual web server operates. Because horizontal scaling of web servers has become easier, bottlenecks have often shifted to the reverse proxies or load balancers in the preceding stage.

On the other hand, I feel that understanding how web servers work leads to an understanding of concurrent processing in programs. Understanding the inner workings of a web server means understanding the methods of concurrent processing—specifically, how to handle multiple requests. To understand this in detail, knowledge of system-level network programming is required, and I believe this knowledge can be applied to everything, not just web servers.

An understanding of concurrency is necessary to improve the performance of various applications, not just web servers.

I hope this post serves as a starting point for understanding web server mechanisms and, by extension, improving application performance.

References

Discussion