Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 79 ยท Transport Layer

TCP Connection Teardown and State Machine

Learn how TCP closes a connection with FIN and ACK, what half-close, RST and TIME_WAIT mean, how to read the state diagram, and why CLOSE_WAIT piles up.

Opening a TCP connection takes three segments. Closing it is more subtle, because TCP connections are full duplex: there are really two independent byte streams, one in each direction, and each one must be shut down on its own. That is why a clean close normally needs four segments, and why a connection can sit half-open in states such as FIN_WAIT_2 or CLOSE_WAIT for a long time.

Every TCP connection moves through a set of named states. The names appear in the output of netstat and ss, so knowing them lets you answer practical questions: why does my server show thousands of TIME_WAIT entries, and why does a leaking program accumulate CLOSE_WAIT? In this lesson you learn the closing handshake, the full state diagram, and you run a small state machine that follows the rules exactly.

Closing with FIN

When an application calls close() (or shutdown() for writing) it tells TCP: "I have no more data to send." TCP sends a segment with the FIN flag set. A FIN consumes one sequence number, like a SYN, and the other side acknowledges it. The other direction stays open until that side also sends its own FIN.

sequenceDiagram
    participant A as Side A (active close)
    participant B as Side B (passive close)
    Note over A,B: both ESTABLISHED
    A->>B: FIN, seq = u
    Note over A: FIN_WAIT_1
    B->>A: ACK, ack = u + 1
    Note over A: FIN_WAIT_2
    Note over B: CLOSE_WAIT
    B->>A: FIN, seq = v
    Note over B: LAST_ACK
    A->>B: ACK, ack = v + 1
    Note over A: TIME_WAIT
    Note over B: CLOSED

The side that closes first is the active closer. It ends up in TIME_WAIT, the other side goes straight to CLOSED.

Walk through it:

  1. A calls close(). It sends FIN and enters FIN_WAIT_1.
  2. B's TCP acknowledges the FIN and enters CLOSE_WAIT. It now tells its application "the peer is done" (a read() returns end-of-file). B may keep sending data for as long as it likes.
  3. A receives the ACK and enters FIN_WAIT_2, waiting for B's side to finish.
  4. When B's application calls close(), B sends its own FIN and enters LAST_ACK.
  5. A receives the FIN, sends the final ACK and enters TIME_WAIT.
  6. B receives that ACK and moves to CLOSED. A leaves TIME_WAIT after a timeout.

The ACK in step 2 and the FIN in step 4 are separate because B's application may need time to finish sending. If B has nothing more to say, it can combine them into one FIN+ACK segment, which makes a three-segment close.

Half-close

Because the two directions are independent, an application can close only its sending direction with shutdown(SHUT_WR) and keep reading. This is a half-close. A classic use: a client sends a whole request, shuts down the write side so the server sees end-of-file and knows the request is complete, then reads the response until the server closes too. Some command-line tools and old protocols work this way.

Simultaneous close

If both sides call close() at about the same time, their FINs cross on the wire. Each side is in FIN_WAIT_1 when the peer's FIN arrives, so each moves to CLOSING, and each ends in TIME_WAIT after the other's ACK arrives. Both sides pay the TIME_WAIT cost.

TIME_WAIT: the waiting room

The side that sent the last ACK, normally the active closer, cannot just forget the connection. It stays in TIME_WAIT for 2 x MSL, twice the maximum segment lifetime. The standard suggests an MSL of 2 minutes, so 4 minutes; Linux uses a fixed 60 seconds. There are two reasons:

  • The final ACK may be lost. If it is, B retransmits its FIN. A must still be around to acknowledge it again. Without TIME_WAIT, A would answer a stray FIN with a RST and B would report an error.
  • Old segments must die out. A new connection with the same four values (source IP, source port, destination IP, destination port) could otherwise receive a delayed duplicate from the previous one. Waiting twice the longest time a segment can live in the network guarantees that all old segments are gone.

TIME_WAIT is not a bug. It is a feature that costs a little memory and, more importantly, the port: while an entry exists, that exact four-value combination cannot be reused. A client making thousands of short connections to the same server address and port can run out of local ports, because only the source port varies.

Python How many short connections per second before ports run out?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The best cure is to open fewer connections: keep-alive, pooling and multiplexing all help. Tuning kernel flags such as tcp_tw_reuse can allow safe reuse of a TIME_WAIT slot for new outgoing connections (it relies on TCP timestamps), but it should be a last resort, and shortening the timer itself is risky.

RST: aborting a connection

A segment with RST (reset) kills a connection at once, with no handshake. It is the "this makes no sense, stop" signal. TCP sends a RST in several situations:

  • A SYN arrives for a port where nothing is listening. The connecting program sees "connection refused".
  • A segment arrives for a connection that does not exist, for example after a reboot (the half-open case from the handshake lesson).
  • An application deliberately aborts, for instance with the SO_LINGER option set to zero, or after it closes a socket that still had unread data.
  • A firewall or middlebox injects a RST to cut off a connection, which is also how some networks block sites.

A RST is not acknowledged, and unsent data on the connection is thrown away. For that reason a server should prefer the orderly FIN close, so the peer receives every byte first.

"Connection refused" means a RST came back: the host is up, but nothing listens on that port. A connection that just times out usually means packets are being dropped silently, as a firewall often does. The two messages point to quite different problems. See troubleshooting networks.

The full state diagram

All of TCP's life fits into eleven states. Memorize the shape of the diagram rather than every arrow:

