title: Interview Questions in Essence: Network description: In Python interviews, language features are a must. Understanding these underlying mechanisms will not only help you cope with interviews, but also avoid writing bugs that are difficult to troubleshoot in actual development.

Hello everyone, I am the webmaster of "Interview Sprint Station". For Python back-end engineers, network knowledge often accounts for more than 25% in written tests and interviews. It is not only a "must order" for interviewers, but also a core weapon for you to understand Web architecture, troubleshoot online timeouts, cross-domain, and full connections.

Today, we use a popular hard-core tutorial to dismantle 10 high-frequency network test points, complete the logical links, and add some practical code to help you truly "explain clearly and thoroughly" the eight-part essay that you have memorized.


1. TCP three-way handshake: why not two or four?

To establish a reliable connection between the client and the server, they must first synchronize the sequence numbers "to the table". This confirmation process is a three-way handshake. The standard process is as follows:

  1. SYN (synchronization) Client sendsseq=x,EnterSYN_SENTstate. → After the server receives it, it knows that the sending ability of the client is normal**.

  2. SYN+ACK (synchronous confirmation) Server responseseq=y, and confirm the client’sack=x+1,EnterSYN_RCVDstate. → After the client receives it, it knows that the sending and receiving capabilities of the server are normal**.

  3. ACK (final confirmation) The client replies againack=y+1, both parties enterESTABLISHEDstate. → After the server receives it, it knows that the client’s receiving capability is also normal**.

Why doesn’t two handshakes work?

Mainly to prevent historical failed connection attacks**. Imagine: the network is congested, the client sends a SYN, waits for too long and gives up without a response. Then this "old SYN" suddenly arrived on the server. If there are only two handshakes, the server will immediately establish a connection and allocate resources once it receives the SYN, but the client has already ignored the connection, which wastes server resources. The extra last step of the three-way handshake, ACK, gives the server the opportunity to sense that "the client has not confirmed" and release the half-open connection in time to avoid malicious use.


2. TCP waves four times: Why wait for 2MSL in the end?

When closing the connection, both parties may still have data that has not been transmitted, so four steps are needed to release the connection:

  1. FIN: The client sends FIN and entersFIN_WAIT_1, telling the server "I have no data to send."
  2. ACK: The server confirms FIN and entersCLOSE_WAIT, meaning "I know, but I may still have data to send."
  3. FIN: After the server data is sent, it also sends FIN and entersLAST_ACK
  4. ACK: The client confirms the FIN of the server, then enters the TIME_WAIT state, and waits for 2MSL before closing.

2MSL’s dual role

  • Ensure that the last ACK can be delivered: If the last ACK is lost in the network, the server will resend the FIN, and the client can still receive and resend the ACK within 2MSL to ensure that the server shuts down normally.
  • Clear the "old connection fragments" in the network: Let all delayed packets of this connection disappear from the network to avoid receiving dirty data when new connections reuse the same port.

Note: MSL is the maximum packet survival time. Linux defaults to 30 seconds, so TIME_WAIT is usually 60 seconds.


3. HTTP Core: The Truth About GET vs POST

Stop blurting out "POST is safer than GET", look at the essential differences first:

