Chaos Engineering in QA: Simulating Network and API Latency
Test application resilience under catastrophic conditions. Learn to simulate packet loss, TCP latency, dropped connections, and downstream API timeouts.
Modern microservice architectures fail in production not because upstream servers crash cleanly with HTTP 500 errors, but because third-party dependencies degrade unpredictably. An external payment gateway taking 15 seconds to reply, an inventory database dropping 10% of TCP packets, or a cross-region cloud link experiencing jitter can tie up backend worker threads until an entire cluster collapses under cascading resource exhaustion.
Injecting artificial network chaos into staging environments allows QA and DevOps teams to verify circuit breakers, retries, and fallback mechanisms before catastrophic production outages occur.
Principles of Chaos Injection Testing
Originating at Netflix with the creation of Chaos Monkey, chaos engineering tests how distributed systems behave under hostile, degraded conditions.
Standard QA suites verify the "happy path" and basic error handling:
- Server returns HTTP 200 $\rightarrow$ parse data.
- Server returns HTTP 404 $\rightarrow$ display error banner.
Chaos engineering tests degraded states:
- Server takes 8,000 milliseconds to send the first byte.
- Connection resets abruptly midway through receiving a 5 MB payload.
- DNS resolution hangs indefinitely.
- 15% of packets are duplicated or reordered.
Comparing Network Chaos Injection Techniques
| Tool / Layer | Target Failure Mode | Implementation Mechanism | Infrastructure Impact |
|---|---|---|---|
Linux tc (netem) |
Kernel-level latency and packet loss | Traffic control qdisc in Linux kernel | Modifies host/container virtual NIC |
| Shopify Toxiproxy | TCP-level (Layer 4) latency, timeouts, bandwidth limits | TCP proxy sitting between microservices | Zero kernel modifications; API driven |
| Chaos Mesh / LitmusChaos | Kubernetes pod kills, network partitions | Privileged agents in the cluster applying tc and iptables rules |
Kubernetes cluster orchestration |
| Mock Server Stubs | Simulated status codes (503, 504) | Application mock responses | Does not test TCP or network layer |
Simulating Latency and Packet Loss with Linux tc (Traffic Control)
The Linux kernel includes the netem (Network Emulator) queueing discipline, configured with the tc command from the iproute2 package. Developers can inject latency and packet drops into Docker containers (with the NET_ADMIN capability) or local virtual machines:
sudo tc qdisc add dev eth0 root netem delay 250ms 20ms distribution normal
# Add 10% random packet loss while keeping the delay
# ("change" replaces all netem parameters, so repeat the delay settings)
sudo tc qdisc change dev eth0 root netem delay 250ms 20ms distribution normal loss 10%
# Verify active traffic control rules
sudo tc qdisc show dev eth0
# Delete all rules and restore native network speed
sudo tc qdisc del dev eth0 root
Programmatic Chaos with Shopify Toxiproxy
For automated CI/CD regression suites, using Shopify Toxiproxy enables tests to inject network toxics programmatically via HTTP REST calls:
import time
import requests
TOXIPROXY_API = "http://localhost:8474"
def inject_upstream_latency(proxy_name: str, latency_ms: int, jitter_ms: int) -> None:
"""Injects artificial network latency into a running Toxiproxy channel."""
toxic_payload = {
"name": "latency_toxic",
"type": "latency",
"stream": "upstream",
"toxicity": 1.0, # Probability of applying the toxic to a connection (1.0 = all)
"attributes": {
"latency": latency_ms,
"jitter": jitter_ms
}
}
resp = requests.post(f"{TOXIPROXY_API}/proxies/{proxy_name}/toxics", json=toxic_payload)
if resp.status_code == 200:
print(f"Injected {latency_ms}ms latency into {proxy_name}.")
def remove_upstream_latency(proxy_name: str) -> None:
"""Restores clean network connection."""
requests.delete(f"{TOXIPROXY_API}/proxies/{proxy_name}/toxics/latency_toxic")
print(f"Removed toxic from {proxy_name}.")
# Example test workflow
inject_upstream_latency("payment_gateway", latency_ms=4500, jitter_ms=500)
# Run API integration assertions to verify client timeout and fallback trigger...
remove_upstream_latency("payment_gateway")
Pro-Tip: The slow-drip response Refused connections are easy to handle: socket libraries raise
ECONNREFUSEDimmediately. A much nastier failure is a dependency that keeps the connection alive but sends one byte every few seconds (the mirror image of the Slowloris attack, where a client trickles a request to a server). A per-read timeout does not help here, because every read succeeds before the timeout expires. Configure an overall deadline for the whole request, otherwise threads stay blocked and eventually exhaust the pool. Toxiproxy'sslicerandbandwidthtoxics are useful for reproducing this.
When testing retry policies, backoff intervals, or synthetic payment payload queues, generate non-repeating mock order numbers and session IDs with our Random Value Generator. If your chaos test scenarios simulate complex international billing accounts and address verification systems, create realistic test identities using our PESEL, NIP, REGON and IBAN Generator.
Frequently Asked Questions (FAQ)
What is the Circuit Breaker pattern?
A circuit breaker (such as Resilience4j or Polly) monitors remote calls. If downstream failure rates exceed a threshold (e.g., 50% timeouts over 10 seconds), the circuit opens: subsequent calls fail fast immediately without making network calls, allowing the degraded service to recover while returning cached fallback responses.
How do I simulate DNS resolution failures?
Use local DNS mapping (such as modifying /etc/hosts or CoreDNS configuration in Kubernetes) to point the downstream domain at a non-routable documentation address (192.0.2.1, TEST-NET-1), which simulates connection timeouts, or configure the resolver to return NXDOMAIN or not respond at all. Verify that the application handles lookup errors and slow resolution without crashing.
Can chaos testing be performed safely in production?
Yes, but only after architectures have matured through automated chaos testing in staging. The Principles of Chaos Engineering recommend running experiments in production, but with a minimized blast radius. Start small (e.g., 1% of canary traffic), during business hours when engineers are available to respond, and with a clear way to stop the experiment immediately.
References & Official Sources
- Principles of Chaos Engineering
- tc-netem(8) - Linux manual page
- Shopify Toxiproxy - repository and documentation
- Chaos Mesh documentation
- Nygard, M. T. (2018). Release It! Design and Deploy Production-Ready Software (2nd ed.), Pragmatic Bookshelf - Circuit Breaker and Bulkhead patterns.