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 waits2MSLbefore moving intoSYN_SENT. - B. Arrival of the client's
ACKsegment is the event that transitions the server intoSYN_RCVD. - C. At a moment when the client has already entered
ESTABLISHED, the server can still be sitting inSYN_RCVD. - D. When the client's concluding
ACKnever arrives, the server waits2MSLand 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 fromLISTEN. MSLstands for Maximum Segment Lifetime (2MSLis 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
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 inSYN_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 fromCLOSED; the server waits for incoming requests (listen()), starting fromLISTEN. SYNandACKcontrol flags: aSYN(synchronize) segment announces a side's initial sequence number (ISN) — its starting byte counter — and consumes1virtual sequence number; anACK(acknowledge) confirms receipt by echoingack = peer_ISN + 1.SYN_SENTvs.SYN_RCVD:SYN_SENTmeans "I sent the openingSYNand am waiting forSYN+ACK" (client role);SYN_RCVDmeans "I receivedSYN, replied withSYN+ACK, and am waiting for the finalACK" (server role).MSL(Maximum Segment Lifetime) and2MSL:MSLis the maximum time a TCP segment may wander in the network before being discarded (2 minutesin RFC 793 / RFC 9293). Waiting2MSLhappens only during connection teardown in theTIME_WAITstate on whichever side closes first — never during the opening handshake.
- Active opener (client) vs. passive opener (server): the client initiates the connection (
Trace the three-way handshake packet by packet
Suppose the client chooses initial sequence number
1000and the server chooses5000. 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 -> ESTABLISHEDWe 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" ]Why Option C is true: the flight-time window of the final ACK
Put concrete millisecond timestamps on the ladder above assuming a
20 msone-way network delay (40 msround-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 ESTABLISHEDThroughout the entire
t = 40 mstot = 60 mswindow (one one-way network delay — and even longer if thatACKpacket is dropped in transit!), the client is already inESTABLISHEDwhile the server is still inSYN_RCVD. Why? Att = 40 ms, the client has seen its ownSYNacknowledged (ack=1001) and has received the server'sSYN(seq=5000), so the client already has proof that both directions work; the server does not get that proof untilack=5001arrives att = 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 initialSYNcarries theACKflag (ack=5001), even if the bareACKpacket was dropped, the client's first data segment automatically completes the handshake on the server!Why Option A is false: wrong role state and teardown timer
Option A asserts that receiving the client's initial
SYNcauses the server to wait2MSLbefore moving intoSYN_SENT. Both parts of that claim fail:- Wrong state (
SYN_SENTinstead ofSYN_RCVD): in a standard passive open, aLISTENserver receivingSYNtransitions toSYN_RCVD, neverSYN_SENT. Only an endpoint that initiates an active open by sending an unpromptedSYNentersSYN_SENT. - Nonexistent
2MSLdelay: the server replies toSYNwithSYN+ACKimmediately. Waiting2MSL(4 minutesper RFC 793, or60 secondsin Linux'sTIME_WAITimplementation) on every new connection would stall every web request for minutes;2MSLexists solely at connection teardown.
- Wrong state (
Why Option B is false: swaps entering and leaving SYN_RCVD
Option B asserts that arrival of the client's
ACKsegment is the event that transitions the server intoSYN_RCVD.The state's name literally stands for "SYN received":
- At
t = 20 ms, receiving the client'sSYNmoves the server intoSYN_RCVD. - At
t = 60 ms, receiving the client'sACKmoves the server out ofSYN_RCVDintoESTABLISHED.
Option B reverses the entry and exit triggers of
SYN_RCVD.- At
Why Option D is false: exponential-backoff retransmission, not 2MSL
Option D asserts that when the client's concluding
ACKnever arrives, the server waits2MSLand immediately closes the connection without sending anything else.TCP is a reliable protocol — it never silently waits
2MSLand gives up without trying to recover a lost packet. When the finalACKdoes not arrive, the connection sits half-open inSYN_RCVDinside 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):- When the timer expires, the server retransmits
SYN+ACKand doubles the timeout. - If the
ESTABLISHEDclient is still reachable, receiving the duplicateSYN+ACKcauses the client to immediately re-sendACK, moving the server toESTABLISHED. - Only after exhausting an OS-configured retry limit does the server delete the
SYN_RCVDentry.
On Linux,
net.ipv4.tcp_synack_retriesdefaults to5retries starting from a1-second initial timeout (1, 2, 4, 8, 16, 32seconds):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 == 63Thus the server actively retransmits
SYN+ACKat1, 3, 7, 15, 31seconds and aborts around63seconds — neither waiting2MSLnor closing directly without retries.- When the timer expires, the server retransmits
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):
t = 0 ms: Client sendsSYN-> client entersSYN_SENT(server is stillLISTEN).t = 20 ms: Server receivesSYNand sendsSYN+ACK-> server entersSYN_RCVD(ruling out A, which claimsSYN_SENTafter2MSL, and ruling out B, which claimsSYN_RCVDstarts onACK).t = 40 ms: Client receivesSYN+ACK, sendsACK, and entersESTABLISHED. From40 msto60 ms, client isESTABLISHEDwhile server is stillSYN_RCVD(proving C correct; and ifACKis lost, the server retransmitsSYN+ACKwith backoff rather than waiting2MSL, ruling out D).
Key points
- Option C is correct because
ACKflight time is nonzero. The client entersESTABLISHEDupon receivingSYN+ACK, whereas the server entersESTABLISHEDonly upon receiving the resultingACKat 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. SYNconsumes 1 sequence number. With client ISN1000and server ISN5000,SYN+ACKacknowledges1001(1000 + 1) and the client's finalACKacknowledges5001(5000 + 1).2MSLbelongs exclusively to teardown (TIME_WAIT), never setup. Whichever peer sends the firstFIN(finish) flag to close the connection is the active closer and waits2MSL(4 minutesin RFC 793 / RFC 9293; fixed at60 secondson Linux) inTIME_WAIT.- Lost final
ACKtriggersSYN+ACKretransmission, not immediate close. Either a retransmittedSYN+ACKeliciting a freshACKor the client's very first data segment (which carriesACKflagack=5001) completes the server's transition toESTABLISHED. - OS socket nuance. On Linux, the listening parent socket itself remains in
LISTENforever; each half-open handshake creates a lightweight mini-socket in the kernel's SYN queue (SYN-RECVinss), moving to the accept queue foraccept()only after reachingESTABLISHED.
Common mistakes
- Swapping
SYN_SENTandSYN_RCVD(Option A trap). Anchor each name to the local action:SYN_SENT= "I sent the initialSYN";SYN_RCVD= "I receivedSYNwhile listening". - Assuming simultaneous state transitions. Network diagrams look horizontal, but causal arrows slant downward in time; the server cannot know the client received
SYN+ACKuntilACKcrosses back. - Confusing state entry with state exit (Option B trap). Receiving the client's
ACKmoves the server out ofSYN_RCVDintoESTABLISHED, not intoSYN_RCVD. - Misplacing
2MSLinto the handshake or assuming only servers enterTIME_WAIT(Options A & D trap).TIME_WAITonly 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) or63 stimeout 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_RCVDand runs an exponential-backoff retransmission timer (on Linux with defaulttcp_synack_retries = 5and1 sinitial timeout, resendingSYN+ACKat1, 3, 7, 15, 31seconds). If theESTABLISHEDclient is alive, it either sends data (whose header already includesack = server_ISN + 1) or replies to the duplicateSYN+ACKwith a freshACK, promoting the server toESTABLISHED. If all retries fail (e.g., the client crashed or the network partitioned), the server silently deletes theSYN_RCVDentry at ~63seconds; if the client later wakes up and sends data for that forgotten connection, the server replies withRST(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'sFIN) is dropped in the network, the passive closer will retransmitFIN, and staying inTIME_WAITlets the active closer re-sendACKinstead of replying with an errorRST. Second, it drains wandering duplicate packets from the network (1 MSLfor the lostACK+1 MSLfor a retransmitted packet, or2MSLconservatively) 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
SYNpackets and never sends the finalACK, filling the server's finite SYN queue withSYN_RCVDentries 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-bitSYN+ACKinitial 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 returnsack = cookie + 1, the server subtracts1, verifies the hash and timestamp, and allocates theESTABLISHEDsocket on the spot — trading awaySYN+ACKretransmissions and advanced TCP options like SACK (Selective Acknowledgment) or window scaling unless tucked into TCP timestamps (Linux activates cookies automatically on queue overflow whentcp_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
SYNto each other at the same time before receiving anything, both start as active openers (CLOSED -> SYN_SENT), then upon receiving the peer'sSYNinSYN_SENT, both transition toSYN_RCVDand reply withSYN+ACK, and finally upon receivingSYN+ACKboth enterESTABLISHED(4 packets total instead of 3). This overturns the passive-server premise behind Option A — in a simultaneous open, both peers pass throughSYN_SENTbeforeSYN_RCVD(though still with zero2MSLwait) — 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
- 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?
- What is the purpose of holding the active closer in TIME_WAIT for 2MSL, and which two failure modes does this delay guard against?
- Why are SYN_RCVD queue entries vulnerable to SYN flood attacks, and how do stateless SYN cookies mitigate the problem?
- 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?
Similar questions
- Effective Prompting Strategies for AI-Assisted Debugging
- Identify the Interleaved Transaction Anomaly
- Midpoint Probe Counts in Binary Search
- Iteration Count of a C For-Loop with Assignment
- Smallest 8-Bit Two's-Complement Number Using Three Set Bits
- Spotting the Flawed HTTP Status Code Claim
More Bitkernel interview questions
- Effective Prompting Strategies for AI-Assisted Debugging Medium
- Identify the Interleaved Transaction Anomaly Medium
- Midpoint Probe Counts in Binary Search Medium Pro
- Iteration Count of a C For-Loop with Assignment Medium Pro
- Smallest 8-Bit Two's-Complement Number Using Three Set Bits Medium Pro
- Spotting the Flawed HTTP Status Code Claim Medium Pro
- Popup Dialog Followed by Conditional Page Redirect Hard Pro
- Conceptual Evaluation Order of SQL Clauses Medium Pro
- Deduce Contents from Four Labeled Cups Medium Pro
- Array State After Initial Max-Heap Extraction Medium Pro