stateDiagram-v2
    [*] --> CLOSED
    CLOSED --> LISTEN : passive open
    CLOSED --> SYN_SENT : connect / send SYN
    LISTEN --> SYN_RCVD : rcv SYN / send SYN+ACK
    SYN_SENT --> ESTABLISHED : rcv SYN+ACK / send ACK
    SYN_SENT --> SYN_RCVD : rcv SYN / send SYN+ACK
    SYN_RCVD --> ESTABLISHED : rcv ACK
    ESTABLISHED --> FIN_WAIT_1 : close / send FIN
    ESTABLISHED --> CLOSE_WAIT : rcv FIN / send ACK
    FIN_WAIT_1 --> FIN_WAIT_2 : rcv ACK
    FIN_WAIT_1 --> CLOSING : rcv FIN / send ACK
    FIN_WAIT_1 --> TIME_WAIT : rcv FIN+ACK / send ACK
    FIN_WAIT_2 --> TIME_WAIT : rcv FIN / send ACK
    CLOSING --> TIME_WAIT : rcv ACK
    CLOSE_WAIT --> LAST_ACK : close / send FIN
    LAST_ACK --> CLOSED : rcv ACK
    TIME_WAIT --> CLOSED : 2 MSL timeout

The TCP state machine. Opening goes down the left, an orderly close forks into the active path (FIN_WAIT, TIME_WAIT) and the passive path (CLOSE_WAIT, LAST_ACK). A RST from any state returns to CLOSED.

A short guide to the states you will see in ss -tan:

State Meaning
LISTEN A server socket waiting for SYNs.
SYN_SENT A client sent a SYN and waits for the SYN-ACK.
SYN_RCVD A server got a SYN and sent a SYN-ACK. Many of these suggest a SYN flood.
ESTABLISHED Normal data transfer.
FIN_WAIT_1 / FIN_WAIT_2 The local side closed first and waits for the ACK of its FIN, then for the peer's FIN.
CLOSE_WAIT The peer closed; the local application has not yet.
LAST_ACK The local side closed after the peer and waits for the final ACK.
CLOSING Both sides closed at the same moment.
TIME_WAIT Waiting 2 MSL after the last ACK.

Now run a machine that implements that table. Two hosts exchange the events and the program prints every transition for three scenarios.

Python A TCP state machine: normal, simultaneous and passive close

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check the output against the diagram. In scenario 1 the client ends in TIME_WAIT before the timeout and the server never enters it. In scenario 2 both pass through CLOSING. In scenario 3 the client waits in FIN_WAIT_2 and the server stays in CLOSE_WAIT.

CLOSE_WAIT leaks

Notice who is responsible for each state. TIME_WAIT is TCP doing its protective job, and it ends by itself. CLOSE_WAIT is different: only the application can leave it, by calling close(). TCP has already told the application that the peer finished (end-of-file on read). If the program ignores that and keeps the socket open, the connection stays in CLOSE_WAIT forever, holding a file descriptor and memory.

A server with thousands of CLOSE_WAIT sockets nearly always has a bug: an error path that forgets to close the socket, a connection pool that does not discard dead connections, or a loop that never reads the end-of-file. The symptom usually ends with "too many open files". The fix is in the code, not in the network.

Python Count sockets by state to find a leak

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Putting it together

When you debug a connection, the state tells you who is waiting for whom:

  • SYN_SENT for a long time: the SYN was sent but nothing came back (drops, or a dead host).
  • ESTABLISHED but idle: nothing is wrong at the TCP level; the application is silent. Keepalive probes can detect a dead peer.
  • FIN_WAIT_2 forever: the peer got our FIN and acknowledged it but never closed its side.
  • CLOSE_WAIT forever: we never closed after the peer did.
  • Lots of TIME_WAIT: a high rate of short connections, usually from the side that closes first.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which side of a connection enters TIME_WAIT in a normal close?

    The active closer sends the last ACK and must wait in TIME_WAIT in case that ACK is lost. The passive closer goes straight to CLOSED when it receives the final ACK.
  2. 2. Why does TCP keep a connection in TIME_WAIT for twice the maximum segment lifetime?

    The final ACK might be lost, so the peer may resend its FIN, and delayed segments of the old connection must not be confused with a new connection that reuses the same addresses and ports.
  3. 3. A server shows thousands of sockets in CLOSE_WAIT that never go away. What is the most likely cause?

    CLOSE_WAIT means the peer closed and TCP is waiting for the local application to close. Only the application can leave that state, so it is a leak in the program.
  4. 4. What does a program see when it connects to a port where nothing is listening, and the host is reachable?

    The host's TCP answers a SYN for a closed port with a RST, which the client reports as connection refused. A silent timeout points to dropped packets instead.
  5. 5. What is a half-close?

    The two directions of a TCP connection are independent. After an application closes only its sending side, it can keep receiving data until the peer sends its own FIN.

Summary

  • Each direction of a TCP connection closes on its own with a FIN that the peer acknowledges, so a clean close takes four segments (or three when the FIN and ACK are combined).
  • The active closer ends in TIME_WAIT for 2 x MSL to retransmit a lost final ACK and let old segments die. Heavy short-lived traffic from one client can exhaust ports; reuse connections.
  • A half-close (shutdown of the write side) lets a program signal end of request and still read the reply.
  • RST aborts a connection immediately; "connection refused" means a RST came back from a closed port.
  • Eleven states describe the whole life of a connection. CLOSE_WAIT piling up is an application bug, TIME_WAIT piling up is normal behavior under heavy short connections.

Next, see how TCP makes sure every byte arrives with reliability, acknowledgments, timers and retransmission.