Network policies for traffic control in Kubernetes - Time & Space Complexity
When using Kubernetes network policies, it is important to understand how the system processes rules as the number of policies grows.
We want to know how the time to enforce traffic control changes when more policies or pods are added.
Analyze the time complexity of the following network policy snippet.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-nginx
spec:
podSelector:
matchLabels:
app: nginx
ingress:
- from:
- podSelector:
matchLabels:
role: frontend
ports:
- protocol: TCP
port: 80
This policy allows pods labeled 'frontend' to send TCP traffic on port 80 to pods labeled 'nginx'.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each incoming packet against all matching network policies.
- How many times: For each packet, the system checks all relevant policies and their rules.
As the number of network policies and pods increases, the system must check more rules for each packet.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 policies | Checks 10 rules per packet |
| 100 policies | Checks 100 rules per packet |
| 1000 policies | Checks 1000 rules per packet |
Pattern observation: The number of checks grows roughly linearly with the number of policies.
Time Complexity: O(n)
This means the time to process traffic grows linearly as the number of network policies increases.
[X] Wrong: "Adding more policies won't affect traffic processing time much because they run in parallel."
[OK] Correct: Even if policies are processed efficiently, each packet still needs to be checked against all relevant rules, so more policies mean more checks.
Understanding how network policies scale helps you design systems that keep traffic secure without slowing down communication.
"What if we changed the policy to select pods by namespace instead of labels? How would the time complexity change?"