0
0
Nginxdevops~5 mins

Server block structure in Nginx - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Server block structure
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

As the number of server blocks increases, nginx checks more names to find a match.

Input Size (n)Approx. Operations
10Up to 10 name checks
100Up to 100 name checks
1000Up to 1000 name checks

Pattern observation: The number of checks grows linearly with the number of server blocks.

Final Time Complexity

Time Complexity: O(n)

This means the time to find the right server block grows directly with how many server blocks exist.

Common Mistake

[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.

Interview Connect

Understanding how nginx matches server blocks helps you reason about configuration performance and scaling in real setups.

Self-Check

What if nginx used a hash map to store server names instead of checking each block? How would the time complexity change?