# Closing a TCP port when the backend is gone

*Traefik ingress controller made field devices reboot after the service was stopped a small watcher fixed it.*

## The setup

A fleet of devices in the field keeps a long-lived TCP connection to a backend service in Kubernetes. The protocol is raw TCP, not HTTP, so it goes through Traefik as a **custom TCP route**:

```
device ──TCP──▶ cloud load balancer ──▶ Traefik entrypoint :7000 ──IngressRouteTCP──▶ backend Service ──▶ backend pod
```

- **Entrypoint:** Traefik gets one extra entrypoint per device port in its static configuration (`--entryPoints.backend7000.address=:7000/tcp`). Traefik's own `LoadBalancer` Service exposes it, with a named port (`backend7000`) as `targetPort`.
- **Route:** an `IngressRouteTCP` (Traefik's CRD for TCP routing) binds that entrypoint to the backend Service. There is no TLS or SNI to route on, so the match is a catch-all:

```yaml
apiVersion: traefik.io/v1alpha1
kind: IngressRouteTCP
metadata:
  name: backend-tcp
spec:
  entryPoints:
    - backend7000
  routes:
    - match: HostSNI(`*`)
      services:
        - name: backend
          port: 7000
```

The devices are simple. When a connect fails, they wait and retry. When a connect *succeeds* and the connection then drops right away, they read that as "the network is flaky". After a few of those in a row, some of them reboot.

## The problem

During a release, the backend is scaled to zero, upgraded and scaled up again. We expected the devices to see "can't connect" for a minute and then come back.

They didn't. They saw **connected / disconnected / connected / disconnected**, and some rebooted.

The cause was how Traefik handles a custom TCP route without a backend. An entrypoint is *static* configuration: Traefik opens the listening socket at startup, whatever routes exist. The `IngressRouteTCP` is only *dynamic* configuration that says where to send a connection once it has been accepted. On top of that, the CRD provider ran with `allowEmptyServices=true`, so the route stays loaded even when its Service has no ready endpoints. So with the backend at zero replicas:

1. the device connects,
2. Traefik **accepts** the connection on the entrypoint (the three-way handshake completes),
3. the route finds no backend, and Traefik closes the connection (FIN) almost at once (~200 ms in our capture).

To the device, that is a successful connect followed by a drop: the worst signal you can send it.

**What didn't help:**
- **Deleting the `IngressRouteTCP`:** the entrypoint keeps listening, and with no route at all Traefik still accepts the connection and then closes it.
- **Turning `allowEmptyServices` off:** it's a provider-wide flag, so it changes every CRD route (HTTP `IngressRoute`s too), not just the device ports. And without the flag the route is dropped, which brings you back to the case above.

You can't solve this inside the routing layer. The socket has to stop accepting connections.

## First fix: take the port off the Service

The first working fix was done by hand in the release pipeline:

- **Stop:** scale the backend to 0, wait until the pod is gone, then remove the port from Traefik's `LoadBalancer` Service.
- **Start:** scale up, wait for the rollout, then add the port back.

With the port gone from the Service, the cloud load balancer drops its rule and connects **time out** instead of being accepted. Order matters: scale down *first*, so the existing connections still get a clean close from the backend itself.

It worked, but it had two problems:

- A timeout is slow and vague. The device waits for its connect timeout, not a crisp "no".
- It only covers *planned* stops. A crash or an OOM kill still leaves Traefik accepting and closing.

## Better: "connection refused", automatically

What we really wanted was for the port to behave as if nothing was there: **connection refused**, at once.

The trick turned out to be one patch. Leave the port on the Service (same load balancer rule, same nodePort), but point its `targetPort` at a port that nothing in the Traefik pod listens on:

```sh
# close: connects now get RST / "connection refused"
kubectl patch svc traefik -n <ingress-ns> \
  -p '{"spec":{"ports":[{"port":7000,"targetPort":65000}]}}'

# open again: back to the named entrypoint port
kubectl patch svc traefik -n <ingress-ns> \
  -p '{"spec":{"ports":[{"port":7000,"targetPort":"backend7000"}]}}'
```

kube-proxy forwards the connect to the Traefik pod on port 65000. The pod's kernel has no listener there and answers with a reset. The load balancer rule never changes, so reopening is instant.

To make it automatic, we wrote a small **port guard**: a single-file, standard-library-only Python process in the ingress namespace. It:

- **Watches** the backend's EndpointSlices (a Kubernetes watch wakes it up, and a 1 s poll is a safety net).
- **Closes** the port (`targetPort` 65000) when no endpoint is ready.
- **Opens** it again when an endpoint has been ready for a few seconds.
- **Logs** one JSON line per decision, and serves Prometheus metrics.

Its RBAC is narrow: read and watch EndpointSlices in the backend namespaces, and get and patch one Service.

### Iteration 1: close sooner

The first version closed the port after 15 s without a ready pod (some hysteresis felt prudent). In a test, the devices *still* flipped. The backend drops all connections the moment it gets SIGTERM, so for those 15 s Traefik was back to accepting and closing.

Fix: an endpoint marked **terminating**, with no other pod ready, means a deliberate stop. Close at once, no hysteresis.

### Iteration 2: a short `preStop` pause

Even "close at once" leaves a gap. The guard has to see the change (≤ 1 s), and kube-proxy has to apply the new rule (~1 s). Meanwhile the backend has already dropped its connections, and the devices reconnect straight into Traefik.

We first tried not to touch the backend at all. In the end, a 3-second pause was the honest fix:

```yaml
lifecycle:
  preStop:
    sleep:
      seconds: 3   # native sleep action, Kubernetes 1.30+
```

Now the order is right. The pod is marked terminating, the guard closes the port, and only then does the backend drop its connections. Reconnects get "refused".

### Iteration 3: crashes

`preStop` doesn't run on a crash or an OOM kill. The pod isn't terminating then, just *not ready*, so the guard waited for its "not ready" delay. We set that delay to 0. The readiness probe already has its own tolerance (many failures before "not ready"), so a second delay on top only added a window of accept-and-close.

Opening waits 3 s after Ready. That's safe here because the backend starts its listener before it reports ready.

### Iteration 4: does "closed" really refuse?

A port with `targetPort: 65000` is only closed if nothing listens on 65000. So while a port is closed, the guard connects to the Service's ClusterIP on that port and expects "refused". If something accepts, it logs an error and sets a `port_refusing` metric to 0, which an alert picks up after 2 minutes.

## A false alarm in the first production test

The first run on the production cluster looked like this (trimmed):

```
12:25:11 close  port=7001 target_port=65000 reason=terminating
12:25:11 close  port=7002 target_port=65000 reason=terminating
12:25:11 error  port 7001 is closed but <clusterIP>:7001 accepts connections
12:25:11 error  port 7002 is closed but <clusterIP>:7002 accepts connections
12:25:40 state  port=7001 open=false refusing=true
12:26:00 open   port=7001 target_port=backend7001 ready=1
```

The close and reopen were exactly right. The errors were not real. The guard skipped the probe in the round where it closed the port, but the very next round came within a second, or at once when the pod deletion woke the watch. kube-proxy hadn't applied the new rule yet, so the probe was still accepted. Thirty seconds later the same port was correctly refusing.

The fix is a grace period: don't probe a port until a few seconds after it was closed (or first seen closed). The 2-minute alert window meant this never paged anyone, but a check that cries wolf on every release soon gets ignored.

This environment didn't have the `preStop` pause yet. The probe being accepted is also direct evidence of the ~1 s gap that the pause exists to cover.

## Lessons learned

1. **"Accept then close" is worse than "refuse".** For a client, a refused connect is a clear "not now". An accepted connection that dies at once looks like a broken network, and clients escalate on that (retries, resets, reboots). When a backend is gone, make the front door say so.

2. **A custom TCP route in an ingress controller isn't a "port that's there when the backend is".** The entrypoint (the listening socket) and the route (where to forward) have separate lifecycles. For HTTP, accepting and answering 503 is polite. For a raw TCP protocol there is no 503: the client only sees a connect and a drop. If the port must follow the backend, something outside the route has to manage it.

3. **Timeouts and "refused" are different answers.** Removing the port from the load balancer gave timeouts: slow, and it looked like a network outage. Re-pointing `targetPort` gave an instant reset, and the load balancer never changed.

4. **"Close immediately" is never immediate.** There is always the watcher's reaction time plus kube-proxy's propagation. If the backend drops its clients at SIGTERM, a short `preStop` pause is what makes the ordering correct. It's three lines of YAML, and resisting it cost us a test round.

5. **Planned stops and crashes are different cases.** `preStop` and "terminating" cover the planned ones. For crashes, rely on the readiness probe's own tolerance, not on a second delay layered on top.

6. **A self-check needs the same patience as the system it checks.** The refuse probe was the right idea, but it ran before the change could have taken effect. Any verification of an eventually-consistent change needs a grace period, or it turns into noise.

---

*Co-authored with Claude.*

If this was useful, [you can buy me a coffee](https://ko-fi.com/p47k0).

New articles: [follow via RSS](https://blog.koorevaar.com/feed.xml).

Let's connect on [LinkedIn](https://nl.linkedin.com/in/patrickkoorevaar).
