Server block structure in Nginx - Time & Space Complexity
We want to understand how the time to process requests grows as we add more server blocks in nginx.
How does nginx handle multiple server blocks when matching requests?
Analyze the time complexity of the following nginx server block configuration.
server {
listen 80;
server_name example.com;
location / {
root /var/www/example;
}
}
server {
listen 80;
server_name test.com;
location / {
root /var/www/test;
}
}
This configuration defines two server blocks, each handling requests for different domain names.
When a request arrives, nginx checks each server block to find a matching server_name.
- Primary operation: Matching the request's host against server_name in each server block.
- How many times: Once per server block until a match is found or all are checked.
As the number of server blocks increases, nginx checks more names to find a match.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 name checks |
| 100 | Up to 100 name checks |
| 1000 | Up to 1000 name checks |
Pattern observation: The number of checks grows linearly with the number of server blocks.
Time Complexity: O(n)
This means the time to find the right server block grows directly with how many server blocks exist.
[X] Wrong: "nginx instantly finds the right server block no matter how many there are."
[OK] Correct: nginx checks server blocks one by one until it finds a match, so more blocks mean more checks.
Understanding how nginx matches server blocks helps you reason about configuration performance and scaling in real setups.
What if nginx used a hash map to store server names instead of checking each block? How would the time complexity change?