Operating System and Networking Essentials

Medium · System Design · Software Engineer · Onsite

Prompt

Walk through this four-part systems engineering round spanning operating system internals, concurrent execution, transport protocols, and web page delivery:

  1. Processes, threads, and context switches: Explain how an OS process differs from a thread, and break down both the direct kernel work and indirect hardware penalties paid during a context switch.
  2. Concurrency versus parallelism: Distinguish concurrent execution from parallel execution, then illustrate a classic shared-state concurrency defect alongside a practical way to prevent it.
  3. Transport protocols and rate regulation: Contrast TCP with UDP and give concrete workloads suited to each; also distinguish receiver-side flow control from network-wide congestion control.
  4. End-to-end browser navigation: Trace the lifecycle of loading an https:// web address (such as https://app.example.com/dashboard) from pressing Enter until pixels appear on screen — covering DNS lookup, TCP and TLS handshakes, the HTTP exchange, and the browser's client-side rendering stages.

Scope & Expectations

  • Ground each part in concrete kernel, CPU cache, packet-window, and browser-engine mechanics rather than surface-level textbook definitions.
  • Budget time evenly across all four segments and pair protocol or OS concepts with realistic latency figures and production engineering scenarios.
  • Highlight clear trade-offs showing when an engineer picks one mechanism (processes vs. threads, locks vs. atomics, TCP vs. UDP) over its alternative.

