CLOSE_WAIT vs TIME_WAIT: Diagnose Linux TCP Connections
Diagnose Linux CLOSE_WAIT and TIME_WAIT with ss, socket ownership and a reproducible Python loopback lab. Separate cleanup defects from connection churn.
CLOSE_WAIT means the peer has sent FIN and the local send direction has not finished closing. TIME_WAIT retains protocol state after an orderly close. Diagnose persistent CLOSE_WAIT through application ownership and cleanup; investigate TIME_WAIT alongside connection churn and actual resource failures.
Start with the local endpoint, not the word client
A TCP connection has state at each endpoint. The line you see on one Linux host describes that local endpoint; the peer can be in a different state at the same moment. Record the local address, local port, peer address and peer port before deciding which application needs attention. A reverse proxy has separate downstream and upstream connections, so a browser closing its connection does not identify the state of the proxy’s database socket.
In the ordinary orderly-close sequence, the endpoint that sends the first FIN proceeds through FIN_WAIT states. The receiver acknowledges that FIN and enters CLOSE_WAIT. When its application finishes sending and closes its direction, that receiver sends its own FIN. The original closer acknowledges it and enters TIME_WAIT. These are protocol roles, not permanent client and server roles. Simultaneous close and reset paths can differ from this common sequence.
The useful first question is therefore: has the local application still got cleanup to finish, or is the kernel retaining a completed connection record? Those lead to different investigations. A state count by itself cannot answer whether users are affected.
| Local state | Meaning in the ordinary close path | First investigation |
|---|---|---|
| CLOSE_WAIT | Peer FIN received; local send direction has not finished closing | Application lifetime, EOF handling and ownership |
| FIN_WAIT_2 | Local FIN acknowledged; waiting for peer FIN | Peer behavior and local socket ownership |
| TIME_WAIT | Close handshake completed at this endpoint; temporary TCP state retained | Connection creation rate and evidence of resource pressure |
Source: RFC 9293 — TCP state machine and connection closing ↗
Capture state, endpoints and ownership
These read-only commands use ss from iproute2. Numeric output avoids name lookups during diagnosis; the state filters separate the two populations. The example port 8080 is only a placeholder: filter by the service port that actually appears as the local source port. For outgoing connections the service of interest may instead be the peer destination port.
Use -p to request process details and -o for timer information. Process information can be incomplete when permissions are insufficient or when the relevant process is outside your visible PID namespace. TIME_WAIT entries commonly have no owning application descriptor because the application has already closed it. An empty process field therefore means something different from proof that a live CLOSE_WAIT socket has no owner.
Run the inspection in the network namespace where the application’s sockets exist. A container, host and sidecar can expose different views. If a row disappears between commands, do not join the two snapshots as though they were an atomic trace. Save timestamps and repeat during the symptom, using your normal access procedures rather than changing namespace or privilege boundaries blindly.
ss -s
ss -Htnp state close-wait
ss -Htnop state time-wait
ss -Htnp state close-wait '( sport = :8080 )'
ss -Htnop state time-wait '( dport = :443 )'Source: ss(8) — socket state filters, processes and timers ↗
Investigate persistent CLOSE_WAIT as a lifetime problem
A brief CLOSE_WAIT is compatible with correct behavior. TCP is full duplex: receiving the peer’s FIN ends incoming data after already queued bytes are delivered, but the local application may still have a legitimate response to send. An empty bytes result from a positive-length Python TCP recv means orderly EOF, not an instruction to keep polling for another request indefinitely. Other runtime APIs expose EOF through their own return values or events.
Trouble becomes more convincing when the same owned connections remain after their requests should have completed, the population grows across samples, and open descriptors or stalled work grow with it. Inspect exception paths, cancellation handlers, response-body disposal, worker shutdown and connection-pool return logic. Identify the component that actually owns the socket; an application using a library should normally release the library’s response or session object through its documented API.
Check whether a worker is blocked before it reaches cleanup. A database call, lock or queue wait can delay the local close even when EOF handling itself is correct. Capturing a supported thread or task dump and correlating it with request identifiers is more useful than simply increasing a socket timeout. Avoid logging credentials or entire private request bodies while collecting that evidence.
Use structured resource management so normal returns and exceptions converge on cleanup. In Python, socket context managers close the socket on exit; a makefile wrapper or duplicated descriptor can complicate lifetime, so account for all references. A timeout limits a particular wait only if the code handles it and releases its resources. Killing a worker can temporarily remove its sockets while leaving the defect ready to return.
Treat TIME_WAIT as connection churn until evidence says otherwise
TIME_WAIT serves TCP’s close correctness, including allowing a final acknowledgment to be sent again if the peer retransmits its FIN and separating old segments from a later connection incarnation. It is not simply an application forgetting to call close. The protocol specifies a waiting interval tied to maximum segment lifetime; do not assume every operating system, kernel or network path exposes the same duration.
A busy service can have many TIME_WAIT records while serving requests successfully. Compare connection creation and close rates with the state population over time. As a rough steady-state intuition, more closes per second and a longer retained lifetime produce more retained records. This is a capacity-planning relationship, not a measured prediction or a universal alarm threshold. Bursts, reuse rules and different destinations can change the observed picture.
Escalate on evidence: connection failures, latency, descriptor errors, memory pressure or inability to allocate an outgoing local address and port. Outgoing ephemeral-port pressure depends on source addresses, destination tuples, bind behavior, NAT and the available range; a machine-wide TIME_WAIT count does not directly equal exhausted ports. A TIME_WAIT record also should not be counted as one live application file descriptor.
If excessive churn is established, investigate why connections are short lived. Appropriate HTTP keep-alive, pooling or multiplexing may reduce new TCP connections, but must respect peer limits and application semantics. Bound pool size and idle lifetime, release responses correctly, and measure before and after. A connection that cannot safely be reused must be closed; keeping every socket forever trades churn for a different resource problem.
Source: RFC 9293 — TCP state machine and connection closing ↗
Do not use tcp_fin_timeout as a CLOSE_WAIT remedy
Linux documents tcp_fin_timeout for orphaned FIN_WAIT_2 connections: those no longer referenced by an application. It is not a general timer for every TCP state, and changing it does not repair application-owned CLOSE_WAIT cleanup. Keep FIN_WAIT_2 distinct from TIME_WAIT when reading advice that uses the vague phrase “FIN timeout.”
The kernel also documents tcp_tw_reuse as a policy for reusing TIME_WAIT sockets when protocol safety permits. That is a separate mechanism, not a command to release leaked application references. Defaults and behavior can depend on kernel version and policy. Review the documentation matching the deployed kernel and test any justified change through the normal rollout process; this guide does not recommend a global sysctl value.
Likewise, sending resets with abortive-close options can change what the peer observes. Suppressing an orderly shutdown merely to make a dashboard count smaller can lose useful failure evidence or disrupt protocols. Preserve the connection’s intended semantics and fix the measured bottleneck.
Source: Linux IP sysctl — tcp_fin_timeout and tcp_tw_reuse ↗
Reproduce both states with two real loopback connections
The complete script below requires Linux, Python 3 and ss. It binds only 127.0.0.1 on an operating-system-selected port, creates one connection at a time, and changes no kernel settings. Run it in a disposable development environment where loopback sockets and socket inspection are allowed. Its ss filters use both ports so unrelated sockets are not mistaken for the test connection.
Each pass starts with both endpoints established. One endpoint sends a small payload and shuts down only its write direction. The other reads through EOF, remains in CLOSE_WAIT, and still sends a reply. The script then closes that passive endpoint and verifies TIME_WAIT at the endpoint that initiated FIN. Repeating with the roles reversed demonstrates why “TIME_WAIT always belongs to the client” is unreliable.
The published script passed 18 checks across two actual IPv4 loopback connections in this run. State checks poll for up to three seconds instead of relying on one fixed sleep. The checks cover observed states, payload delivery, reverse-direction delivery after EOF, and disappearance of the passive CLOSE_WAIT after cleanup. They do not measure TIME_WAIT expiration, packet loss, retransmissions, simultaneous close, IPv6, NAT, proxies, TLS or production throughput. A restricted environment or unusual timing can make a state assertion fail; investigate that limit rather than treating it as a TCP compliance verdict.
import socket
import subprocess
import time
def rows(state, local, remote):
result = subprocess.run(
['ss', '-Htn', 'state', state,
f'( sport = :{local} and dport = :{remote} )'],
check=True, capture_output=True, text=True, timeout=3)
return result.stdout.strip()
def await_state(state, local, remote):
deadline = time.monotonic() + 3
while time.monotonic() < deadline:
if rows(state, local, remote):
return
time.sleep(0.02)
raise AssertionError((state, local, remote))
checks = 0
for initiator in ('client', 'server'):
with socket.socket() as listener:
listener.bind(('127.0.0.1', 0))
listener.listen(1)
with socket.create_connection(listener.getsockname(), timeout=3) as client:
with listener.accept()[0] as server:
server.settimeout(3)
active, passive = ((client, server) if initiator == 'client'
else (server, client))
ap = active.getsockname()[1]
pp = passive.getsockname()[1]
await_state('established', ap, pp)
await_state('established', pp, ap)
checks += 2
active.sendall(b'payload')
active.shutdown(socket.SHUT_WR)
received = b''
while True:
chunk = passive.recv(4096)
if not chunk:
break
received += chunk
assert received == b'payload'
checks += 1
await_state('close-wait', pp, ap)
await_state('fin-wait-2', ap, pp)
checks += 2
# EOF affects one direction: the passive end can still send.
passive.sendall(b'reply')
assert active.recv(4096) == b'reply'
checks += 1
passive.close()
assert active.recv(4096) == b''
checks += 1
active.close()
await_state('time-wait', ap, pp)
assert not rows('close-wait', pp, ap)
checks += 2
print(initiator, 'initiated FIN: CLOSE_WAIT -> cleanup; TIME_WAIT observed')
print(f'{checks} checks passed; two loopback connections; no sysctl changes')Turn the observations into a repair you can verify
For a CLOSE_WAIT incident, retain several timestamped samples, group by service and owning process, and correlate them with stuck requests and descriptor trends. Reproduce the relevant EOF, cancellation or error path in staging. After the fix, verify that completed requests release their resources and that the persistent population stops growing under the same workload. A single clean snapshot immediately after restart is weak evidence.
For TIME_WAIT pressure, record the actual failing operation and error, the outgoing destination distribution and the connection churn rate. Test one targeted change, such as corrected response disposal or an appropriately bounded pool. Confirm both the original user symptom and resource usage improve. Keep rollback criteria tied to request success and latency, not just a lower socket count.
The distinction stays practical: CLOSE_WAIT asks what the local application still needs to finish; TIME_WAIT asks how completed connections and connection churn interact with capacity. Start with ownership and endpoint evidence, preserve orderly protocol behavior, and choose the smallest change that resolves the demonstrated failure.
Your next steps
- Read states from the local endpoint and identify the exact connection tuple.
- Persistent CLOSE_WAIT needs application lifetime evidence, not a generic kernel timeout.
- TIME_WAIT can be normal; measure failed operations before tuning.
- The loopback lab demonstrates both client-initiated and server-initiated FIN.
Sources & official resources
Linked resources checked on 2026-10-29. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →