TCP Handshake Endpoint State Transitions

Medium · Software Engineering Fundamentals · Software Engineer · Online Assessment

Prompt

Consider standard TCP connection setup (the three-way handshake) between an active-opening client and a passive server waiting in LISTEN. Only one of the four claims below accurately describes TCP behavior. Select the true claim and explain why each of the remaining three claims is invalid.

  • A. Upon receiving the client's initial SYN, the server waits 2MSL before moving into SYN_SENT.
  • B. Arrival of the client's ACK segment is the event that transitions the server into SYN_RCVD.
  • C. At a moment when the client has already entered ESTABLISHED, the server can still be sitting in SYN_RCVD.
  • D. When the client's concluding ACK never arrives, the server waits 2MSL and immediately closes the connection without sending anything else.

Assumptions:

  • Standard TCP state machine (RFC 793 / RFC 9293) with no TCP_DEFER_ACCEPT, no TCP Fast Open, and no simultaneous open.
  • Single-choice question: exactly one statement is valid.
  • The client performs the active open from CLOSED; the server performs a passive open from LISTEN.
  • MSL stands for Maximum Segment Lifetime (2MSL is double that duration).

Scope & Expectations

  • Identify the sole valid claim and justify it by tracing local send/receive events and propagation delay across both endpoints.
  • Refute each of the three false claims by pointing to the exact state ownership rule, transition trigger, or recovery mechanism it gets wrong.
  • Distinguish setup-phase retransmission behavior on half-open connections from teardown-phase TIME_WAIT (2MSL) timers.

