0
0
Nginxdevops~5 mins

Adding response headers (add_header) in Nginx - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Adding response headers (add_header)
O(n)
Understanding Time Complexity

When nginx adds response headers, it processes each header line before sending the response.

We want to understand how the time to add headers grows as the number of headers increases.

Scenario Under Consideration

Analyze the time complexity of the following nginx configuration snippet.


server {
    listen 80;
    location / {
        add_header X-Custom-1 "Value1";
        add_header X-Custom-2 "Value2";
        add_header X-Custom-3 "Value3";
        # ... more add_header directives ...
    }
}
    

This snippet adds multiple custom headers to each HTTP response served by nginx.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Adding each header line to the response.
  • How many times: Once per header configured with add_header.
How Execution Grows With Input

As the number of headers increases, nginx processes each header one by one.

Input Size (n)Approx. Operations
10 headers10 operations
100 headers100 operations
1000 headers1000 operations

Pattern observation: The work grows directly with the number of headers added.

Final Time Complexity

Time Complexity: O(n)

This means the time to add headers grows linearly with the number of headers configured.

Common Mistake

[X] Wrong: "Adding more headers does not affect response time because headers are small."

[OK] Correct: Even small headers require processing; more headers mean more work, so response time grows with header count.

Interview Connect

Understanding how configuration directives like add_header scale helps you reason about server performance and response times in real projects.

Self-Check

What if nginx cached the headers once instead of adding them on every response? How would the time complexity change?