FeaturesGETPOST
SemanticsSafe "read-only" operations (get resources)Unsafe "write" operations (create/modify/delete)
Impotence✅ Yes (results are consistent for multiple calls)❌ No (multiple submissions will create repeated orders)
Parameter locationURL query string (will be recorded and cached by the browser)Request body (will not be left in the history)
Data lengthLimited (browser + server dual limit, recommended <2KB)Theoretically unlimited, configurable upper limit (such as Nginxclient_max_body_size
Caching BehaviorCached by defaultUsually not cached unless explicitly specified

💡 Supplement: HTTPS will encrypt the entire message, including the POST body, but the domain names, ports, and paths of both parties are still transmitted in clear text during the TLS handshake phase.

If the interviewer asks "Why can GET send Body?", you can answer this: The HTTP specification does not prohibit GET from sending Body, but most proxies and servers will directly ignore it, so it is basically not used in practice.


HTTP is stateless. In order for the server to know that two consecutive requests come from the same user, a state management mechanism needs to be introduced. A comparison of the three mainstream solutions is as follows:

MethodStorage locationSecurityScalabilityTypical scenarios
CookieBrowser (can memory/disk)❌ Low: easy to be read by JS (unless addedHttpOnly), vulnerable to CSRF attacks✅ High: server-side statelesssmall amount of non-sensitive data (topics, language preferences)
SessionServer (Memory/Redis/File)✅ Medium and High: Sensitive information is stored on the server❌ Low: Shared storage is required under distributed conditionsTraditional single application, strong security requirements (bank)
JWTClient (Cookie/LocalStorage)✅ Medium: Payload is only Base64 encoded, signature is tamper-proof✅ Extremely high: naturally stateless, suitable for microservicesModern SPA, front-end and back-end separation, cross-domain authentication

Avoid pitfalls in actual combat

  • Be sure to add it when setting cookiesHttpOnlyAnti-theft reading,SecureForce HTTPS, andSameSite=LaxorStrictProtect against CSRF.
  • Do not set the JWT expiration time too long. It is best to use a combination of "short Token + refresh Token" to avoid the risk of leakage.

5. Load balancing: Why do major manufacturers prefer Nginx?

One sentence summary: **Nginx relies on asynchronous non-blocking (epoll) to achieve concurrency, and Apache relies on multi-process/thread heap stability. ** Nginx can handle tens of thousands of connections with a small number of fixed processes in high-concurrency scenarios, and its CPU and memory consumption are very low. It is especially suitable for reverse proxy and entry gateway.

Actual configuration: reverse proxy + polling load balancing

http {
    upstream python_backend {
        server 127.0.0.1:8000;
        server 127.0.0.1:8001;
        # ip_hash;   # 需要会话保持时可开启
    }

    server {
        listen 80;
        server_name example.com;

        location / {
            proxy_pass http://python_backend;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }
}

Configuration points:

  • upstreamDefine the backend server pool, polling by default, can be addedweightweight.
  • proxy_passForward the request to the backend and carry the real client IP to facilitate the backend to record logs or limit traffic.

6. HTTP status code cheat sheet (for high-frequency interviews, just remember these 7)

Status codeMeaningInterview scenario analysis
200 OKRequest successfulThe most basic success return, GET/POST common
301 Moved PermanentlyPermanent redirectionReplace old domain name with new domain name, HTTP upgrade HTTPS (search engines will transfer weight)
302 FoundTemporary redirectionJump to login page if not logged in (search engine does not transfer weight)
304 Not ModifiedThe cache is validThe resource has not changed, the server returns an empty Body to save traffic
403 ForbiddenInsufficient permissionsAuthenticated but no permissions (such as trying to access the administrator backend)
404 Not FoundThe resource does not existTriggered when the route is written incorrectly or the file is deleted
502 Bad GatewayThe gateway/agent cannot connect to the backendThe backend process (Gunicorn/Uvicorn) died
504 Gateway TimeoutGateway wait timeoutThe backend interface executes too slowly and exceeds the proxy's timeout threshold

If you can tell you the troubleshooting ideas for 502 and 504 (checking the survival of the back-end process and checking the interface time), the interviewer's favorability will soar.


7. Web security twins: XSS and CSRF

These two are basic questions that are often asked by development and security personnel. Clarifying the principles and defense methods is the most critical.

XSS (cross-site scripting attack)

Principle: The attacker injects malicious JS into the page, and the script is executed when the user visits. It can be used to steal cookies, tamper with the page, or redirect to a phishing site. Three major types:

  • Storage type (the most dangerous): The script is stored in the database and executed every time the page is accessed.
  • Reflective: execute immediately when parameters are passed in through the URL.
  • DOM type: Triggered when the DOM is manipulated through JS on the browser side.

Defense Strategy:

  1. Output encoding: Automatic escaping in templates (Flask's{{ }}Automatic escaping, enabled by django by default).
  2. Cookie addedHttpOnly: Disable JS from reading sensitive cookies.
  3. Enable CSP (Content Security Policy): Limit the sources of scripts, styles, images and other resources that can be loaded by the page.

CSRF (cross-site request forgery)

Principle: The attacker uses the user's logged-in identity (Cookie is automatically sent) to forge requests on third-party sites, such as secretly transferring money or changing passwords.

Defense Strategy:

  1. CSRF Token: Every form submission or non-idempotent request must carry a random Token generated by the server (django and Flask have ready-made plug-ins).
  2. Check Referer/Origin: Verify whether the request source is trustworthy (but may be tampered with).
  3. Cookie addedSameSite: Set toLaxorStrict, restricting automatic carrying of cookies when making cross-site requests.

8. Synchronous vs. asynchronous: WSGI vs. ASGI

Two protocols that cannot be avoided in Python web development can be distinguished in one sentence:

  • WSGI: Traditional synchronization model, one thread is requested at a time, and WebSocket equal-length connections are not supported.
  • ASGI: asynchronous model, native supportasync/await, one thread can handle massive concurrency, and supports HTTP, WebSocket, SSE, etc.

Applicable framework

ProtocolRepresentation FrameworkFeatures
WSGIdjango (early stage), FlaskMature ecology, average performance
ASGIFastAPI, django ≥3.2High concurrency, native support for WebSocket, first choice for real-time applications

Don’t forget to add during the interview: Using ASGI needs to be deployed on a server that supports the protocol, such as Uvicorn or Daphne, and you cannot continue to use Gunicorn (unless paired with Uvicorn worker).


9. *NIX Inter-Process Communication (IPC): Occasionally tested for back-end advancement

When writing multi-process programs, you may encounter these IPC methods. Focus on mastering their characteristics:

MethodSpeed ​​Core LimitationsApplicable Scenarios
PipeMediumCan only be used for parent-child/sibling processes, half-duplexSimple data transfer
Shared Memory🚀 FastestNeed to handle locks yourself to prevent data competitionLarge amounts of data sharing (image processing, scientific computing)
SocketSlower-Cross-process, cross-machine communication, the cornerstone of distributed systems
Semaphore-Only synchronization, no data transmissionProcess synchronization and resource control

In Python you can passmultiprocessingModules easily use pipes, shared memory and locks, while message queues or Redis are more commonly used in distributed scenarios.


Okay, that’s it for today’s online interview questions! I hope this review can help you build a skeleton of knowledge and no longer memorize it by rote. If you find it useful, please like, collect, and forward it to friends who are looking for jobs~

Next time we will talk about "Python language features high-frequency interview questions", see you there!