How to Simulate an API Outage
How to Simulate an API Outage Using /etc/hosts
One of the easiest ways to simulate an API outage during testing is by modifying the
/etc/hosts file. This forces your application to resolve the API hostname
to a different IP address, allowing you to simulate connection failures or timeouts
without changing your application code.
How It Works
The /etc/hosts file overrides DNS resolution. When your application tries
to connect to an API such as:
https://api.example.com
You can redirect api.example.com to another IP address to simulate an outage.
Step 1: Open the Hosts File
Linux / macOS
sudo nano /etc/hosts
Windows
Edit the following file using Administrator privileges:
C:\Windows\System32\drivers\etc\hosts
Step 2: Simulate Different Types of Failures
Option 1 – Connection Refused
Redirect the API hostname to localhost.
127.0.0.1 api.example.com
If no service is listening on the API port (typically 443), the connection fails immediately.
Expected Behavior
- Connection refused
- Immediate failure
- Useful for testing error handling
Option 2 – Network Timeout
Redirect the hostname to an unroutable IP address.
10.255.255.1 api.example.com
or
192.0.2.1 api.example.com
Expected Behavior
- Connection timeout
- Retry logic is exercised
- Useful for resilience testing
Step 3: Flush the DNS Cache
macOS
sudo dscacheutil -flushcache
sudo killall -HUP mDNSResponder
Linux (systemd-resolved)
sudo resolvectl flush-caches
Windows
ipconfig /flushdns
Verify the Override
Verify that the hostname resolves to the IP address you configured.
ping api.example.com
or
getent hosts api.example.com
Note: nslookup may bypass the hosts file because it queries DNS servers directly.
Restore Normal Connectivity
- Remove the hosts file entry.
- Save the file.
- Flush the DNS cache again.
Failure Types
| Hosts Entry | Simulated Failure | Typical Result |
|---|---|---|
127.0.0.1 api.example.com |
Connection Refused | Immediate failure |
10.255.255.1 api.example.com |
Network Timeout | Request waits until timeout |
192.0.2.1 api.example.com |
Host Unreachable | Timeout or network unreachable |
Limitations
Modifying the hosts file only simulates network connectivity failures. It does not simulate:
- HTTP 500 Internal Server Error
- HTTP 503 Service Unavailable
- Slow API responses after a connection is established
- Malformed JSON responses
- TLS/SSL certificate errors
- Intermittent or partial failures
For these scenarios, consider using a mock API server, reverse proxy, or service virtualization
tool capable of injecting latency or returning custom HTTP responses.