Step-by-step walkthrough

  1. Pace the four-part quickfire

    This prompt bundles four foundational systems topics into one rapid-fire interview section. The easiest way to lose points is spending fifteen minutes lecturing on DNS caching and running out of clock before browser rendering. Set expectations in one sentence upfront, divide your time evenly across the four parts, and give every answer the same four-beat rhythm:

    1. Plain-English definition in one or two crisp sentences.
    2. Underlying mechanism — what actually changes in OS memory, CPU hardware, or packets on the wire.
    3. Concrete magnitude — a real latency or memory figure (~1–5 microseconds for a context switch, 1 RTT for TLS 1.3) so your answer reflects production intuition rather than memorized buzzwords.
    4. Real engineering scenario — where you choose one option over the other in practice.
  2. Processes vs. threads

    A process is an executing instance of a program that the operating system isolates inside its own virtual address space — a private map from program memory addresses to physical RAM, maintained in kernel page tables — along with its own open-file table, security credentials, and process ID. One process cannot read or corrupt another process's memory unless both explicitly set up shared memory.

    A thread is an independent stream of execution inside a process. All threads of a process share the same virtual address space (compiled code, global variables, heap allocations, and open files/sockets), while each thread keeps its own call stack (local variables and return addresses), CPU registers (including the program counter, which tracks the next instruction, and the stack pointer), and thread-local storage.

    TWO ISOLATED PROCESSES                     ONE PROCESS WITH TWO THREADS
    +--------------------+ +--------------------+   +-----------------------------------------+
    | Process A          | | Process B          |   | Process C (shared virtual address space)|
    |  Code / Globals    | |  Code / Globals    |   |  Shared: Code, Globals, Heap, Open FDs  |
    |  Heap, Open FDs    | |  Heap, Open FDs    |   |  +-----------------+ +----------------+ |
    |  Page Table A      | |  Page Table B      |   |  | Thread 1        | | Thread 2       | |
    |  [Stack] [Regs]    | |  [Stack] [Regs]    |   |  | Stack 1, Regs 1 | | Stack 2, Regs 2| |
    +--------------------+ +--------------------+   |  +-----------------+ +----------------+ |
             |                      |               +-----------------------------------------+
       Communicate via OS IPC (pipes/sockets)             Communicate via shared RAM (+ locks)
    
    Dimension Process Thread
    Memory isolation Private virtual address space (Page Table per process) Shared heap, globals, code, and open file descriptors
    Creation cost Higher (new address space; Linux fork() shares pages copy-on-write until modified, but still duplicates page-table metadata) Lower (allocates a thread stack, typically 1–8 MB virtual, plus register state)
    Communication IPC (Inter-Process Communication): pipes, sockets, message queues, explicit shared memory Direct pointer reads/writes in shared RAM (fast, requires synchronization)
    Fault blast radius A crash (SIGSEGV) kills only that process An invalid memory write in one thread terminates the entire process
    Context-switch cost Higher (must switch address-space mappings) Lower (keeps the current address space active)

    On Linux, both are kernel task_struct scheduling entities created via the clone() system call — a thread simply passes flags (CLONE_VM | CLONE_FILES | ...) telling the kernel to share its parent's memory and file tables rather than copying them. Choose processes when security and crash isolation dominate (Chrome isolates untrusted websites in separate renderer processes; PostgreSQL isolates client backends), and threads when workers share large in-memory state with minimal copying (a multi-threaded service querying a shared in-process cache).

  3. What a context switch actually costs

    A context switch occurs when the OS kernel pauses the currently running thread on a CPU core and resumes another thread. It can be voluntary (the thread blocks waiting for network/disk I/O, a mutex, or sleep()) or involuntary / preemptive (its scheduler time slice expires or a higher-priority thread wakes up).

    Separate its cost into two parts — beginners usually mention only the first, while the second is often larger in production:

    1. Direct kernel overhead (~1–3 microseconds)

    • Transition the CPU core from user mode into kernel mode via an interrupt or system call.
    • Save the outgoing thread's CPU registers (general-purpose, floating-point/SIMD, instruction & stack pointers) into its kernel task block, run the scheduler to pick the next runnable thread, and load the incoming thread's registers.
    • If switching to a different process, point the CPU's page-table base register (CR3 on x86-64) to the new process's page tables. Without hardware PCID / ASID tags (Process-Context / Address-Space Identifiers that label cached translations by process), switching page tables flushes the TLB (Translation Lookaside Buffer) — the CPU's fast hardware cache of virtual-to-physical address translations.

    2. Indirect cache-warming penalty (microseconds to tens of microseconds)

    • The incoming thread wakes up to find L1/L2 CPU caches and TLB entries populated with the previous thread's working set, plus CPU branch predictors trained on different code paths. Every cold miss stalls the CPU waiting on L3 cache or main DRAM (~60–100 ns per DRAM miss vs ~1 ns for L1).
    Why microseconds add up under high load:
      100,000 switches/s * 3 microseconds/switch = 300,000 us/s = 0.30 s/s = 30% of an entire CPU core!
    

    Two crisp distinctions interviewers love:

    • System call vs. context switch: A non-blocking system call (like clock_gettime or reading ready socket bytes) performs a mode switch into the kernel and returns to the exact same thread (~100–300 ns) — no scheduler swap, no cold cache.
    • User-space coroutines / goroutines vs. OS threads: Async tasks (asyncio, Go goroutines) multiplex thousands of concurrent waits onto a handful of OS worker threads, switching stacks in user space in tens of nanoseconds without entering the kernel. Measure OS switches on Linux with vmstat 1 (cs), pidstat -w, or perf stat -e context-switches.
  4. Concurrency vs. parallelism

    • Concurrency is a program-structuring property: multiple tasks are in progress over overlapping time windows by interleaving their steps (for example, switching away from Request A while it waits on a database socket so Request B can parse headers on the same single CPU core).
    • Parallelism is a hardware-execution property: multiple computations physically execute at the exact same instant across multiple CPU cores, SIMD vector lanes, or GPU cores.
    Concurrency WITHOUT parallelism (1 CPU core, async event loop handling 2 requests):
      Core 0: [Req A: parse]--[Req B: parse]--[Req A: render]--[Req B: render]--> time
                     \..(Req A DB wait)../  \..(Req B DB wait)../
    
    Parallelism (2 CPU cores crunching two matrix blocks simultaneously):
      Core 0: [================ Task A: CPU math ================]--> time
      Core 1: [================ Task B: CPU math ================]--> time
    

    A concrete real-world illustration is standard CPython's Global Interpreter Lock (GIL) — a mutex allowing only one thread to execute Python bytecodes at once. Ten Python threads fetching REST APIs achieve high concurrency (threads release the GIL while waiting on network sockets), yet ten Python threads hashing passwords get zero parallel CPU speedup and require multiple processes (multiprocessing) or native C/Rust/CUDA code that releases the GIL. Match the tool to the bottleneck: concurrency hides I/O wait time; parallelism multiplies CPU throughput.

  5. A classic concurrency bug (lost update) and how to fix it

    The textbook bug is a data race causing a lost update during a non-atomic read-modify-write. Writing balance -= 80 or count += 1 looks like a single line in source code, yet compiles to three separate operations (READ from memory into a register, MODIFY in the ALU, WRITE back to memory). Without coordination, two threads interleave:

    Initial shared state: count = 5
    
    Time   Thread A                       Thread B                       Shared `count` in RAM
    ----   ----------------------------   ----------------------------   ---------------------
    t1     READ count -> regA = 5                                        5
    t2                                    READ count -> regB = 5         5
    t3     ADD 1 -> WRITE 6 to count                                     6
    t4                                    ADD 1 -> WRITE 6 to count      6  (1 increment lost!)
    

    In a banking or ticketing service, the exact same interleaving lets two simultaneous 80 USD withdrawals both pass if balance >= 80: against a 100 USD account, overdrawing the account or double-selling a single seat.

    Four standard mitigations (from finest-grained to architectural)

    1. Mutual exclusion (Lock / Mutex): Wrap the read-modify-write critical section in a lock so only one thread enters at a time.
    2. Hardware atomic instructions: For single counters or pointers, CPU atomic primitives (LOCK XADD / compare-and-swap via C++ std::atomic or Java AtomicLong) perform read-modify-write indivisibly in hardware without sleeping threads.
    3. Avoid shared mutable state: Give each worker thread a private counter and sum them periodically, or funnel updates as immutable messages to a single owning actor/thread.
    4. Database-level atomicity: Execute one conditional SQL update (UPDATE accounts SET balance = balance - 80 WHERE id = 1 AND balance >= 80) or use optimistic concurrency control (WHERE id = 1 AND version = 7), rather than reading in app code and writing back later.
    import threading
    
    
    class SafeCounter:
        def __init__(self) -> None:
            self.value = 0
            # Mutex ensuring only one thread executes the read-modify-write at once.
            self._lock = threading.Lock()
    
        def increment_buggy(self) -> None:
            # UNSAFE: read -> add 1 -> write can be interrupted mid-flight by another thread.
            self.value += 1
    
        def increment_safe(self) -> None:
            # SAFE: `with` acquires the lock before reading and releases it even on exceptions.
            with self._lock:
                self.value += 1
    

    (Bonus note if asked about lock risks: When threads acquire two or more locks in opposite orders — Thread 1 locks Account A then waits on Account B while Thread 2 locks Account B then waits on Account A — they freeze forever in a deadlock. Prevent deadlocks unconditionally by enforcing a strict global lock acquisition order, such as always locking the smaller account_id first.)*

  6. TCP vs. UDP, flow control, and congestion control

    1. Comparing TCP and UDP at the transport layer

    Feature TCP (Transmission Control Protocol) UDP (User Datagram Protocol)
    Connection setup Stateful 3-way handshake (1 RTT) before sending data Connectionless (0 RTT setup; send immediately)
    Reliability Guaranteed via sequence numbers, ACKs, and retransmissions Best-effort; lost packets are not retransmitted by the OS
    Ordering & framing Strictly ordered byte stream (app frames its own messages) Independent datagrams (preserves message boundaries; may reorder)
    Pacing Built-in flow control and congestion control None in kernel; application must pace itself
    Header & blocking 20–60 B header; head-of-line blocking on packet loss Lean 8 B header; a lost datagram never stalls later datagrams
    • Choose TCP whenever every byte must arrive intact and in sequence: HTTP/1.1 & HTTP/2 APIs, database drivers, SSH, file transfers, and financial order-entry protocols (such as FIX), where a dropped or reordered message is unacceptable.
    • Choose UDP when stale data is worse than missing data, multicast fan-out is needed, or a custom user-space protocol handles reliability: live voice/video calls (WebRTC — playing a retransmitted audio frame 150 ms late sounds worse than concealing a 20 ms gap), real-time multiplayer player positions, short DNS lookups, exchange market-data multicast feeds (paired with a separate gap-recovery channel), and QUIC / HTTP/3 (which builds stream-level reliability and TLS encryption in user space atop UDP).

    2. Flow control vs. congestion control

    Both cap how many unacknowledged bytes a TCP sender keeps in flight (bytes_in_flight <= min(cwnd, rwnd)), but they protect completely different bottlenecks:

    [TCP Sender]  =======( Network routers: protected by cwnd )=======>  [TCP Receiver RAM buffer]
      tracks cwnd                                                          advertises rwnd in ACKs
      (Congestion Control)                                                 (Flow Control)
    
    • Flow control protects the receiver from drowning when the receiving application reads socket buffers too slowly. Every ACK packet advertises the receiver's free buffer space (rwnd, scaled beyond 65,535 B up to ~1 GiB via the TCP Window Scale option). If rwnd hits 0, the sender pauses and sends tiny zero-window probes until buffer space opens.
    • Congestion control protects the intervening network from router queue collapse. Because no single router tells the sender the bottleneck link's spare capacity, the sender maintains a congestion window (cwnd):
      • Slow start: Begin conservatively (10 segments ≈ 14.6 KB on Linux) and double cwnd every round-trip time (RTT) as ACKs return cleanly.
      • Congestion avoidance & loss response: Above a threshold (ssthresh), grow cautiously (linearly in classic Reno; along a cubic curve in Linux's default CUBIC) and cut cwnd multiplicatively upon packet loss (0.5x in Reno, 0.7x in CUBIC on 3 duplicate ACKs; reset on timeout), or pace directly from measured bottleneck bandwidth and minimum RTT (BBR).

    Concrete Bandwidth-Delay Product (BDP = bandwidth * RTT) check: with an unscaled 64 KB (65,535 B) window across a 100 ms transcontinental link, throughput cannot exceed 65,535 B / 0.1 s ≈ 655 KB/s (5.24 Mbit/s) even on a 1 Gbit/s fiber pipe — saturating 1 Gbit/s at 100 ms requires 10^9 bit/s * 0.1 s = 100 Mbit = 12.5 MB of unacknowledged data in flight!

  7. URL to page, part 1: caches, DNS, and TCP + TLS handshakes

    Trace what happens from pressing Enter on https://app.example.com/dashboard:

    1. URL parsing, HSTS, and local caches: The browser parses scheme, host, and path. If example.com is on its HSTS (HTTP Strict Transport Security) list, plain http:// upgrades to https:// locally without touching the network. Next, the browser checks its in-memory/disk HTTP cache and any registered Service Worker; a fresh cache hit skips the network altogether.
    2. DNS lookup (domain name -> IP address): If neither the browser DNS cache nor the OS stub cache (/etc/hosts + OS resolver cache) holds a valid record within its TTL (Time-To-Live), the OS queries a recursive resolver (ISP, enterprise, or 1.1.1.1 / 8.8.8.8, over UDP port 53 or encrypted DNS-over-HTTPS). On a cache miss, the recursive resolver walks the hierarchy — Root (.) -> TLD (.com) -> Authoritative nameserver (ns1.example.com) — returning the A (IPv4) or AAAA (IPv6) address (often pointing to a nearby CDN edge).
    3. TCP 3-way handshake (1 RTT) + TLS 1.3 handshake (1 RTT): Before sending encrypted HTTP on a fresh TCP connection, client and server establish sequence numbers (SYN -> SYN-ACK -> ACK) and negotiate encryption keys in two network round trips, followed by a third round trip for the first HTTP response bytes:
    Timeline (fresh TCP + TLS 1.3 connection):
    Client                                                       Server / CDN Edge
      |--- SYN -------------------------------------------------->|  \  RTT 1: TCP 3-way
      |<-- SYN-ACK -----------------------------------------------|  /  handshake
      |--- ACK + TLS ClientHello (SNI, ALPN="h2", key share) ---->|  \  RTT 2: TLS 1.3
      |<-- ServerHello (key share) + Cert + Sig + Finished -------|  /  key exchange & auth
      |--- TLS Finished + HTTP GET /dashboard ------------------->|  \  RTT 3: HTTP request
      |<-- HTTP 200 OK + first compressed HTML bytes -------------|  /  (+ server app time)
    

    During TLS 1.3, the client sends SNI (Server Name Indication) so a shared IP knows which certificate to present, ALPN (Application-Layer Protocol Negotiation) to select h2 (HTTP/2) without an extra round trip, and an ephemeral Diffie-Hellman key share; it then verifies the server's certificate chain against trusted root Certificate Authorities. (TLS 1.2 needed 2 RTTs for TLS alone; HTTP/3 over QUIC merges transport + TLS 1.3 into a single 1 RTT handshake before the HTTP GET.)

  8. URL to page, part 2: HTTP exchange and browser rendering pipeline

    1. HTTP request and response

    Over the encrypted tunnel (as binary frames in HTTP/2 or HTTP/3, shown logically below), the browser requests the document and receives headers plus compressed HTML chunks:

    Request:                                      Response:
      GET /dashboard HTTP/2                         HTTP/2 200
      Host: app.example.com                         content-type: text/html; charset=utf-8
      accept: text/html                             content-encoding: br
      accept-encoding: br, gzip                     cache-control: private, max-age=0
      cookie: sid=...                               <Brotli-compressed HTML stream>
    

    On the backend, a CDN edge or L7 load balancer terminates TLS and forwards cache misses to stateless app servers reading from caches/databases. Remember status classes (2xx success, 3xx redirect costing extra RTTs, 4xx client error, 5xx server fault), conditional revalidation (ETag / 304 Not Modified), and HTTP/2 stream multiplexing, which fetches CSS, JS, and images concurrently over the same warm connection without repeating handshakes.

    2. Browser Critical Rendering Path (streaming incremental pipeline)

    The browser begins parsing the very first HTML chunk before the full response finishes downloading:

    HTML bytes -> Tokens -> DOM Tree  ----\
                                           +--> Render Tree -> Layout -> Paint -> GPU Composite
    CSS bytes  -> Rules  -> CSSOM Tree ---/      (visible      (boxes    (draw     (combine layers
    (render-blocking!)                            styles)      x,y,w,h)  commands)  onto screen)
    
    • DOM construction & preload scanner: The HTML parser builds the DOM (Document Object Model) tree while a lightweight preload scanner peeks ahead at <link>, <script>, and <img> tags to start subresource downloads immediately.
    • CSSOM construction (render-blocking): External <link rel="stylesheet"> files build the CSSOM (CSS Object Model). Browsers hold back first paint until CSSOM completes so users never see an ugly flash of unstyled text.
    • JavaScript execution (parser-blocking by default): A plain <script src="..."> pauses HTML parsing while it downloads and runs because JS can mutate the DOM or query styles. Adding defer downloads in parallel and executes in order after HTML parsing; async executes as soon as downloaded.
    • Style -> Layout (Reflow) -> Paint -> Composite: Combining DOM + CSSOM yields the Render Tree (excluding display: none nodes). Layout calculates exact (x, y, width, height) boxes; Paint records text, color, border, and shadow draw lists into layers; and the GPU compositor blends layers into 60–120 Hz screen frames. Animating transform or opacity skips Layout and Paint completely, whereas mutating width or reading element.offsetHeight right after a style edit triggers expensive synchronous reflow.
  9. Tie everything together: an end-to-end 50 ms RTT latency budget

    Unify all four answers into one concrete cold-visit timeline at 50 ms network RTT (with DNS cached at the local ISP resolver in 10 ms and 25 ms backend server execution):

    Step                                      Round trips / work          Elapsed time
    ----------------------------------------  --------------------------  ------------
    1. DNS lookup to warm recursive resolver  1 local UDP hop             10 ms
    2. TCP 3-way handshake                    1 RTT                       60 ms
    3. TLS 1.3 handshake                      1 RTT                       110 ms
    4. HTTP GET -> Time To First Byte (TTFB)  1 RTT + 25 ms backend       185 ms
    5. Download 100 KB compressed HTML+CSS    Slow start IW10 (~14.6 KB,  285 ms
       (3 flights: 14.6 + 29.2 + 58.4 KB)     so 2 extra RTTs after TTFB)
    6. Parse DOM/CSSOM, run JS, Layout/Paint  Browser main thread         ~330 ms -> First Paint!
    

    Every systems layer shows up in that 330 ms budget: TCP + TLS handshakes (100 ms) explain why keep-alive pooling and HTTP/3 (1 RTT setup) matter; TCP congestion slow start (100 ms after TTFB) explains why keeping critical HTML/CSS under ~14 KB saves full round trips; render-blocking CSS and parser-blocking JS govern when bytes turn into pixels; and OS processes, threads, and event loops explain how Chrome isolates tabs into separate processes while running each tab's DOM, JS, and Layout on a single main-thread event loop where any 200 ms CPU loop freezes scrolling.

Intuition & how it works

Picture a computer as an office building and the internet as the highway system connecting buildings. Inside the building, a process is a locked private suite with its own filing cabinets (its own isolated memory), whereas threads are coworkers inside the same suite sharing one big table and whiteboard — passing notes across the table is instant, but if two coworkers erase and update the same tally mark simultaneously without taking turns, they corrupt the count. When a browser thread needs a web page from a remote server building, it looks up the street address in a directory (DNS), agrees on a reliable delivery contract and locked courier pouch (TCP + TLS handshakes), fetches the blueprints (HTTP), and assembles walls, paint, and glass panels onto the screen (browser rendering pipeline).

Treating these layers as "free black boxes" causes classic production failures. Spawning 50,000 OS threads wastes gigabytes of stack memory and burns CPU cores swapping thread state instead of doing useful work; modifying shared state without synchronization silently drops financial or inventory updates under load; and opening fresh, unpooled HTTPS connections pays three full network round trips before the first byte of data even arrives. Understanding what happens in the kernel, on the wire, and on the browser's main thread lets you spot exactly which resource — CPU cores, memory caches, locks, round-trip latency, or packet loss — limits a system.

Trace one tiny concrete click on https://app.example.com/dashboard over a 50 ms round-trip network:

  1. Address & connection (0 -> 110 ms): The OS resolves app.example.com from a nearby DNS resolver (10 ms), completes a 1 RTT (50 ms) TCP handshake, and completes a 1 RTT (50 ms) TLS 1.3 encryption handshake.
  2. Request & slow-start transfer (110 -> 185 ms): The client sends GET /dashboard; after 50 ms on the wire plus 25 ms on the server (where worker threads query a shared cache under safe locks), the first ~14.6 KB window of compressed HTML arrives at 185 ms.
  3. Parse & style (185 -> 220 ms): Inside the tab's isolated renderer process, the main-thread event loop incrementally parses HTML into the DOM (tree of page elements) and CSS into the CSSOM (tree of visual styles).
  4. Layout, paint & composite (220 -> 235 ms): The browser calculates element coordinates (Layout), records drawing commands (Paint), and hands textures to a separate GPU process to Composite the final frame onto your monitor.

Key trade-offs

  • Processes vs. threads. A process isolates memory using hardware page tables (kernel maps from virtual addresses to physical RAM), containing crashes and memory bugs inside one process at the cost of heavier creation, context switches, and IPC (Inter-Process Communication) over pipes or sockets. Threads share one virtual address space for cheap creation and zero-copy memory sharing, trading away fault isolation and introducing data-race hazards.
  • OS thread-per-connection vs. async event loop. Dedicating one OS thread per client socket is straightforward to write, but tens of thousands of connections consume megabytes of per-thread stacks and trigger heavy kernel context switches (saving/restoring registers and evicting CPU caches). An event loop (single-threaded non-blocking I/O multiplexed via epoll / kqueue) handles tens of thousands of idle sockets with minimal memory, provided no handler ever runs a long CPU loop that stalls the thread.
  • Mutex locks vs. hardware atomics vs. share-nothing. A mutex (mutual exclusion lock) safely protects arbitrarily complex multi-variable invariants at the cost of serialization and deadlock risk (threads waiting in a cycle); atomic instructions (CPU-level indivisible read-modify-write primitives such as compare-and-swap) update a single counter or pointer with tiny overhead; share-nothing / message passing eliminates shared-memory races completely in exchange for copying or routing messages.
  • TCP vs. UDP. TCP provides guaranteed delivery, strict byte-stream ordering, and automatic congestion pacing at the cost of a 1 RTT setup handshake and head-of-line blocking (one lost packet stalls delivery of subsequent arrived bytes until retransmitted). UDP sends lean 8-byte-header datagrams (self-contained packets) with 0 RTT setup and zero head-of-line blocking, pushing loss handling, ordering, and rate pacing onto the application (or onto QUIC, HTTP/3's user-space transport built over UDP).
  • Flow control vs. congestion control. Flow control is exact: the receiver advertises its remaining socket buffer (rwnd) in every acknowledgment so a fast sender never overflows a slow reader's RAM. Congestion control (cwnd) is an inference loop probing unknown router queues across the internet — ramping aggressively fills high-bandwidth links faster after connection start, whereas ramping conservatively avoids packet drops and latency spikes for competing traffic.
  • TLS handshake round trips vs. replay safety. TLS 1.3 trimmed encryption setup from TLS 1.2's 2 RTTs down to 1 RTT; 0-RTT session resumption sends application data on the very first packet for returning clients, but an eavesdropper can replay that captured packet, restricting 0-RTT strictly to idempotent (safe-to-repeat) read requests.
  • Render-blocking correctness vs. fast first paint. Waiting for CSS before painting avoids a jarring flash of unstyled content (FOUC) at the cost of delaying initial pixels, while marking <script> tags defer or async unblocks the HTML parser in exchange for managing script execution order carefully.

Common mistakes

  • Saying threads "share all memory." Threads share code, globals, heap, and open file descriptors, never their call stacks, CPU registers, or thread-local storage — each thread needs its own stack to make independent function calls.
  • Reducing context-switch cost to "saving a few registers." Register save/restore takes nanoseconds; cross-process page-table switches, TLB (Translation Lookaside Buffer) misses, and reloading evicted L1/L2 CPU caches account for most of the real multi-microsecond slowdown.
  • Confusing a system call with a context switch. A non-blocking system call switches CPU privilege from user mode to kernel mode and returns to the same thread without invoking the scheduler or polluting caches with another task's working set.
  • Treating concurrency and parallelism as synonyms. An asyncio or Node.js server on a single-core VM is highly concurrent (interleaving thousands of waiting sockets) without executing anything in parallel; conversely, CPython threads give concurrency on I/O but cannot run Python bytecode in parallel across cores under the default GIL (Global Interpreter Lock).
  • Assuming count += 1 is atomic. High-level increment syntax compiles into separate LOAD, ADD, and STORE steps that interleave freely across threads unless guarded by a lock or atomic primitive.
  • Mixing up flow control (rwnd) and congestion control (cwnd). Flow control protects the receiver's memory buffer; congestion control protects network routers; actual bytes in flight are bounded by min(cwnd, rwnd).
  • Walking every DNS query from the root servers or quoting outdated TLS round trips. Thanks to TTL (Time-To-Live) caching, almost all lookups resolve from browser, OS, or ISP recursive caches, and modern HTTPS over TCP + TLS 1.3 takes 2 handshake RTTs (1 TCP + 1 TLS 1.3), not 3 or 4.
  • Stopping the URL-to-page walkthrough once HTML arrives. Interviewers explicitly look for the browser pipeline: DOM + CSSOM -> Render Tree -> Layout (reflow) -> Paint -> GPU Composite, plus why CSS blocks rendering and synchronous <script> blocks HTML parsing.

Follow-up questions

  • Why does HTTP/2 still suffer from head-of-line blocking, and how does HTTP/3 eliminate it? HTTP/2 multiplexes dozens of parallel request/response streams over a single TCP connection, which solves HTTP/1.1's application-level blocking where one slow response held up the socket. However, the OS kernel's TCP layer sees only one undifferentiated byte stream and refuses to hand later packets to the browser until a single lost packet is retransmitted (1+ RTT stall across every multiplexed CSS, JS, and image stream). HTTP/3 replaces TCP with QUIC over UDP, moving stream framing into user space so a lost UDP packet stalls only the single HTTP stream whose bytes were inside that packet while all sibling streams keep rendering.
  • How do you size a thread pool for CPU-bound work versus I/O-bound work? For purely CPU-bound tasks (image encoding, cryptographic hashing), size the pool near N_cores because extra runnable threads beyond physical cores cannot increase parallel throughput and only add context-switch and cache-thrashing overhead. For I/O-heavy handlers that spend most of their wall time blocked waiting on network or disk responses, Little's-law style sizing starts around N_cores * (1 + wait_time / cpu_time) — for instance, 8 cores running handlers that spend 5 ms on CPU and 45 ms waiting on RPCs keep roughly 8 * (1 + 9) = 80 threads productively utilized — though you should always cap and load-test against downstream bottlenecks like database connection limits.
  • What is the TCP TIME_WAIT state, and how can short-lived connections exhaust a server or proxy? Whichever side initiates an active TCP close (FIN) keeps the (local_ip, local_port, remote_ip, remote_port) 4-tuple reserved in TIME_WAIT (60 seconds on Linux) so stray delayed packets from the old connection cannot corrupt a newly opened connection reusing the same ports, and so the final ACK can be resent if lost. When a reverse proxy or microservice opens fresh unpooled TCP connections to a single upstream remote_ip:remote_port, Linux's default ephemeral port range (32768–60999, or 28,232 ports) caps throughput at 28,232 / 60 s ≈ 470 connections/second before connect calls fail with EADDRNOTAVAIL. The primary fix is HTTP keep-alive / connection pooling so thousands of requests reuse warm sockets instead of churning new TCP handshakes and TIME_WAIT entries.

Follow-up questions

Similar questions

More Citi interview questions

All 4 Citi questions →