Overview
At 01:47 the payment channel’s callbacks started failing. Not a full outage — intermittent: seven or eight out of ten succeeded, the remaining two or three timed out on connect. Egress QPS on the application was flat, node CPU, memory and bandwidth were all normal, ss on the hosts showed only a few hundred TIME_WAIT sockets, and ephemeral port usage was sparse.
The on-call engineer’s first instinct was that the counterparty’s endpoint was flapping. A phone call settled that: their ingress traffic was normal, and no other merchant reported problems in the same window. Second instinct: network jitter. The packet capture showed SYNs going out with no reply. A SYN with no reply means the packet never even reached their door — so at which step was it dropped?
The answer was the cloud NAT gateway’s SNAT port pool. Four egress EIPs, more than twenty thousand long-lived connections, all aimed at the same third-party domain, and the pool had long since run dry. New connections couldn’t get a source port and were dropped outright by the gateway, which is exactly what “SYN goes out, nothing comes back” looks like in a capture.
What makes this class of failure nasty isn’t the fix — it’s the misdiagnosis. It looks like network jitter, like an unstable counterparty API, like a badly configured application connection pool. It looks like everything except “not enough ports”. And once you misdiagnose it as host-side port exhaustion, you go change ip_local_port_range, enable tcp_tw_reuse, bump nf_conntrack_max — all wasted effort, because you’re editing the wrong table.
This article breaks the troubleshooting logic down: the cloud has three distinct port/connection tables, and each one looks different and is observed differently when it fills up; which traffic pattern punches through a gateway’s port pool first; and the five decisions I landed afterwards — egress layering, expansion order, connection lifecycle governance, per-destination port watermark monitoring, and architectural fallback.
If you run microservices in the cloud and any one of your scenarios needs a fixed egress IP (third-party allowlists, reconciliation, payment callbacks, external API auth), the traps in this article will most likely find you too. For the host-side network parameter tuning, see Related: Linux Network Stack Tuning — but keep in mind: that article solves host-side problems, this one is about the gateway side, and neither substitutes for the other.
1. Sort Out the Three Port Tables in the Cloud
Most people hear “port exhaustion” and think of the host. Along the cloud egress path there are actually three independent layers of connection state; when any one of them fills up, the symptom is the same “can’t connect”, but the remedy is completely different.
Business process
└── ① Local ephemeral ports (ip_local_port_range) + ② Local conntrack
└── ③ Cloud NAT gateway SNAT port pool (attached to the EIPs)
└── Public destination address
Layer 1: Local ephemeral ports
Linux assigns source ports to outbound connections from 32768-60999 by default, which is a bit over twenty-eight thousand. The defining property of this pool: it’s bound to the destination. For a single destination IP + destination port pair, you can consume at most the number of ports in that range. So one host talking to one backend has a theoretical ceiling of 28k, minus whatever other connections are already using.
Layer 2: Local conntrack
The connection tracking table. nf_conntrack_max varies widely across distributions and kernel versions; cloud vendor images commonly ship 65536 to 262144. A full table shows up as nf_conntrack: table full, dropping packet flooding the kernel log while new connections are dropped outright.
Layer 3: The cloud NAT gateway’s SNAT port pool
This is the most easily overlooked layer. A private address reaching the public internet must be source-NATed at the gateway into the EIP’s address plus a source port. That source port pool is managed by the cloud vendor’s gateway implementation and has nothing to do with your hosts.
Vendors quote the numbers differently, but the structure is similar:
| Vendor / Product | Ports per public IP | Concurrency accounting | Spec ceiling | Notes |
|---|---|---|---|---|
| Azure NAT Gateway | 64,512 | 50,000 concurrent per IP to a single unique destination, 2 million in total | Up to 16 public IPs | Idle timeout defaults to 4 minutes and cannot be set lower |
| Tencent Cloud public NAT gateway | 55,000 (calculated as 55000 × number of EIPs) | One pool per protocol + destination IP + destination port | See product specs | Port allocation failures have a dedicated drop metric |
| Huawei Cloud NAT gateway | Carried by the EIP | The spec determines maximum SNAT connections: small 10k, medium 50k, large 200k, extra-large 1M | Up to 20 EIPs per SNAT rule | Throughput is bounded by EIP bandwidth; the spec does not affect DNAT performance |
The most important column in that table isn’t “ports per IP”, it’s the “concurrency accounting” column: the port pool is partitioned per destination IP:port, not shared as one global pool.
In plain terms: your gateway may still have 70% of its total concurrency free, but as soon as one business line concentrates on a single third-party domain, that one destination pool can already be 100% full. The aggregate connection metric looks perfectly healthy while the business times out intermittently.
That is exactly where we hit the wall. Four EIPs against one third-party domain gives 4 × 55000 = 220,000 usable ports, and actual business connections hovered around twenty thousand — headroom to spare on paper. But those twenty thousand were almost entirely long-lived connections that never get reclaimed, and on top of that short-lived connections still held ports in TIME_WAIT on the gateway side. At peak, occupancy for that single destination broke past 90% and new connections started failing to acquire a port.
Symptom comparison across the three layers
Only by putting all three side by side can you decide where to look:
| Dimension | Local ephemeral port exhaustion | Local conntrack full | Gateway SNAT pool exhaustion |
|---|---|---|---|
| Blast radius | A single instance | A single instance | Every instance behind the same NAT |
ss -tan on the host | ESTAB/TIME_WAIT toward the destination approaching the port range | Many connections, kernel log spamming table full | Looks clean, connection count far below port count |
| Kernel log | Nothing notable | nf_conntrack: table full, dropping packet | Nothing (it isn’t your machine) |
| Capture signature | No SYN leaves the host | SYN leaves but is dropped locally | SYN sent, no SYN-ACK, no RST |
| Key metric | ip_local_port_range utilisation | nf_conntrack_count / max | Gateway-side port allocation failure count |
| Typical trigger | High-concurrency short connections from a single host | Heavy traffic + long timeouts | Many instances sharing a few EIPs, same destination |
| Fix | Widen the port range, reuse connections, split destinations | Grow the table, cut timeouts, reduce long-lived connections | Add EIPs, split the egress, cut connection counts |
Walk that order when troubleshooting: first confirm whether only one machine is affected (single host → layers 1 and 2). If multiple machines fail at the same time and all talk to the same destination, jump straight to layer 3. That one check saves an hour of pointless debugging.
2. Five-Minute Triage: From Metrics to Packet Capture
Step 1: Look at gateway metrics first, not the host
Every cloud NAT gateway exposes SNAT connection metrics, just under different names. Azure has SNAT Connection Count (splittable into attempted / failed) and PacketDropCount; Tencent Cloud exposes port-allocation-failure drops; Huawei Cloud shows an SNAT connection curve in its monitoring. The common thread: find a “failure”-dimension metric instead of staring at total connections.
Total connections alone produces the wrong conclusion — “only 30% used, so it can’t be the gateway”. I’ve watched more than one team circle that drain for two days.
# Triage order (pseudo-code; substitute the metric names for your cloud)
1. Gateway total SNAT connections → approaching the spec ceiling?
2. Gateway port allocation failures / drops → is it > 0 (the key signal)
3. Gateway bandwidth / packet loss → rule out bandwidth saturation (a different failure type)
4. Host-side conntrack and ephemeral ports → rule out the host
If item 2 is non-zero during the incident window, you’re basically done — it’s the port pool. If item 2 is zero but the bandwidth curve is pinned at the ceiling, that’s bandwidth contention, not ports. The two call for completely different handling, so don’t change them together.
Step 2: Apply process of elimination on the host side
Host-side commands are for exclusion only, never for locating the gateway:
# 1. How many connections are holding ports toward the destination (ESTAB + TIME_WAIT)
dest=203.0.113.10 # replace with the real destination IP
ss -tan dst "${dest}" | awk 'NR>1 {print $1}' | sort | uniq -c
# 2. Local ephemeral port range; most distributions default to 32768-60999, roughly 28k ports
sysctl net.ipv4.ip_local_port_range
# 3. Local conntrack watermark
if [ -r /proc/sys/net/netfilter/nf_conntrack_count ]; then
echo "conntrack $(cat /proc/sys/net/netfilter/nf_conntrack_count)/$(cat /proc/sys/net/netfilter/nf_conntrack_max)"
else
echo "nf_conntrack not loaded"
fi
# 4. Confirm the packet really leaves this machine, and who the next hop is
ip route get "${dest}"
How you read step 1 matters: if the host’s ESTAB + TIME_WAIT toward that destination is far below the ephemeral port count, and multiple machines hit the same timeout together, then host ports are not the bottleneck — go check the gateway. Conversely, if a single host is pegged at 28k, fix local connection reuse first.
Step 4 gets skipped a lot. Inside a VPC the default route’s next hop is the subnet gateway, and you won’t see the NAT gateway’s ID in ip route get output. That step only proves the packet left — it doesn’t prove it went through the NAT you happen to be looking at. One VPC can host several NAT gateways (Tencent Cloud allows up to 3 per VPC), and a subnet route points at exactly one, so you can only read that one’s metrics. Reading the wrong instance yields “the metrics are fine, so it isn’t NAT” — I’ve stepped in that hole myself.
Step 3: Confirm with a capture which hop drops it
# Capture on the failing instance; you'll see SYNs go out with no SYN-ACK and no RST
sudo tcpdump -ni eth0 -c 200 "tcp and host ${dest} and port 443" -tttt
Three packet behaviours map to three root causes:
- SYN only, no SYN-ACK, no RST: the packet is silently dropped somewhere in the middle. Gateway port allocation failure looks exactly like this.
- RST immediately after the SYN: the peer is alive but refuses the connection (port closed, rate-limited, blocked by a firewall).
- Not even the SYN leaves: it’s stuck locally; check conntrack and ephemeral ports.
Capture the first pattern and stop fiddling with the host.
3. Postmortem Timeline: 70 of 90 Minutes Spent Heading the Wrong Way
Afterwards I rebuilt the on-call log minute by minute. That table is worth more than any conclusion — it shows not “how we fixed it” but “how we burned seventy percent of the time in the wrong direction”.
| Time | Action | What we believed at the time | What was actually happening |
|---|---|---|---|
| 01:47 | Callback failure alert (8% over 5 minutes) | Assumed an application-side anomaly | Port pool occupancy already above 90% |
| 01:52 | Contacted the channel provider | Their ingress normal, no other merchant affected | The peer really was fine |
| 01:58 | Packet capture | SYNs only, no SYN-ACK, no RST | Enough evidence to localise it, but read as “packet loss” |
| 02:05 | Opened a cloud vendor ticket | Suspected backbone jitter | Ticket queued while the direction was already off |
| 02:10 | Checked host conntrack and ephemeral ports | conntrack 12%, host port usage 3% | Both host layers excluded — this was the moment to turn to the gateway |
| 02:18 | Opened NAT gateway monitoring | Total connections 31% | Nearly misjudged a second time as “the gateway is fine” |
| 02:21 | Switched dimension, found the port allocation failure metric | Non-zero and climbing throughout the incident | Root cause located, 34 minutes gone |
| 02:26 | Interim mitigation: added 2 EIPs and synced the allowlist | — | Port pool expanded by roughly 50% |
| 02:38 | Failure rate back under 0.5% | — | Service recovered |
| 03:30 | Postmortem | — | Conclusion: the governance order was wrong, not the capacity |
Get any one of the three decision points right and the damage halves:
- “SYN with no response” should immediately suggest a middlebox. No reply at the TCP layer means the problem isn’t at either end.
- When both host layers are healthy and multiple instances fail together, turn to the gateway immediately. This one cost 8 extra minutes.
- Total connections aren’t the signal; failure counts are. This one cost 3 extra minutes and nearly produced the opposite conclusion — “not a port problem”.
4. The Root Cause Isn’t “Not Enough Ports” — It’s Connections That Never Get Reclaimed
Once the port pool was identified, the team’s first instinct was “add EIPs”. I pushed back this time, because a quick calculation shows that adding IPs only buys delay.
Connection count is amplified by replicas × pool ceiling
The service in question was a mixed Spring Cloud + Go stack: 28 replicas, each holding up to 400 connections to the same third-party domain. Watch the multiplication:
28 replicas × 400 connections = 11,200 long-lived connections
plus three different ports on the same domain (443 / 8443 / 9443)
≈ 33,600
The pool ceiling for a single destination IP:port is 4 × 55,000 = 220,000, which looks sufficient. The problems are:
- At peak, HPA scaled replicas past 40 and the connection count rose linearly along with it — scaling out actually pushed the port pool tighter. This is the most counter-intuitive part. Traffic up 40%, connections up 40%, but the pool is a constant.
- These connections are application-level long-lived connections that nobody closes. The gateway’s idle timeout only reclaims connections with genuinely no traffic, and with a business heartbeat every 30 seconds the connection is never judged idle.
- The short-connection side (HTTP calls from reconciliation jobs) also holds ports in
TIME_WAITat the gateway, competing for the same pool.
Stack all three and, at peak, port occupancy for that single destination burst past 90% and new connections began to fail.
Why ss on the host looked so clean
This is the most deceptive part, and the reason we lost an extra 20 minutes. Host-side TIME_WAIT is a Linux kernel state with a fixed reclaim cadence (on the order of 60 seconds); once a connection crosses the gateway, the gateway keeps its own session table whose reclaim cadence is set by its own implementation and timeout configuration. Different tables, different cadences.
Three consequences:
- Host-side
ssonly answers “do I still need this port”, not “is the gateway still holding it”. - During a short-connection storm, host
TIME_WAITpiles up and drains fast, self-healing within seconds; the gateway side can lag by tens of seconds, so its instantaneous occupancy is several times higher. - The easiest wrong turn: seeing a clean host, you go tune host kernel parameters, and end up paying for the gateway’s gaps the whole time.
| Aspect | Host | Cloud NAT gateway |
|---|---|---|
| Who maintains state | Host kernel conntrack | The cloud vendor gateway’s session table |
| Reclaim cadence | Fixed, TIME_WAIT around 60 seconds | Set by gateway implementation and timeouts, usually longer |
| Visibility | ss / /proc expose per-entry detail | Metrics only, no per-entry detail |
| Port pool partitioning | Per destination IP:port | Per destination IP:port, but shared across instances |
So “are there enough ports” can only be answered from gateway metrics; extrapolating from host connection counts points the wrong way.
A counter-intuitive measured comparison
Before and after the rework I ran a comparison in the load-test environment: a fixed 2000 QPS at the same destination, changing only the connection reuse policy:
| Scenario | Peak concurrent connections | Peak port occupancy | New connection failure rate | P99 connect latency |
|---|---|---|---|---|
| New connection per request (no pooling) | About 4,100 | 92% | 3.1% | 310ms |
| Per-process pool, ceiling 400, IdleTimeout 5 minutes | About 1,600 | 36% | 0 | 42ms |
| Same + reclaim after 90s idle + liveness probe every 30s | About 1,250 | 28% | 0 | 39ms |
The takeaway isn’t the platitude “bigger pools are better” — it’s: derive the ceiling from the replica count, don’t eyeball a number per replica. The more common engineering mistake is giving each replica a very respectable ceiling of 500, then multiplying by 28 replicas and puncturing the pool.
5. Five Production Decisions
Decision 1: Egress must be layered — don’t run the world through one NAT
The default state of most cloud accounts is: one NAT gateway per VPC, every subnet route pointing at it, all egress traffic crammed together. Convenient, and a latent landmine.
What I do now is split egress by traffic character, at minimum into two classes:
| Egress class | Traffic it carries | Fixed IP required | Port watermark monitoring | Dedicated NAT |
|---|---|---|---|---|
| Controlled egress | Third-party allowlisted APIs, payment callbacks, reconciliation, external auth | Yes — peers allowlist by IP | Mandatory, per destination | Yes |
| General egress | Dependency downloads, image pulls, log shipping, non-allowlisted internal calls | No | Totals only | Yes (may share a bandwidth package with controlled egress, but a separate NAT instance) |
The rationale is practical: the controlled egress pool gets eaten slowly by long-lived connections, and its failures are business-visible failures (money not collected, ledgers that don’t balance); general egress failures usually just mean slowness. Separate the two physically and a short-connection storm on general egress can’t reach controlled egress.
The cost is maintaining two sets of subnet routes. The approach: give workloads that need a fixed egress their own subnet (or their own node pool), with the route pointing at the “controlled NAT”. In K8s this amounts to node affinity for a class of workloads, or simply using Cilium’s Egress Gateway to pin egress nodes — the latter can go as granular as a namespace or even a Pod label. For the configuration details see CiliumEgressGatewayPolicy in the official docs.
On the order-fulfilment path of a mobility project, that’s exactly how I split it: the services authenticating against external partners got their own NAT and set of EIPs, and everything else went through the shared egress. Later the shared egress was saturated twice by image-pull storms; controlled egress was never affected once.
Decision 2: The expansion order must be “cut connections first, add IPs later”
Adding EIPs is the most intuitive action and also the most expensive one. Expensive not in money, but in coordination cost:
- Every new IP has to be allowlisted in the peer’s system, and some third parties run on tickets where one change takes two days;
- If the peer rate-limits per source IP, more IPs make you look like “several different callers” to them, and in some cases you’re actually more likely to hit per-IP limits;
- The egress IP inventory is part of security audit, and changes go through approval and filing; under China’s MLPS wording, every added egress IP may require supplementary documentation.
So the expansion order I settled on is:
- Cut the connection count first: derive the pool ceiling from the replica count and set a hard cap such as
MaxConnsPerHost(many language clients have no total cap by default, only an idle connection cap). - Then raise the reuse ratio: confirm HTTP/1.1 keep-alive is on, and that gRPC multiplexes over one connection instead of dialling per RPC; convert chatty short calls into batch APIs (fetch 100 records in one call instead of 100 calls of one record — this change usually pays more than any network tuning).
- Then shorten the holding time: application-level idle reclaim plus liveness probing, so connections no longer in use enter the close path quickly and return their ports to the pool.
- Only then add EIPs, and after adding them sync the peer allowlist and the baseline of your port watermark monitoring.
That order isn’t dogma: if after steps 1 to 3 the watermark is still above 80%, capacity genuinely is short and adding IPs is correct. But skip the first three and, six months from now, you’ll be in the same meeting about the same hole.
Three hidden constraints on the peer side
Egress expansion is never “two clicks in the cloud console” — half the pain lives in the counterparty’s systems:
- Allowlist lead time. Some partners run tickets, others need a change process on the contract addendum: same-day at best, three to five business days at worst. Which means the schedule for egress IP expansion must be estimated against the peer’s slowest process, not against your cloud console time. I now write this into the integration document during the access review.
- The rate-limiting dimension isn’t necessarily total QPS. Plenty of third parties limit per source IP. Add 4 IPs and capacity looks doubled, when in fact each IP’s quota may be far below the original shared allowance, leaving the total flat or even worse. Before adding any IP, confirm with the peer whether limits apply per IP or per merchant entity.
- The egress IP inventory is an audit object. Under MLPS, egress IPs count as network-boundary assets and inventory changes must be recorded. In one audit I was asked to explain “why the egress IPs went from 2 to 8 within six months”; there were no change records, so I had to dig through tickets on the spot. Since then, every egress IP addition or removal goes into a change ticket, with a list maintained in configuration management.
Together those three say one thing: most of the cost of this problem isn’t the technical design, it’s the coordination process. So treat “the number of egress IPs will grow” as a default assumption at design time, instead of discovering during an incident that every expansion requires cross-company coordination.
Decision 3: Connection lifecycle belongs in code, not in the gateway’s safety net
Gateway-side timeouts are a safety net, not a design. Azure NAT’s idle timeout can’t be set below 4 minutes, and you cannot lean on it to “reclaim useless long-lived connections” — as long as the business sends heartbeats, the connection is never idle.
So the lifecycle has to be owned by the application. In Go, a configuration that can withstand port-pool pressure looks roughly like this:
transport := &http.Transport{
// Derived from replica count: per-replica ceiling × max replicas ≤ port pool / destinations × 0.6
MaxConnsPerHost: 120, // hard cap; requests queue beyond this instead of dialling forever
MaxIdleConnsPerHost: 80, // resident idle connections, avoiding rebuilds on every call
MaxIdleConns: 400, // global idle ceiling, so several destinations don't add up per replica
IdleConnTimeout: 90 * time.Second, // return the port after 90 seconds idle
DialContext: (&net.Dialer{
Timeout: 3 * time.Second,
KeepAlive: 30 * time.Second, // application-level liveness, catching dead connections early
}).DialContext,
TLSHandshakeTimeout: 3 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
client := &http.Client{
Transport: transport,
Timeout: 8 * time.Second, // safety net; don't let a single request hang forever
}
MaxConnsPerHost is the line that separates “a usable pool” from “a pool that punctures the pool”. It makes requests beyond the ceiling queue locally, trading a little tail latency for a predictable connection count. In an egress-constrained environment that trade is almost always worth it.
Client knobs across runtimes
The same governance idea lands on very different parameter names per runtime. The table below is one I’ve looked up, tripped over and confirmed myself:
| Runtime / client | Hard connection cap | Idle reclaim | Liveness | Trap in the defaults |
|---|---|---|---|---|
Go net/http | MaxConnsPerHost | IdleConnTimeout | Dialer.KeepAlive | The default 0 means unlimited — effectively no cap at all |
| Java OkHttp | Dispatcher.maxRequestsPerHost | ConnectionPool keepAlive | HTTP/2 pingInterval | 5 idle connections by default, but total connections are unconstrained |
| Java Apache HttpClient | maxConnPerRoute / maxConnTotal | validateAfterInactivity | — | Defaults of 2 / 20, silently inflated by many frameworks |
Python requests | Determined by urllib3 PoolManager’s pool_maxsize | pool_maxsize + session reuse | — | Not reusing a Session means a new connection on every call |
| gRPC (Go) | Multiplexed over a single connection | keepalive.ClientParameters | Time / Timeout | Saves ports, but one stuck connection stalls every stream |
The Python row deserves a note: requests.get() creates a fresh temporary session on every call and closes the connection right after, which from the pool’s point of view is “one port per request”. Reuse a module-level Session and the connection count drops by an order of magnitude — two lines of code. Changes like “two lines halve the port usage” beat any architectural rework on cost-effectiveness.
On the Java side, if you use OkHttp, note that Dispatcher limits concurrent requests per host, not connections; that’s a different dimension from the pool ceiling, and configuring only one isn’t enough:
// OkHttp: pool of 100 connections, idle reclaim after 5 minutes, plus a per-host concurrency cap
ConnectionPool pool = new ConnectionPool(100, 5, TimeUnit.MINUTES);
Dispatcher dispatcher = new Dispatcher();
dispatcher.setMaxRequests(600); // global concurrent requests
dispatcher.setMaxRequestsPerHost(120); // concurrent requests per host; anything beyond queues
OkHttpClient client = new OkHttpClient.Builder()
.connectionPool(pool)
.dispatcher(dispatcher)
.build();
Tune the host-side TCP keepalive parameters while you’re at it, so dead connections get cleaned up sooner:
# Start probing after 10 minutes of no data, once every 30 seconds, 3 failures marks the connection dead
sysctl -w net.ipv4.tcp_keepalive_time=600
sysctl -w net.ipv4.tcp_keepalive_intvl=30
sysctl -w net.ipv4.tcp_keepalive_probes=3
# Persist, so it survives a reboot
cat >> /etc/sysctl.d/99-egress.conf <<'EOF'
net.ipv4.tcp_keepalive_time=600
net.ipv4.tcp_keepalive_intvl=30
net.ipv4.tcp_keepalive_probes=3
EOF
sysctl --system
Note that tcp_keepalive_time defaults to 7200 seconds (two hours), which means a connection that’s already dead can lie in the table for two hours — on a port-constrained egress that’s two hours of free occupancy. Dropping it to 10 minutes is, I think, the highest return-on-effort change I’ve made.
One more thing: don’t casually enable net.ipv4.tcp_tw_reuse. It only helps the active opener reuse TIME_WAIT sockets, and it bypasses some timestamp protection; when the gateway port pool is the bottleneck, no amount of host-side reuse saves the gateway. Confirm which layer the bottleneck is actually at with the methods above before flipping it.
Decision 4: Monitor the watermark per destination, not just the total
This is the area I changed most after the incident. The old dashboard had a single “total egress connections” panel, sitting at 30% year-round, all green, and nobody ever looked twice. What actually decides success or failure is occupancy for an individual destination.
There are two collection sources; use them together:
Source 1: cloud gateway metrics. Per NAT instance, watch SNAT connections, port allocation failures and drops. This layer only shows “the gateway as a whole” and has no destination dimension, but it’s the only one that emits the “allocation failed” signal.
Source 2: per-destination aggregation on the node. Run a small collector on each node, aggregate connections by (destination IP, destination port) and expose them as Prometheus metrics:
# Coarse per-node aggregation (for troubleshooting; in production use eBPF or a custom exporter reporting every 15s)
ss -tan state established | awk 'NR>1 {print $5}' \
| sed 's/:[0-9]*$//' | sort | uniq -c | sort -rn | head -20
With per-destination time series in place, alerting rules can finally say something meaningful:
# Per-destination port watermark alert (illustrative: metrics exposed by a custom egress exporter)
groups:
- name: egress-port-watermark
rules:
- alert: EgressPortPoolHigh
# connections to one destination / total destination port pool available on that egress
expr: |
sum by (egress, dst) (egress_conn_active)
/ on(egress) group_left
sum by (egress) (egress_port_pool_size)
> 0.6
for: 10m
labels:
severity: warning
annotations:
summary: "Port pool usage on egress {{ $labels.egress }} toward {{ $labels.dst }} exceeds 60%"
runbook: "Check whether connections are growing linearly with replicas, then decide: cut connections or add EIPs"
- alert: EgressPortAllocFailure
# Gateway-side port allocation failures; any non-zero value deserves a look
expr: increase(egress_snat_port_alloc_failed_total[5m]) > 0
for: 2m
labels:
severity: critical
The 60% threshold isn’t arbitrary: the buffer between 60% and 100% has to cover the whole “localise → canary the pool change → observe it take effect” sequence, typically 30 to 60 minutes. Alert at 90% and, by the time the page arrives, the business is already failing.
The alerting data behind this comes from an alert pipeline optimisation I did on another project, where delivery is down to the 5-second range. The point here isn’t delivery speed — it’s that this metric deserves waking someone up immediately, because the failure it corresponds to is direct business failure, not a resource sitting high.
Decision 5: Architectural fallback — Egress Gateway for fixed egress, not luck
If the business needs “a stable, predictable egress IP” long term, don’t let it depend on “whichever EIP the gateway happens to translate into”. In K8s, Cilium’s Egress Gateway is the better answer: route egress traffic from a given namespace or Pods with a given label to fixed gateway nodes, SNAT out through a fixed IP, and pair it with a node pool that guarantees those gateway nodes have enough egress bandwidth and port pool.
Two practical details are worth recording:
- Gateway nodes must be dedicated. Don’t co-locate business Pods and egress gateway nodes on the same machines, or egress and business traffic will fight over bandwidth and conntrack, and during an incident you won’t be able to tell whose fault it is.
- Egress Gateway is not “free fixed IPs”. All traffic through it concentrates onto a few nodes, so port pressure shifts from “spread across dozens of nodes” to “concentrated on three” — which in turn requires you to get the ephemeral port range and connection reuse right on the node side. Otherwise you’ve merely moved the gateway’s bottleneck onto the nodes.
In that K8s migration of 120+ microservices, the decision I’m most grateful for was carving out the services that needed fixed egress ahead of time and doing node pool isolation as part of the migration. It proved to save at least two rounds of cross-team coordination afterwards: without that isolation, every peer allowlist change would have triggered another full-gateway audit.
The NAT gateway itself goes down too — don’t forget egress availability
Beyond the port pool there’s a blunter failure mode: the NAT gateway itself becomes unavailable. Then it isn’t intermittent new-connection failures, it’s the entire egress path down. Clouds differ on NAT gateway deployment granularity (some deploy per availability zone, some per VPC), so find out which layer your product sits on before you choose it, because that determines whether the blast radius is “one subnet” or “the whole VPC”.
My approach has two parts:
- Active/standby NATs with route switching. Subnet routes point at the primary NAT by default; when it misbehaves, switch the routes to the standby. The switch itself is a minutes-level operation, but the source IP changes afterwards, so the peer allowlist must register both sets of EIPs — otherwise incident handling turns into an exercise in cross-company coordination.
- Bring egress availability into monitoring too, read alongside the port watermark. Three curves — gateway-side datapath availability (Azure exposes a dedicated DatapathAvailability metric), egress-direction packet loss, and “egress connection establishment success rate” — any one of them dipping should alert.
There’s also one easily missed coupling: if several EIPs sit in the same shared bandwidth package, a peak on one business line can eat the whole package’s bandwidth and the other egress paths start dropping packets along with it. Port pools are partitioned per destination, bandwidth is shared per package — the two resources are sliced along different dimensions, so govern them separately. Don’t expect one change to fix both problems at once.
6. Short-Connection Storms and Retry Amplification: The Other Way to Puncture the Pool
Long-lived connections are a slow knife; a short-connection storm is a fast one. Both compete for the same port pool, but the remedies are entirely different.
Retries are a connection amplifier
During the incident the gateway’s new-connection rate went from 1,200/s to 4,800/s. Broken down, about 68% of it came from reconciliation job retries: upstream saw a timeout and re-sent under a “retry 3 times” policy, and every re-send was a new connection and a new port.
That’s the textbook positive feedback loop: not enough ports → connect timeout → application retries → more connections → even fewer ports.
| Baseline failure rate | Retries | Effective connection amplification | Extra pressure on the pool |
|---|---|---|---|
| 5% | 2 | 1.05 | Negligible |
| 10% | 3 | 1.33 | Moderate |
| 30% | 3 | 2.19 | High |
| 50% | 5 | 3.88 | Extreme — will lock the pool up outright |
So retry policy has to be designed together with egress capacity. Three hard rules:
- Retry idempotent requests only, and disable non-idempotent retries by default. For reconciliation and payment APIs, configure “query” and “submit” separately, or one mistaken retry becomes a duplicate record.
- Backoff must carry jitter. Fixed-interval retries send dozens of replicas into the same millisecond, creating a fresh peak.
- Always pair it with a circuit breaker. Once consecutive failures hit the threshold, fail fast instead of stuffing more connections into a pool that’s already full.
// Minimal jittered backoff (illustrative; use an off-the-shelf library for the circuit breaker)
func backoff(attempt int) time.Duration {
base := 200 * time.Millisecond << attempt // 200ms, 400ms, 800ms...
jitter := time.Duration(rand.Int63n(int64(base / 2))) // add 0-50% randomness to break up peaks
return base + jitter
}
// Circuit-breaker rule: failure rate > 50% with more than 20 samples in a 5-second window → reject outright for 30 seconds, no new dials
Batching pays more than any network tuning
The same reconciliation logic used to do “one query per record”. After converting it to “one query per 100 records”:
| Metric | Before | After |
|---|---|---|
| Requests per round | 12,000 | 120 |
| Peak new-connection rate | About 900/s | About 40/s |
| End-to-end time per round | 4m 20s | 38s |
| Port occupancy (assuming 60s residency) | About 54,000 | About 2,400 |
What’s worth remembering here isn’t the platitude “batching is better”, it’s that the gain must be accounted in ports, not in QPS. 12,000 requests spread over a minute is only 200/s, invisible on a graph; converted to port occupancy it’s in the fifty-thousand range, a quarter of a small EIP pool gone in one move.
Egress bandwidth and egress ports are two different things
| Dimension | Symptoms when saturated | Metric to watch | Remedy |
|---|---|---|---|
| Port pool | All new connections fail; old ones still work | Port allocation failure count > 0 | Reduce connections / add EIPs |
| Egress bandwidth | Connects but slowly, heavy retransmits, partial timeouts | Bandwidth curve pinned at the ceiling, packet loss rising | Add bandwidth / split egress / cut transfer volume |
At the time of the incident, egress bandwidth was only at 40%. Had we gone off to add bandwidth based on “not enough bandwidth”, we’d have spent the money and solved nothing. There’s exactly one deciding signal: is the port allocation failure metric non-zero?
7. How to Size Capacity: A Formula You Can Copy Directly
Don’t judge “is it enough” by feel. Run this expression and you have an answer in five minutes:
Port pool per destination = number of EIPs × ports per IP (55,000 or 64,512)
Required peak concurrency = replicas × per-replica connection ceiling + peak short-connection rate × gateway TIME_WAIT residency in seconds
Watermark = required peak concurrency ÷ port pool per destination
Assume a set of real numbers:
- 4 EIPs at 55,000 each: per-destination pool of 220,000
- 28 replicas at 400 each: 11,200
- Reconciliation peak of 150 QPS of short connections, gateway-side
TIME_WAITat 60 seconds residency: 9,000 - Three destination ports each count as their own share: three ports on the same destination IP are three independent pools, so take the maximum rather than the sum
The tightest pool works out to 11,200 + 9,000 = 20,200, or 9.2%. That was the “paper number” at the time of the incident, and it looks extremely safe.
So why did it still fill up? Because the paper math missed two items:
- The replica count after HPA scaling (actual peak of 42 replicas × 400 = 16,800)
- Connections are bounded by business concurrency, not by the pool ceiling: some SDKs hold one connection per business thread, with a thread pool of 64, so the actual connection count far exceeds the semantics of that “pool ceiling” setting
Corrected: 42 × 400 = 16,800, plus 9,000 short connections, times a 1.3 safety factor for retries and liveness connections, landing around 33,500. Against a 220,000 pool that’s still a 15% watermark. But during the incident the short-connection storm drove QPS to 800, the TIME_WAIT term alone became 48,000, the total approached 65,000, and with the gateway’s own state-reclaim lag on top, failures appeared.
Takeaway: when sizing, don’t treat the “configured connection pool ceiling” as the real connection count — look at connections actually established. In many language clients those two aren’t equal at all.
8. Actually Collecting Per-Destination Metrics
Decision 4 says to watch the destination dimension, and in practice you hit an awkward problem: cloud gateway metrics don’t offer that granularity. So you have to collect it yourself on the node side. I’ve used all four approaches below in production, at very different costs:
| Collection method | Granularity | Additional overhead | Use case | Trap |
|---|---|---|---|---|
| Cloud gateway metrics | Whole NAT instance | None | Deciding “did port allocation fail” | No destination dimension |
ss polling script | Destination | Moderate; noticeable CPU with many connections | Ad-hoc troubleshooting | High-frequency collection hurts the workload; output parsing is error-prone |
Parsing /proc/net/nf_conntrack | Destination | Low to moderate | Long-term collection | Slow reads on big tables; field format shifts with kernel version |
| eBPF collection | Destination + process | Low | Production-grade long-term solution | Needs kernel support and extra maintenance |
I finally settled on “eBPF primary + conntrack as a backstop”: eBPF hooks the connect and close events and counts incrementally, which is precise enough; conntrack parsing runs every 5 minutes to reconcile, preventing dropped eBPF events from slowly skewing the numbers.
// Minimal conntrack aggregation (illustrative: counts established connections only, summed per destination IP)
func topDst() map[string]int {
f, err := os.Open("/proc/net/nf_conntrack")
if err != nil {
return nil
}
defer f.Close()
counts := map[string]int{}
s := bufio.NewScanner(f)
s.Buffer(make([]byte, 0, 64*1024), 1024*1024)
for s.Scan() {
line := s.Text()
if !strings.Contains(line, "ESTABLISHED") {
continue // established connections only; TIME_WAIT is counted separately
}
for _, field := range strings.Fields(line) {
if strings.HasPrefix(field, "dst=") {
counts[strings.TrimPrefix(field, "dst=")]++
}
}
}
return counts
}
High cardinality is this monitoring stack’s biggest enemy
Using the destination IP as a label blows Prometheus up easily: egress faces the public internet, destination IPs can number in the tens of thousands, one time series per IP, and memory is gone within days.
Three constraints; miss any one and it breaks:
- Keep the Top N only. Sort by connection count, keep the top 50 destinations, fold the rest into
other. - Prefer aggregating by domain or CIDR. What the business actually cares about is “the pool talking to third-party A”, not one specific IP; merge by resolution result or by prefix and cardinality drops by two orders of magnitude.
- Keep process and Pod names out of labels. Cardinality multiplies by ten immediately for zero benefit — governance actions are issued per destination, not per Pod.
# Prometheus relabel: keep only the destinations you care about, fold the rest into other, and cap the time series count
- job_name: egress-exporter
metric_relabel_configs:
- source_labels: [dst]
regex: "(203\\.0\\.113\\.(10|11)|198\\.51\\.100\\.5)"
target_label: dst_bucket
replacement: "tracked"
- source_labels: [dst_bucket]
regex: "^$"
target_label: dst_bucket
replacement: "other"
Set the scrape interval to 15 seconds and configure alerts with for: 10m to smooth things out, so a single scrape cycle’s wobble doesn’t page someone directly. I’ve honed this stack on another project’s alert pipeline, where end-to-end delivery reaches the 5-second range; but what really matters here isn’t delivery speed, it’s whether this metric value is worth paging someone immediately — port allocation failures mean direct business failure, so it is.
9. Rollout Order and Rollback
Reworking anything port-related carries inherent risk: changing the connection pool can crush throughput, changing egress routes can cut the traffic off. So I ordered the work from low to high risk, with every step independently revertible.
| Step | Action | Expected effect | Rollback | Observation window |
|---|---|---|---|---|
| 1 | Add monitoring: per-destination connection counts, gateway port allocation failures | Data to look at | Delete the Prometheus rules | 7 days |
| 2 | Cap the application connection pool (canary one service first) | Peak connection count down 30-50% | Revert the config to the previous version | 3 days |
| 3 | Idle reclaim + liveness probe + lower tcp_keepalive_time | Shorter port holding time | sysctl rollback + config rollback | 3 days |
| 4 | Layer egress by purpose, dedicated NAT for controlled traffic | Fault domain isolation | Switch the routes back (minutes) | 7 days |
| 5 | Add EIPs as the watermark dictates (sync the peer allowlist) | Pool capacity ×N | Unbind the EIPs (confirm no long-lived connections first) | Ongoing |
Step 2 is where things most easily go wrong: after adding MaxConnsPerHost, if you haven’t load-tested, requests can queue and P99 can spike. Canary one low-traffic service first and watch it for 3 days before rolling out wide. The lesson I learned here: don’t change the default pool configuration across all services at once, because tolerance for queueing differs completely — a reconciliation job can queue for a few seconds, while an external API times out after 200ms.
Step 4’s route switch happens in a low-traffic window, with the new NAT’s SNAT rules, EIPs and bandwidth all provisioned in advance and a connectivity check run through once. Switching the routes back takes minutes, but long-lived connections get torn down by the peer when the source IP changes, so keep the switch window clear of business peaks.
On-call checklist (paste it straight into the runbook)
Woken up in the middle of the night, nobody is clear-headed. So I compressed the decision logic into a seven-item checklist the on-call engineer can simply follow, with no reasoning required on the spot:
[ ] 1. Confirm the blast radius: single instance / one subnet / whole VPC
[ ] 2. Single instance → check ip_local_port_range usage, nf_conntrack_count/max, and dmesg for table full
[ ] 3. Multiple instances hitting the same destination → open NAT gateway monitoring immediately; stop looking at hosts
[ ] 4. On the gateway, check three things: total connections, port allocation failure count, egress bandwidth and drops
[ ] 5. Allocation failures > 0 → count connections per destination, and decide whether it's long-lived accumulation or a short-connection storm
[ ] 6. Stop the bleeding in order: circuit-break/rate-limit new connections first, then cut the connection count, add EIPs last
[ ] 7. 30 minutes after recovery, re-check that the watermark really came down, to avoid a second shock from retries
Item 6’s “circuit-break before scaling” is the most direct change to come out of this postmortem. Our first move during the incident was adding EIPs, and while we did that upstream retries kept amplifying the connection count; it took 12 minutes after the change to stabilise. Circuit-breaking first would have at least halved the time to stop the bleeding.
Results after the rework
Three months of before and after, on the same business line’s egress metrics:
| Metric | Before | After |
|---|---|---|
| Peak resident connections (single destination) | 20,200 | 8,600 |
| Peak port occupancy (per-destination pool) | 92% | 31% |
| Egress-related alerts per month | 7, of which 3 were P1 | 1, a plain watermark notice |
| New connection failure rate | Above 3% during peak hours | 0 |
| Egress EIP count | 4 | 6 (controlled egress only; 2 for general egress) |
Going from 4 to 6 EIPs looks like “we scaled up”, but in reality every business line’s connection count dropped below half of what it was before — those two extra EIPs serve the newly split-out controlled egress, not life support for the old pool. The order matters: fix connections first, add capacity second, otherwise you’ll keep buying time with IPs and each purchase will buy you less.
10. Every Trap I’ve Stepped In, Listed Plainly
| Trap | Symptom | Root cause | Correct approach |
|---|---|---|---|
| Misdiagnosed as host port exhaustion | ss showed few TIME_WAIT; changing tcp_tw_reuse did nothing | The bottleneck was the gateway port pool, not the host | Multiple hosts failing + same destination → go straight to gateway metrics |
| Watching only total connections | 30% total concurrency, concluded “the gateway is fine” | The pool is partitioned per destination:port | Always watch the watermark per destination |
| Scaling made things worse | Failure rate rose after HPA scaled out | Connections grow linearly with replicas; the pool is a constant | Derive the pool ceiling from the maximum replica count |
| Reading the wrong NAT instance | Monitoring said “all normal” | Several NATs in the VPC, and the subnet route pointed at another one | Confirm the next hop with ip route get; read only that instance |
| Bandwidth saturation misread as port exhaustion | 5xx rising, captures showed a mix of RSTs and silence | The symptoms look alike, the metrics don’t | Check the loss/bandwidth curves first, then the allocation failure count |
Treating tcp_tw_reuse as a panacea | No effect, plus side effects | It only affects the host as active opener and can’t bypass the gateway | Identify the layer first; don’t fiddle with kernel parameters blindly |
| Raising the idle timeout | Port occupancy didn’t drop, it rose | The longer the timeout, the longer ports are held | Keep gateway timeouts at the default or lower; leave reclamation to the application |
| Peer allowlist not synced | Added EIPs, business still failing | The peer had only allowed the old IPs | Adding IPs and changing the allowlist belong in the same change ticket |
| Shared bandwidth package eaten by neighbours | Ports fine but many timeouts | Bandwidth is shared per package, not isolated per destination | Govern egress bandwidth and the port pool separately |
| Retries locked the pool up | The incident widened and recovery dragged on | Fixed retries with no jitter and no circuit breaker | Idempotency + jittered backoff + circuit breaker, all three |
11. The Boundaries of This Approach
Applicability has to be spelled out, so this isn’t taken for a panacea:
- Short-connection-dominant workloads (many independent small requests, outbound crawling): the first bottleneck is usually not long-lived accumulation but the
TIME_WAITrate and the gateway’s state reclaim speed. What works better here is batching and rate limiting, not pool tuning. - Cases where the egress IP isn’t constrained (the peer doesn’t allowlist, or traffic goes over a private line): the least-effort answer is to give the workload its own EIP directly, or to bypass the public egress entirely with a VPC endpoint — the port pool problem then never appears.
- Cross-cloud / hybrid-cloud doubles the complexity of egress governance: port accounting differs between clouds, allowlists must be maintained on both sides, and during an incident you first have to work out which side’s gateway is at fault. Here “egress layering + freezing the fixed EIP inventory into configuration management” matters more than any tuning; for the thinking behind it see Related: Cloud-Native Network Architecture Selection.
- Dual-stack egress: first work out which layer is doing the translation. IPv6 egress doesn’t go through SNAT on many clouds, but NAT64 or an IPv6 gateway brings its own session table and quotas. Applying IPv4 pool conclusions straight to IPv6 during an incident is wrong nine times out of ten; build separate monitoring for each.
- Environments with private NAT and dedicated-line access: egress isn’t only the public path — cross-VPC and cross-datacenter traffic goes over private NAT or dedicated lines, and that layer’s connection table belongs to a different set of devices. During troubleshooting, confirm first whether this traffic actually uses the public egress, or you’ll spend half an hour hunting for a cause in the metrics of an idle gateway.
One sentence for the boundary: this method solves the class of problem where “a finite, shared egress port pool is consumed in a concentrated way”. If your egress is one-to-one (an EIP per instance), or you don’t use NAT at all, the problem shows up in a different shape and needs a different playbook.
Summary
If the postmortem had to be written in one sentence, I’d write: you didn’t run out of ports — they were diced up by an allocation scheme you couldn’t see.
Three lessons are worth keeping:
- Identify the layer before touching anything. Cloud egress has three independent tables — local ephemeral ports, local conntrack, gateway SNAT port pool. Editing the wrong table doesn’t just waste time; it costs you the stop-the-bleed window. The test is simple: only one machine failing, look at the host; several machines failing at once while hitting the same destination, look at the gateway.
- Total connections is a placebo; the per-destination watermark is the truth. The port pool is partitioned per “destination IP:port”, so any dashboard that monitors only totals will show green during an incident.
- Change the connection lifecycle before adding capacity. Many teams have never done the replicas × pool-ceiling multiplication; and one line of
MaxConnsPerHostconfiguration is often more effective than two more EIPs. Adding EIPs touches the peer allowlist and passes through audit; changing the pool takes a single canary release.
If you do only one thing, do this: drop tcp_keepalive_time from 7200 to 600, and set a hard connection cap on the application’s HTTP client. Under twenty lines combined, and the egress port pool’s watermark halves at the same business volume.
References & Acknowledgments
This article drew on the following sources while it was being written. Thanks to their authors:
- Troubleshoot Azure NAT Gateway connectivity problems — Microsoft Learn: how to identify SNAT port exhaustion, 64,512 ports per IP and the concurrency accounting, and guidance on adjusting idle timeouts
- Azure NAT gateway metrics and alerts — Microsoft Learn: definitions of SNAT connection count, total connections, dropped packets and other monitoring metrics
- Troubleshooting public NAT gateway SNAT port allocation failures — Tencent Cloud Developer Community: computing the per-destination port pool as EIP count × 55000, and the troubleshooting approach that separates host ports from the gateway port pool
- What Is NAT Gateway? — Huawei Cloud: product framing for NAT gateway specs, maximum SNAT connections, and bandwidth being determined by the EIP
- Improve network fault tolerance in AKS using TCP keepalive — Microsoft Learn: how idle timeouts and TCP keepalive work together
- Cilium Egress Gateway — Cilium official documentation: the policy model for pinning Pod egress to fixed gateway nodes and egress IPs
- Site Reliability Engineering — Google SRE team: the methodological foundation for incident severity and capacity assessment