Default server handling in Nginx - Time & Space Complexity
When nginx receives a request, it decides which server block should handle it. This process is called default server handling.
We want to understand how the time to find the right server changes as the number of server blocks grows.
Analyze the time complexity of the following nginx configuration snippet.
server {
listen 80 default_server;
server_name _;
location / {
return 444;
}
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
}
}
This snippet defines two server blocks. One is the default server for port 80, and the other handles requests for example.com.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: nginx checks each server block's listen and server_name directives to find a match.
- How many times: It compares the incoming request against each server block until it finds a match or uses the default.
As the number of server blocks increases, nginx checks more entries to find the right one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 comparisons |
| 100 | About 100 comparisons |
| 1000 | About 1000 comparisons |
Pattern observation: The number of checks grows directly with the number of server blocks.
Time Complexity: O(n)
This means the time to find the right server grows linearly as you add more server blocks.
[X] Wrong: "nginx instantly finds the correct server no matter how many servers there are."
[OK] Correct: nginx must check each server block until it finds a match or defaults, so more servers mean more checks.
Understanding how nginx matches requests to servers helps you reason about performance and scaling in real setups. This skill shows you can think about how systems behave as they grow.
"What if nginx used a hash map to store server names instead of checking each one? How would the time complexity change?"