Step-by-step walkthrough

  1. Identify the correct option and the two core TCP rules

    Among the four candidate claims about the TCP handshake, Option C is the single valid statement: at a moment when the client has already entered ESTABLISHED, the server can still be sitting in SYN_RCVD.

    To verify Option C and eliminate Options A, B, and D from first principles, define four core TCP terms first:

    • Active opener (client) vs. passive opener (server): the client initiates the connection (connect()), starting from CLOSED; the server waits for incoming requests (listen()), starting from LISTEN.
    • SYN and ACK control flags: a SYN (synchronize) segment announces a side's initial sequence number (ISN) — its starting byte counter — and consumes 1 virtual sequence number; an ACK (acknowledge) confirms receipt by echoing ack = peer_ISN + 1.
    • SYN_SENT vs. SYN_RCVD: SYN_SENT means "I sent the opening SYN and am waiting for SYN+ACK" (client role); SYN_RCVD means "I received SYN, replied with SYN+ACK, and am waiting for the final ACK" (server role).
    • MSL (Maximum Segment Lifetime) and 2MSL: MSL is the maximum time a TCP segment may wander in the network before being discarded (2 minutes in RFC 793 / RFC 9293). Waiting 2MSL happens only during connection teardown in the TIME_WAIT state on whichever side closes first — never during the opening handshake.
  2. Trace the three-way handshake packet by packet

    Suppose the client chooses initial sequence number 1000 and the server chooses 5000. Because network propagation takes nonzero time, state transitions on the two peers are asynchronous — each host advances its own state machine strictly upon a local send or receive event:

    Client (starts CLOSED)                        Server (starts LISTEN)
    ----------------------                        ----------------------
    1. App calls connect()
       send SYN (seq=1000)
       state -> SYN_SENT       --- SYN --------->
                                                  2. Receive SYN (seq=1000)
                                                     send SYN+ACK (seq=5000, ack=1001)
                               <-- SYN+ACK ------    state -> SYN_RCVD
    3. Receive SYN+ACK
       send ACK (seq=1001, ack=5001)
       state -> ESTABLISHED    --- ACK --------->    (server is STILL in SYN_RCVD!)
                                                  4. Receive ACK (ack=5001)
                                                     state -> ESTABLISHED
    

    We can encode this exact state machine in a tiny Python table to replay both sides deterministically:

    # (current_state, local_event) -> (next_state, packet_sent_or_None)
    TCP_SETUP_TRANSITIONS = {
        ("CLOSED", "app_connect"): ("SYN_SENT", "SYN"),
        ("LISTEN", "recv_SYN"): ("SYN_RCVD", "SYN+ACK"),
        ("SYN_SENT", "recv_SYN_ACK"): ("ESTABLISHED", "ACK"),
        ("SYN_RCVD", "recv_ACK"): ("ESTABLISHED", None),
    }
    
    
    def trace_states(initial_state: str, events: list) -> list:
        state = initial_state
        visited = [state]
        for event in events:
            state, _outgoing = TCP_SETUP_TRANSITIONS[(state, event)]
            visited.append(state)
        return visited
    
    
    assert trace_states("CLOSED", ["app_connect", "recv_SYN_ACK"]) == [
        "CLOSED", "SYN_SENT", "ESTABLISHED"
    ]
    assert trace_states("LISTEN", ["recv_SYN", "recv_ACK"]) == [
        "LISTEN", "SYN_RCVD", "ESTABLISHED"
    ]
    
  3. Why Option C is true: the flight-time window of the final ACK

    Put concrete millisecond timestamps on the ladder above assuming a 20 ms one-way network delay (40 ms round-trip time) and zero packet loss:

    Time      Event                                    Client state   Server state
    -------   --------------------------------------   ------------   ------------
    t =  0ms  Client sends SYN                         SYN_SENT       LISTEN
    t = 20ms  Server receives SYN, sends SYN+ACK       SYN_SENT       SYN_RCVD
    t = 40ms  Client receives SYN+ACK, sends ACK       ESTABLISHED    SYN_RCVD     <-- Option C!
    t = 60ms  Server receives ACK                      ESTABLISHED    ESTABLISHED
    

    Throughout the entire t = 40 ms to t = 60 ms window (one one-way network delay — and even longer if that ACK packet is dropped in transit!), the client is already in ESTABLISHED while the server is still in SYN_RCVD. Why? At t = 40 ms, the client has seen its own SYN acknowledged (ack=1001) and has received the server's SYN (seq=5000), so the client already has proof that both directions work; the server does not get that proof until ack=5001 arrives at t = 60 ms.

    This temporary mismatch is completely safe in practice. The client is allowed to send its first application data packet (such as an HTTP request) right at t = 40 ms. Because every TCP segment after the initial SYN carries the ACK flag (ack=5001), even if the bare ACK packet was dropped, the client's first data segment automatically completes the handshake on the server!

  4. Why Option A is false: wrong role state and teardown timer

    Option A asserts that receiving the client's initial SYN causes the server to wait 2MSL before moving into SYN_SENT. Both parts of that claim fail:

    • Wrong state (SYN_SENT instead of SYN_RCVD): in a standard passive open, a LISTEN server receiving SYN transitions to SYN_RCVD, never SYN_SENT. Only an endpoint that initiates an active open by sending an unprompted SYN enters SYN_SENT.
    • Nonexistent 2MSL delay: the server replies to SYN with SYN+ACK immediately. Waiting 2MSL (4 minutes per RFC 793, or 60 seconds in Linux's TIME_WAIT implementation) on every new connection would stall every web request for minutes; 2MSL exists solely at connection teardown.
  5. Why Option B is false: swaps entering and leaving SYN_RCVD

    Option B asserts that arrival of the client's ACK segment is the event that transitions the server into SYN_RCVD.

    The state's name literally stands for "SYN received":

    • At t = 20 ms, receiving the client's SYN moves the server into SYN_RCVD.
    • At t = 60 ms, receiving the client's ACK moves the server out of SYN_RCVD into ESTABLISHED.

    Option B reverses the entry and exit triggers of SYN_RCVD.

  6. Why Option D is false: exponential-backoff retransmission, not 2MSL

    Option D asserts that when the client's concluding ACK never arrives, the server waits 2MSL and immediately closes the connection without sending anything else.

    TCP is a reliable protocol — it never silently waits 2MSL and gives up without trying to recover a lost packet. When the final ACK does not arrive, the connection sits half-open in SYN_RCVD inside the server's SYN queue (kernel memory tracking incomplete handshakes) and runs a retransmission timer with exponential backoff (doubling the wait after each retry to avoid congesting the network):

    1. When the timer expires, the server retransmits SYN+ACK and doubles the timeout.
    2. If the ESTABLISHED client is still reachable, receiving the duplicate SYN+ACK causes the client to immediately re-send ACK, moving the server to ESTABLISHED.
    3. Only after exhausting an OS-configured retry limit does the server delete the SYN_RCVD entry.

    On Linux, net.ipv4.tcp_synack_retries defaults to 5 retries starting from a 1-second initial timeout (1, 2, 4, 8, 16, 32 seconds):

    timeout_sec = 1
    elapsed_sec = 0
    retry_times = []
    
    for _ in range(5):  # Linux default net.ipv4.tcp_synack_retries = 5
        elapsed_sec += timeout_sec
        retry_times.append(elapsed_sec)
        timeout_sec *= 2
    
    abort_time_sec = elapsed_sec + timeout_sec
    assert retry_times == [1, 3, 7, 15, 31]
    assert abort_time_sec == 63
    

    Thus the server actively retransmits SYN+ACK at 1, 3, 7, 15, 31 seconds and aborts around 63 seconds — neither waiting 2MSL nor closing directly without retries.

Intuition & how it works

Picture two people confirming a radio link over walkie-talkies when each transmission takes a noticeable moment to cross the airwaves (or mailing three postcards back and forth). First, the client mails "Can you hear me? My counter starts at 1000" (SYN) and waits in SYN_SENT. Second, the server receives that card, mails back "Heard you! My counter starts at 5000" (SYN+ACK), and waits in SYN_RCVD. Third, the moment the client opens SYN+ACK, the client already has proof that both directions work — so it enters ESTABLISHED immediately and mails back "Got yours too!" (ACK), while the server is still waiting by its mailbox in SYN_RCVD until that final card arrives!

A beginner reading a textbook diagram often assumes both sides become ESTABLISHED at the same instant, or mixes up connection-closing timers (2MSL, twice the Maximum Segment Lifetime a packet can survive in the network) with connection-opening states. Because packets take nonzero flight time across the wire — and can even be dropped — each machine updates its state machine strictly on its own local send and receive events.

Walk through a concrete 20 ms one-way network delay (ISN 1000 on client, 5000 on server):

  1. t = 0 ms: Client sends SYN -> client enters SYN_SENT (server is still LISTEN).
  2. t = 20 ms: Server receives SYN and sends SYN+ACK -> server enters SYN_RCVD (ruling out A, which claims SYN_SENT after 2MSL, and ruling out B, which claims SYN_RCVD starts on ACK).
  3. t = 40 ms: Client receives SYN+ACK, sends ACK, and enters ESTABLISHED. From 40 ms to 60 ms, client is ESTABLISHED while server is still SYN_RCVD (proving C correct; and if ACK is lost, the server retransmits SYN+ACK with backoff rather than waiting 2MSL, ruling out D).

Key points

  • Option C is correct because ACK flight time is nonzero. The client enters ESTABLISHED upon receiving SYN+ACK, whereas the server enters ESTABLISHED only upon receiving the resulting ACK at least half a round-trip later.
  • Keep active vs. passive setup states straight. Client (active opener): CLOSED -> SYN_SENT -> ESTABLISHED. Server (passive opener): LISTEN -> SYN_RCVD -> ESTABLISHED.
  • SYN consumes 1 sequence number. With client ISN 1000 and server ISN 5000, SYN+ACK acknowledges 1001 (1000 + 1) and the client's final ACK acknowledges 5001 (5000 + 1).
  • 2MSL belongs exclusively to teardown (TIME_WAIT), never setup. Whichever peer sends the first FIN (finish) flag to close the connection is the active closer and waits 2MSL (4 minutes in RFC 793 / RFC 9293; fixed at 60 seconds on Linux) in TIME_WAIT.
  • Lost final ACK triggers SYN+ACK retransmission, not immediate close. Either a retransmitted SYN+ACK eliciting a fresh ACK or the client's very first data segment (which carries ACK flag ack=5001) completes the server's transition to ESTABLISHED.
  • OS socket nuance. On Linux, the listening parent socket itself remains in LISTEN forever; each half-open handshake creates a lightweight mini-socket in the kernel's SYN queue (SYN-RECV in ss), moving to the accept queue for accept() only after reaching ESTABLISHED.

Common mistakes

  • Swapping SYN_SENT and SYN_RCVD (Option A trap). Anchor each name to the local action: SYN_SENT = "I sent the initial SYN"; SYN_RCVD = "I received SYN while listening".
  • Assuming simultaneous state transitions. Network diagrams look horizontal, but causal arrows slant downward in time; the server cannot know the client received SYN+ACK until ACK crosses back.
  • Confusing state entry with state exit (Option B trap). Receiving the client's ACK moves the server out of SYN_RCVD into ESTABLISHED, not into SYN_RCVD.
  • Misplacing 2MSL into the handshake or assuming only servers enter TIME_WAIT (Options A & D trap). TIME_WAIT only occurs during connection close, and whichever side closes first (very often an HTTP client or reverse proxy) enters it.
  • Treating Linux's retry count (5) or 63 s timeout as a universal RFC constant. RFC 9293 mandates retransmission with backoff, while exact retry counts (net.ipv4.tcp_synack_retries) are OS-tunable parameters.

Follow-up questions

  • How does the server respond when the third-leg ACK drops in transit, and what ultimately happens to that half-open entry if no reply arrives? The server remains in SYN_RCVD and runs an exponential-backoff retransmission timer (on Linux with default tcp_synack_retries = 5 and 1 s initial timeout, resending SYN+ACK at 1, 3, 7, 15, 31 seconds). If the ESTABLISHED client is alive, it either sends data (whose header already includes ack = server_ISN + 1) or replies to the duplicate SYN+ACK with a fresh ACK, promoting the server to ESTABLISHED. If all retries fail (e.g., the client crashed or the network partitioned), the server silently deletes the SYN_RCVD entry at ~63 seconds; if the client later wakes up and sends data for that forgotten connection, the server replies with RST (reset, a TCP flag that immediately aborts an invalid connection).
  • What is the purpose of holding the active closer in TIME_WAIT for 2MSL, and which two failure modes does this delay guard against? First, it guarantees reliable full-duplex teardown: if the active closer's final ACK (acknowledging the passive closer's FIN) is dropped in the network, the passive closer will retransmit FIN, and staying in TIME_WAIT lets the active closer re-send ACK instead of replying with an error RST. Second, it drains wandering duplicate packets from the network (1 MSL for the lost ACK + 1 MSL for a retransmitted packet, or 2MSL conservatively) before the same four-tuple (client IP, client port, server IP, server port) can be reused by a brand-new connection, preventing stale bytes from corrupting the new session.
  • Why are SYN_RCVD queue entries vulnerable to SYN flood attacks, and how do stateless SYN cookies mitigate the problem? In a SYN flood, an attacker blasts thousands of spoofed SYN packets and never sends the final ACK, filling the server's finite SYN queue with SYN_RCVD entries that sit around for tens of seconds so legitimate clients' SYNs get dropped. SYN cookies eliminate per-SYN server memory completely: instead of storing a queue entry, the server encodes the connection metadata directly into its 32-bit SYN+ACK initial sequence number — classically a 5-bit slow timestamp counter, a 3-bit code for MSS (Maximum Segment Size, the largest payload chunk per packet), and a 24-bit cryptographic hash of (client IP/port, server IP/port, timestamp, secret key). When a legitimate client returns ack = cookie + 1, the server subtracts 1, verifies the hash and timestamp, and allocates the ESTABLISHED socket on the spot — trading away SYN+ACK retransmissions and advanced TCP options like SACK (Selective Acknowledgment) or window scaling unless tucked into TCP timestamps (Linux activates cookies automatically on queue overflow when tcp_syncookies = 1).
  • If two endpoints initiate a simultaneous open by transmitting SYN concurrently, which sequence of TCP states do both sides traverse, and how does that alter our analysis of the options? When two peers bound to known ports send SYN to each other at the same time before receiving anything, both start as active openers (CLOSED -> SYN_SENT), then upon receiving the peer's SYN in SYN_SENT, both transition to SYN_RCVD and reply with SYN+ACK, and finally upon receiving SYN+ACK both enter ESTABLISHED (4 packets total instead of 3). This overturns the passive-server premise behind Option A — in a simultaneous open, both peers pass through SYN_SENT before SYN_RCVD (though still with zero 2MSL wait) — and removes the asymmetric client/server roles assumed in Option C, which is why the problem explicitly excludes simultaneous open. text Peer P (CLOSED) Peer Q (CLOSED) SYN_SENT --- SYN (seq=100) -----------> <-- SYN (seq=300) ------------ SYN_SENT SYN_RCVD --- SYN+ACK (100, ack=301) --> <-- SYN+ACK (300, ack=101) --- SYN_RCVD ESTABLISHED ESTABLISHED

Follow-up questions

Similar questions

More Bitkernel interview questions

All 11 Bitkernel questions →