Network policies for security in Kubernetes - Time & Space Complexity
We want to understand how the time to enforce network policies changes as the number of policies or pods grows.
How does adding more policies or pods affect the work Kubernetes does to secure the network?
Analyze the time complexity of the following Kubernetes 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
This policy allows pods with label role: frontend to send traffic to pods labeled app: nginx.
Look at what Kubernetes does repeatedly when applying network policies.
- Primary operation: Checking each pod against policy selectors to see if it is allowed or denied.
- How many times: For each pod, Kubernetes checks all relevant policies and their rules.
As the number of pods and policies grows, the checks increase.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 pods, 5 policies | ~50 checks |
| 100 pods, 20 policies | ~2000 checks |
| 1000 pods, 50 policies | ~50,000 checks |
Pattern observation: The number of checks grows roughly with the product of pods and policies.
Time Complexity: O(pods × policies)
This means the work to enforce network policies grows proportionally as you add more pods and policies.
[X] Wrong: "Adding more policies won't affect performance much because they run independently."
[OK] Correct: Each pod must be checked against all policies, so more policies mean more checks and more work.
Understanding how network policy enforcement scales helps you design secure and efficient Kubernetes clusters.
"What if network policies used IP blocks instead of pod selectors? How would that change the time complexity?"