Decompose a Flask app into processes, sockets, TCP, TLS, HTTP, bytes, kernel buffers and fsync calls, with real strace, ss and /proc output from a working two-service lab.
Two engineers look at the same Flask service. The first sees a route decorator, a JSON body and a call to requests.post(). The second sees a process with four file descriptors, a listening socket in the kernel's table, a TCP handshake, a TLS session negotiated with X25519, 48 bytes of JSON wrapped in a 70-byte encrypted record, and a database commit that waits on four disk flushes.
Both engineers can ship the feature. Only the second one can tell you why it takes 38 ms, why it fails with CERTIFICATE_VERIFY_FAILED in staging, and why it falls over at 1,000 requests per second.
This article teaches you how to become the second engineer. We will take one small, realistic system and peel it apart one layer at a time. Everything you see here was run on a real Linux machine (Ubuntu, kernel 6.18, Python 3.12, OpenSSL 3.0). The strace, ss and /proc output is real, not invented.
The scenario used throughout: Service A is a Flask app. It receives a message, counts the words, and sends the result over HTTPS to Service B. Service B adds a timestamp and stores the record in SQLite. Service A trusts Service B because B's certificate is signed by a private Root CA.
Here is the whole system as most developers see it. Service A:
from flask import Flask, request, jsonify
import requests
app = Flask(__name__)
SERVICE_B = "https://localhost:8443/store"
ROOT_CA = "rootCA.crt"
@app.post("/message")
def message():
text = request.get_json()["text"]
payload = {"text": text, "word_count": len(text.split())}
r = requests.post(SERVICE_B, json=payload, verify=ROOT_CA, timeout=5)
return jsonify(r.json()), r.status_code
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)
Service B:
from flask import Flask, request, jsonify
from datetime import datetime, timezone
import sqlite3
app = Flask(__name__)
db = sqlite3.connect("messages.db", check_same_thread=False)
db.execute("CREATE TABLE IF NOT EXISTS messages "
"(id INTEGER PRIMARY KEY, text TEXT, word_count INT, received_at TEXT)")
@app.post("/store")
def store():
data = request.get_json()
data["received_at"] = datetime.now(timezone.utc).isoformat()
with db: # commits the transaction
cur = db.execute("INSERT INTO messages (text, word_count, received_at) VALUES (?, ?, ?)",
(data["text"], data["word_count"], data["received_at"]))
data["id"] = cur.lastrowid
return jsonify(data), 201
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8443, ssl_context=("service-b.crt", "service-b.key"))
And the certificates, created with OpenSSL:
# A private Root CA (the thing everyone agrees to trust)
openssl req -x509 -newkey rsa:2048 -nodes -keyout rootCA.key -out rootCA.crt \
-days 365 -subj "/CN=Demo Root CA"
# Service B's key and a certificate signed by the Root CA
openssl req -newkey rsa:2048 -nodes -keyout service-b.key -out service-b.csr -subj "/CN=service-b"
printf "subjectAltName=DNS:service-b,DNS:localhost,IP:127.0.0.1\n" > san.ext
openssl x509 -req -in service-b.csr -CA rootCA.crt -CAkey rootCA.key -CAcreateserial \
-out service-b.crt -days 90 -extfile san.ext
One request through the system:
$ curl -s -X POST localhost:5000/message -H 'Content-Type: application/json' \
-d '{"text":"the quick brown fox"}'
{"id":1,"received_at":"2026-11-30T19:01:27.924930+00:00","text":"the quick brown fox","word_count":4}
It works. For an application-level thinker, the story ends here.
A systems engineer reads the same curl command and sees a stack:
What the code says What actually happens
βββββββββββββββββββββ βββββββββββββββββββββββββββββββββββββββββββββ
@app.post("/message") βββΆ a process with a listening socket on :5000
request.get_json() βββΆ recvfrom() of 167 bytes, parsed as HTTP, then JSON
len(text.split()) βββΆ pure CPU work in the Python interpreter
requests.post(https://β¦) βββΆ socket() + connect() + TCP handshake
+ TLS 1.3 handshake + certificate chain check
+ encrypt + write() of TLS records
with db: INSERT β¦ βββΆ open journal, pwrite() pages, fdatasync() Γ4,
unlink journal
return jsonify(β¦), 201 βββΆ sendto() of headers and body, TCP FIN, TIME-WAIT
Neither view is wrong. The application view is how you build. The systems view is how you debug, scale and reason about what you built. Senior engineers switch between the two without thinking about it.
Every serious production incident happens below the code that the developer wrote. The code says requests.post(). The incident says "connection reset by peer", "too many open files", "certificate has expired", or "p99 latency doubled after the storage migration". None of those words appear in your source file.
An engineer who can only think at the framework level is stuck when the framework's abstraction leaks. An engineer who thinks in layers has a map: they know which layer produces which symptom, which tool can see into it, and what "normal" looks like there.
| Situation | Application-level thinking | Systems-level thinking |
|---|---|---|
| "It's slow" | "Let's add caching." | "Which layer is the time in? DNS, connect, TLS, server, or disk?" |
| "It can't connect" | "Service B is down." | "Refused (RST), timeout (dropped), or DNS failure? Each is a different layer." |
| "Works on my machine" | "Environment issue." | "Different CA bundle, different DNS resolver, different ulimit, different kernel?" |
| "Random 502s" | "Flaky network." | "Is the backend closing keep-alive connections the proxy still reuses?" |
The whole skill reduces to one habit. Whenever you see an abstraction, ask: what is this made of? Then ask it again, one level lower, until you hit hardware.
You do not need to know every layer in depth on day one. You need to know the layers exist, roughly what each one does, and which tool lets you look at it.
| You see | One layer below | Another layer below |
|---|---|---|
| Flask route | A WSGI server (Werkzeug, Gunicorn) calling your function with an environ dict |
A socket accept() loop and an HTTP parser reading bytes |
| Docker container | A normal Linux process | The same process with namespaces (its own view of PIDs, network, mounts) and cgroups (resource limits) |
| Kubernetes Service | A virtual IP | iptables/IPVS/eBPF rules that rewrite packet destinations to pod IPs |
| HTTPS | HTTP inside TLS | TLS records over a TCP byte stream |
| DNS lookup | getaddrinfo() in libc |
/etc/hosts, then UDP packets to the resolver in /etc/resolv.conf |
| Database commit | "Data is saved" | write() into the page cache, then fsync() forcing it to the disk |
Pro tip: A good test of whether you understand a layer: can you name a failure that is born there, and a command that shows it? If you can, you own that layer. If you can't, that's your next thing to learn.
We will walk down this stack. Each section ends with what an average developer thinks versus what a systems engineer thinks.
ββββββββββββββββββββββββββββββββββββββββββββββ
β Your code (Flask routes, business logic) β
ββββββββββββββββββββββββββββββββββββββββββββββ€
β Serialization: JSON β bytes (UTF-8) β Β§9
β HTTP: request line, headers, body β Β§8
β TLS: certificates, keys, encryption β Β§7
β TCP: reliable ordered byte stream β Β§6
β Sockets and file descriptors β Β§5
β Ports and listeners β Β§4
β Processes β Β§3
βββββββββββββββββ system call boundary βββββββ€
β Kernel: network stack, page cache, VFS β Β§10, Β§11
ββββββββββββββββββββββββββββββββββββββββββββββ€
β Hardware: CPU, NIC, disk β
ββββββββββββββββββββββββββββββββββββββββββββββ
The numbering of "layers" in this article follows the order that makes the scenario easy to explain. It is not the OSI model. The point is the habit, not the numbering.
When you run python service_a.py, Linux creates a process: a running program with its own address space (memory), its own table of open files, one or more threads, and a set of credentials (user, group). The kernel gives it a number, the PID.
Everything else in this article belongs to a process. A socket is owned by a process. A TLS session lives in a process's memory. When people say "the service is running", what they mean is "a process exists and is in a healthy state".
$ ps -o pid,ppid,user,stat,rss,cmd -C python
PID PPID USER STAT RSS CMD
6429 6422 ytamang SN 33756 python service_b.py
6430 6422 ytamang SN 37400 python service_a.py
Every column tells you something:
| Column | Meaning | Why you care |
|---|---|---|
PID |
Process ID | The handle for every other tool: /proc/PID, kill, strace -p, ss -p |
PPID |
Parent's PID | Who started it. A shell, systemd, or (in a container) the container's PID 1 |
STAT |
State: S sleeping (the N here means it runs at low priority, "niced"), R running, D uninterruptible (usually waiting on disk), Z zombie |
Lots of D means I/O trouble. Z means a parent isn't reaping children |
RSS |
Resident memory in KB | About 35 MB for a tiny Flask app, mostly the interpreter and imported modules |
htop shows the same thing live and lets you press F5 for a tree view and H to show threads. The kernel's own view is in /proc. (For the rest of the article I restarted both services under strace, so their PIDs are now 6587 for Service B and 6588 for Service A.)
$ grep -E '^(Name|State|Pid|PPid|Threads|VmRSS)' /proc/6588/status
Name: python
State: S (sleeping)
Pid: 6588
PPid: 6581
VmRSS: 36076 kB
Threads: 1
State: S (sleeping) is the healthy idle state for a server: it is blocked inside accept(), waiting for a connection, using zero CPU.
python service_a.py looks instant, but it is a lot of work. I traced the startup of Service A with strace:
strace -f -tt -e trace=network,read,write,close,openat -o straceA.txt python service_a.py
From the first syscall to bind() on port 5000 took about 0.5 seconds (strace itself slows every syscall down, so the real figure is lower). In that time the process opened 376 files:
openat total: 376 .pyc (compiled Python modules): 293 .so (shared libraries): 25
The sequence is always the same:
shell kernel new process
β fork() ββββββββΆ copy of the shell process
β execve("python")βΆ replace it with the python binary
β β
β βββΆ dynamic loader opens /etc/ld.so.cache,
β β libm.so.6, libc.so.6 β¦ and maps them into memory
β βββΆ interpreter initialises, imports site, encodingsβ¦
β βββΆ your imports: flask β werkzeug β jinja2 β β¦
β β requests β urllib3 β ssl β _ssl.so (OpenSSL)
β βββΆ socket() β bind(0.0.0.0:5000) β listen()
β βββΆ accept() β¦ sleeps here until a client connects
Two lines from the real trace show the requests library pulling OpenSSL into the process:
openat(AT_FDCWD, "/usr/lib/python3.12/__pycache__/ssl.cpython-312.pyc", O_RDONLY|O_CLOEXEC) = 3
openat(AT_FDCWD, "/usr/lib/python3.12/lib-dynload/_ssl.cpython-312-x86_64-linux-gnu.so", O_RDONLY|O_CLOEXEC) = 3
This is why "cold start" matters in serverless platforms, why a container's first request is slow, and why a missing .so file produces an ImportError that has nothing to do with your code.
When the request arrived, the trace showed a different ID handling it:
6588 accept4(3, {β¦ sin_port=htons(50046), sin_addr=inet_addr("127.0.0.1")}, β¦) = 4
6628 recvfrom(4, "POST /message HTTP/1.1\r\nHost: lo"..., 8192, 0, NULL, NULL) = 167
Thread 6588 (the main thread) accepted the connection; thread 6628 read and handled it. Flask's development server is threaded: it starts one thread per request. Threads share the process's memory and file descriptors. That is why thread 6628 can read fd 4, which thread 6588 created.
| Average developer | Systems engineer | |
|---|---|---|
| Starting the app | "I ran python app.py." |
"A process was created with fork/execve. It loaded 25 shared libraries and 293 modules, and now it is sleeping in accept()." |
| "Is it running?" | "The terminal didn't crash." | "Is the PID alive, in state S, with a listening socket, and not restarting in a loop?" |
| Concurrency | "Flask handles requests." | "The dev server spawns a thread per request. Gunicorn would fork worker processes. Those behave differently under load and with shared state like our SQLite handle." |
app.run(port=5000) hides three system calls. The trace shows them exactly:
socket(AF_INET, SOCK_STREAM|SOCK_CLOEXEC, IPPROTO_IP) = 3
bind(3, {sa_family=AF_INET, sin_port=htons(5000), sin_addr=inet_addr("0.0.0.0")}, 16) = 0
listen(3, 128) = 0
socket() asks the kernel for a new TCP endpoint (SOCK_STREAM = TCP). The kernel returns a small integer, 3, the file descriptor.
bind() attaches that socket to an address and port: 0.0.0.0:5000. 0.0.0.0 means "every IPv4 address this machine has". If you bound to 127.0.0.1, only local clients could reach it. That is the most common "works locally, unreachable in Docker" bug: the app binds to 127.0.0.1 inside the container, and nothing outside the container can connect.
listen(3, 128) flips the socket into passive mode and gives it a backlog: a queue for connections that have completed the TCP handshake but haven't been picked up by the application yet. The real limit is min(128, net.core.somaxconn).
accept() (we saw accept4 above) takes one completed connection off that queue and returns a new socket, fd 4, for talking to that one client. The listening socket stays open for the next one.
kernel process (Service A)
client SYN ββββΆ βββββββββββββββββββββββ
β SYN queue β handshake in progress
client ACK ββββΆ βββββββββββββββββββββββ€
β accept queue β handshake done, waiting βββ accept()
β (backlog β€ 128) β for the application returns fd 4
βββββββββββββββββββββββ
listening socket fd 3 stays put and keeps receiving new clients
The key insight: the kernel completes the TCP handshake, not your application. Clients can connect even while your Python code is busy. They wait in the accept queue. If the queue fills, the kernel starts dropping new SYNs, and clients see slow connects or timeouts. Your application logs show nothing, because your application never saw them.
ss and netstat$ ss -tlnp
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 128 0.0.0.0:5000 0.0.0.0:* users:(("python",pid=6588,fd=3))
LISTEN 0 128 0.0.0.0:8443 0.0.0.0:* users:(("python",pid=6587,fd=4))
The flags: -t TCP, -l listening only, -n numeric (don't resolve names), -p show the owning process. On a LISTEN socket, Send-Q is the backlog size (128) and Recv-Q is how many connections are currently waiting in the accept queue. A Recv-Q that stays above zero on a listener means your app isn't calling accept() fast enough.
netstat -tlnp shows the same thing. It's older (from the net-tools package) and is missing on many minimal images. Learn ss. Two counters tell you if the accept queue has ever overflowed:
$ nstat -az | grep -E 'ListenOverflows|ListenDrops'
TcpExtListenOverflows 0 0.0
TcpExtListenDrops 0 0.0
| Average developer | Systems engineer | |
|---|---|---|
port=5000 |
"Flask is on port 5000." | "A socket is bound to 0.0.0.0:5000 with a backlog of 128. The kernel handshakes clients for me and queues them until I accept()." |
| "Address already in use" | "Something weird, restart the laptop." | "Another socket owns that port. ss -tlnp 'sport = :5000' names the PID." |
| Unreachable from outside | "Firewall?" | "First check the bind address. 127.0.0.1:5000 is invisible from other hosts and other containers." |
In Linux, a process doesn't hold sockets, files or pipes directly. It holds file descriptors: small integers that index into a per-process table that the kernel maintains. read(), write() and close() work the same way on all of them. That uniformity is one of Unix's best ideas.
You can see the table under /proc/PID/fd:
Home directory paths are shortened to ~/lab below:
$ ls -l /proc/6588/fd # Service A, idle
0 -> /dev/null
1 -> ~/lab/a.log
2 -> ~/lab/a.log
3 -> socket:[41448]
$ ls -l /proc/6587/fd # Service B, idle
0 -> /dev/null
1 -> ~/lab/b.log
2 -> ~/lab/b.log
3 -> ~/lab/messages.db
4 -> socket:[38467]
Read it like a systems engineer:
/dev/null and both outputs go to a log file. That's why print() ends up in a.log.sqlite3.connect() opened it at import time. fd 4 is B's listening socket.socket:[41448] doesn't point to a path. 41448 is an inode number in the kernel's internal socket filesystem. You can find the same inode in the kernel's TCP table:
$ grep " 41448 " /proc/net/tcp
5: 00000000:1388 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 41448 β¦
Decode it by hand once, and you'll never forget it:
| Field | Raw value | Meaning |
|---|---|---|
local_address |
00000000:1388 |
IP 0.0.0.0, port 0x1388 = 5000 |
rem_address |
00000000:0000 |
no peer (it's a listener) |
st |
0A |
TCP state 10 = LISTEN (01 is ESTABLISHED, 06 TIME_WAIT) |
uid |
1000 |
owning user |
inode |
41448 |
the same number as in /proc/6588/fd/3 |
This is exactly how ss -p and lsof find the owning process: they read /proc/net/tcp and match inodes against every /proc/*/fd.
process 6588 kernel
ββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββ
β fd table β β struct socket (inode 41448) β
β 0 β /dev/nullβ β ββ struct sock (TCP) β
β 1 β a.log β β state: LISTEN β
β 2 β a.log β β local: 0.0.0.0:5000 β
β 3 βββββββββββΌβββββββββΆ β accept queue, receive buffer, β
ββββββββββββββββ β send buffer, timersβ¦ β
ββββββββββββββββββββββββββββββββββββββββββ
Every connection costs a descriptor. Every open file costs one. The per-process limit is right there in /proc:
$ grep 'open files' /proc/6588/limits
Max open files 1048576 1048576 files
That's generous. Many systems still default to 1024. To see what happens at the limit, I lowered it to 64 and opened sockets in a loop:
$ (ulimit -n 64; python -c '
import socket
socks = []
try:
while True: socks.append(socket.socket())
except OSError as e: print(len(socks), "sockets, then:", repr(e))')
61 sockets, then: OSError(24, 'Too many open files')
61 sockets plus stdin, stdout and stderr = 64. Error 24 is EMFILE. We'll come back to this in the debugging section.
| Average developer | Systems engineer | |
|---|---|---|
| A connection | "An HTTP call." | "An fd pointing at a kernel socket object with its own buffers, state and timers." |
sqlite3.connect() |
"A DB connection." | "An openat() of messages.db, which holds fd 3 for the life of the process." |
| "Too many open files" | "Raise the limit." | "Something is leaking fds or holding connections open. ls /proc/PID/fd | wc -l over time tells you which." |
IP delivers individual packets with no guarantees: packets get lost, duplicated or reordered. TCP turns that into a reliable, ordered byte stream between two sockets. It does this with sequence numbers, acknowledgements, retransmissions, and flow and congestion control.
Note the words "byte stream". TCP has no idea where one HTTP request ends and the next begins. That's the job of the protocol above it.
When Service A calls requests.post("https://localhost:8443/β¦"), the trace shows:
socket(AF_INET, SOCK_STREAM|SOCK_CLOEXEC, IPPROTO_TCP) = 5
setsockopt(5, SOL_TCP, TCP_NODELAY, [1], 4) = 0
connect(5, {sa_family=AF_INET, sin_port=htons(8443), sin_addr=inet_addr("127.0.0.1")}, 16)
= -1 EINPROGRESS (Operation now in progress)
getsockopt(5, SOL_SOCKET, SO_ERROR, [0], [4]) = 0
connect() returned EINPROGRESS because urllib3 uses a non-blocking connect so it can enforce our timeout=5. The kernel ran the handshake in the background. SO_ERROR = 0 confirms that it succeeded. Meanwhile, Service B's side shows the other end:
accept4(4, {sa_family=AF_INET, sin_port=htons(47920), sin_addr=inet_addr("127.0.0.1")}, β¦) = 5
Port 47920 is the ephemeral port that the kernel picked for Service A's end of the connection (from net.ipv4.ip_local_port_range, here 32768β60999). A TCP connection is identified by four numbers: 127.0.0.1:47920 β 127.0.0.1:8443.
The handshake itself:
Service A (client) Service B (server)
127.0.0.1:47920 127.0.0.1:8443
β β LISTEN
SYN_SENT β ββ SYN seq=x βββββββββββββββββββββββββββββββββββΆβ
β β SYN_RECV
ββββββββββββββββββββββββ SYN-ACK seq=y, ack=x+1 ββ β
ESTABLISHEDββ ACK ack=y+1 βββββββββββββββββββββββββββββββββββΆβ
β β ESTABLISHED
β β (goes to accept queue)
βββββββββββ data flows both ways (TLS, then HTTP) ββ
β β
βββ FIN βββββββββββββββββββββββββββββββββββββββββββΆβ whoever closes first
βββββββββββββββββββββββββββββββββββββββββββ ACK ββ β ends up in TIME_WAIT
βββββββββββββββββββββββββββββββββββββββββββ FIN ββ β
TIME_WAIT βββ ACK βββββββββββββββββββββββββββββββββββββββββββΆβ CLOSED
Why three steps? Each side has to pick a random starting sequence number and confirm that the other side received it. The SYN carries A's number, the SYN-ACK confirms it and carries B's number, and the final ACK confirms B's. After that, every byte has a sequence number, so lost or reordered segments can be detected and fixed.
Cost: one full round trip before any data can be sent. On loopback that's microseconds. Between continents it's 100β200 ms, before TLS adds its own round trip.
ssI opened a connection to Service A and left it idle, then listed every socket touching our two ports:
$ ss -tanpo '( sport = :5000 or dport = :5000 or sport = :8443 or dport = :8443 )'
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 128 0.0.0.0:5000 0.0.0.0:* users:(("python",pid=6588,fd=3))
LISTEN 0 128 0.0.0.0:8443 0.0.0.0:* users:(("python",pid=6587,fd=4))
ESTAB 0 0 127.0.0.1:5000 127.0.0.1:38020 users:(("python",pid=6588,fd=4))
ESTAB 0 0 127.0.0.1:38020 127.0.0.1:5000 users:(("python",pid=6841,fd=3))
TIME-WAIT 0 0 127.0.0.1:40214 127.0.0.1:8443 timer:(timewait,37sec,0)
TIME-WAIT 0 0 127.0.0.1:40224 127.0.0.1:8443 timer:(timewait,37sec,0)
TIME-WAIT 0 0 127.0.0.1:40238 127.0.0.1:8443 timer:(timewait,37sec,0)
TIME-WAIT 0 0 127.0.0.1:8443 127.0.0.1:40750 timer:(timewait,49sec,0)
Notice:
5000β38020 owned by the server, 38020β5000 owned by the client). On loopback you see both ends on the same machine.requests.post() without a Session opens a new TCP connection and a new TLS handshake per call, then closes it. At 1,000 requests per second, that's 60,000 sockets in TIME-WAIT, right at the edge of the 28,000-port ephemeral range. The fix is one line: use a requests.Session() so connections get reused.strace shows what the process asked for. tcpdump shows what actually went on the wire. Capture the TCP control packets between A and B:
sudo tcpdump -i lo -nn 'tcp port 8443 and (tcp[tcpflags] & (tcp-syn|tcp-fin|tcp-rst) != 0)'
The output has this shape (this example is illustrative; the ports match our trace):
19:01:27.909450 IP 127.0.0.1.47920 > 127.0.0.1.8443: Flags [S], seq 3011857142, win 65495, options [mss 65495,sackOK,TS β¦,nop,wscale 7], length 0
19:01:27.909462 IP 127.0.0.1.8443 > 127.0.0.1.47920: Flags [S.], seq 1250193478, ack 3011857143, win 65483, options [mss 65495,β¦], length 0
19:01:27.909473 IP 127.0.0.1.47920 > 127.0.0.1.8443: Flags [.], ack 1, win 512, length 0
[S] is SYN, [S.] is SYN-ACK, [.] is a bare ACK, [F.] is FIN, [R] is RST. Note ack 3011857143: that's the client's sequence number plus one, exactly as in the diagram. Loopback's MSS is 65495 because the lo interface has a 65536-byte MTU; on Ethernet you'd see 1460.
For deeper analysis, write the capture to a file and open it in Wireshark:
sudo tcpdump -i any -w capture.pcap port 8443
# then open capture.pcap in Wireshark, filter with: tcp.port == 8443
Wireshark decodes every layer, can draw a flow graph (Statistics β Flow Graph), and highlights retransmissions and zero-window events in color. With the session keys it can even decrypt TLS (see SSLKEYLOGFILE in the next section).
| Average developer | Systems engineer | |
|---|---|---|
requests.post() |
"An HTTP request." | "A non-blocking connect(), a three-way handshake, a new ephemeral port, and afterwards a TIME-WAIT entry for 60 seconds." |
| Latency | "The API is slow." | "Every new connection pays one RTT for TCP and one more for TLS before the first byte of HTTP. Reuse connections." |
ss output |
(never ran it) | "Many TIME-WAITs on the client side: no connection reuse. Growing Recv-Q on ESTAB: the app isn't reading." |
TLS gives a TCP connection three properties: confidentiality (nobody can read it), integrity (nobody can change it without detection), and authentication (Service A knows it's really talking to Service B, not an impostor).
The first two come from encryption. The third comes from certificates, and it's where most real-world TLS failures happen.
A certificate is a signed statement: "the public key inside me belongs to the name service-b, and whoever signed me vouches for that." Ours:
$ openssl x509 -in service-b.crt -noout -subject -issuer -dates -ext subjectAltName
subject=CN = service-b
issuer=CN = Demo Root CA
notBefore=Nov 30 19:00:54 2026 GMT
notAfter=Feb 28 19:00:54 2027 GMT
X509v3 Subject Alternative Name:
DNS:service-b, DNS:localhost, IP Address:127.0.0.1
The Root CA is a certificate that signed itself. It can't be verified by anyone else. It's trusted because someone decided to trust it, by putting it in a trust store. Your browser trusts about 150 public Root CAs that ship with the OS. Service A trusts exactly one, because we told it to:
requests.post(SERVICE_B, json=payload, verify="rootCA.crt")
ββββββββββββββββββββββββββββ
β Demo Root CA β self-signed; trusted because Service A
β public key: K_root β was configured with rootCA.crt
ββββββββββββββ¬ββββββββββββββ
β signs (with K_root's private key)
βΌ
ββββββββββββββββββββββββββββ
β service-b β presented by Service B during the handshake
β SAN: localhost, β¦ β
β public key: K_b β
β signature by Root CA β
ββββββββββββββββββββββββββββ
You can verify the chain offline:
$ openssl verify -CAfile rootCA.crt service-b.crt
service-b.crt: OK
When Service A receives B's certificate, the TLS library checks all of the following, and any one failing aborts the connection:
| Check | Fails as |
|---|---|
| The signature on B's cert verifies with a public key from a trusted root (possibly through intermediates) | unable to get local issuer certificate |
Current time is between notBefore and notAfter |
certificate has expired / not yet valid |
| The hostname you connected to matches a Subject Alternative Name | Hostname mismatch / IP address mismatch |
| The server proves it has the private key for K_b (the CertificateVerify signature) | handshake failure |
Note the last row: a certificate is public. Anyone can send you B's certificate. What makes the connection safe is that the server must sign the handshake with the matching private key, which only the real Service B has.
openssl s_client -msg prints each handshake message as it happens. Against Service B:
$ openssl s_client -connect localhost:8443 -CAfile rootCA.crt -msg
>>> TLS 1.3, Handshake [length 0120], ClientHello
<<< TLS 1.3, Handshake [length 007a], ServerHello
<<< TLS 1.3, Handshake [length 0006], EncryptedExtensions
<<< TLS 1.3, Handshake [length 0333], Certificate
<<< TLS 1.3, Handshake [length 0108], CertificateVerify
<<< TLS 1.3, Handshake [length 0034], Finished
>>> TLS 1.3, ChangeCipherSpec [length 0001]
β¦
depth=1 CN = Demo Root CA
verify return:1
depth=0 CN = service-b
verify return:1
Peer signature type: RSA-PSS
Server Temp Key: X25519, 253 bits
Verification: OK
New, TLSv1.3, Cipher is TLS_AES_256_GCM_SHA384
Here's what each message does:
Service A (client) Service B (server)
β β
βββ ClientHello βββββββββββββββββββββββββββββββββββββββββββΆβ
β β’ TLS versions + cipher suites I support β
β β’ SNI: "localhost" (which site I want) β
β β’ key_share: my ephemeral X25519 public key (a) β
β β
ββββββββββββββββββββββββββββββββββββββββββββ ServerHello βββ
β β’ chosen: TLS 1.3, TLS_AES_256_GCM_SHA384 β
β β’ key_share: server's ephemeral X25519 public key (b) β
β β
β Both sides now compute the same shared secret from (a,b)β
β βββ everything after this point is encrypted βββ β
β β
ββββββββββββββββββββββββββββββββββ EncryptedExtensions ββββ
ββββββββββββββββββββββββββββββ Certificate (service-b) ββββ
βββββββββββ CertificateVerify (signature with B's key) ββββ
ββββββββββββββββββββββββββββββ Finished (MAC of all) ββββββ
β β
β Client validates the chain to rootCA.crt, checks β
β hostname + dates, verifies the signature β
β β
βββ Finished ββββββββββββββββββββββββββββββββββββββββββββββΆβ
βββββββββββ application data (HTTP), AES-256-GCM βββββββββββ
Session key creation is the clever part. Neither side ever sends the key. Each generates a throwaway (ephemeral) X25519 key pair and sends only the public half. Using Diffie-Hellman maths, each side combines its own private half with the other's public half and arrives at the same shared secret. An eavesdropper who saw both public halves can't compute it. TLS 1.3 feeds that secret through HKDF to derive the actual encryption keys. Because the key pairs are thrown away after the handshake, a stolen server private key later can't decrypt recorded traffic. That property is forward secrecy.
So what's B's long-term RSA key for? Only signing (CertificateVerify), to prove identity. It never encrypts the session key in TLS 1.3.
The same handshake is visible from inside Service A as raw write() and read() calls on fd 5. The first byte of every TLS record is its type: \26 (octal 26 = 0x16) is a handshake record, and \27 (0x17) is encrypted application data:
write(5, "\26\3\1\2\0\1\0\1\374\3\3β¦", 517) = 517 β ClientHello: type 0x16, length 0x0200 = 512 (+5 header)
read(5, "\26\3\3\0z", 5) = 5 β ServerHello record header: length 0x7a = 122
read(5, "\2\0\0v\3\3u\6\34=β¦", 122) = 122 β ServerHello body (unencrypted)
read(5, "\24\3\3\0\1", 5) = 5 β ChangeCipherSpec (compatibility only)
read(5, "\27\3\3\0\27", 5) = 5 β from here on, everything is 0x17 (encrypted):
read(5, "\27\3\3\3D", 5) = 5 EncryptedExtensions, Certificate (836 bytes),
read(5, "\27\3\3\1\31", 5) = 5 CertificateVerify, Finished
read(5, "\27\3\3\0E", 5) = 5
write(5, "\24\3\3\0\1\1\27\3\3\0Eβ¦", 80) = 80 β client CCS + Finished
write(5, "\27\3\3\0\334β¦", 225) = 225 β the HTTP request headers, encrypted
write(5, "\27\3\3\0Aβ¦", 70) = 70 β the 48-byte JSON body, encrypted
That last line is worth a moment. Our JSON body is 48 bytes. On the wire it's 70 bytes: a 5-byte record header, 48 bytes of data, 1 byte of hidden content type, and a 16-byte authentication tag that lets B detect tampering. That's the cost of integrity.
Pro tip: To decrypt your own TLS traffic in Wireshark, run the client with SSLKEYLOGFILE=/tmp/keys.log (supported by curl, Firefox, Chrome, and Python 3.8+ via ssl's keylog_filename). Then point Wireshark at that file under Preferences β Protocols β TLS.
TLS uses both, each for what it's good at:
| Asymmetric (public key) | Symmetric (shared key) | |
|---|---|---|
| Keys | A key pair: public + private | One secret key, shared by both sides |
| Used in TLS for | Key exchange (X25519) and identity proof (RSA/ECDSA signatures) | Encrypting every byte of application data (AES-GCM, ChaCha20) |
| Speed | Slow: thousands of operations per second | Fast: gigabytes per second with AES-NI CPU instructions |
| Analogy | A padlock anyone can close but only you can open | A house key you and your friend both hold copies of |
The handshake uses slow asymmetric crypto once to agree on a symmetric key safely. Then fast symmetric crypto does all the bulk work.
| Average developer | Systems engineer | |
|---|---|---|
verify="rootCA.crt" |
"Some SSL setting." | "This file is Service A's entire trust store. Only certificates that chain to it are accepted." |
| HTTPS overhead | "HTTPS is slower." | "One extra RTT for the TLS 1.3 handshake, an X25519 and an RSA-PSS operation, then about 22 bytes and very little CPU per record." |
verify=False "to fix it" |
"Fixed!" | "That disables authentication entirely. Anyone on the path can now impersonate B. Fix the trust store or the SAN instead." |
Once TLS is set up, HTTP/1.1 is surprisingly plain: lines of ASCII text separated by \r\n, a blank line, then the body. To see exactly what requests sends, I pointed it at a tiny raw-socket server and printed the bytes it received:
POST /store HTTP/1.1\r\n
Host: 127.0.0.1:9099\r\n
User-Agent: python-requests/2.34.2\r\n
Accept-Encoding: gzip, deflate\r\n
Accept: */*\r\n
Connection: keep-alive\r\n
Content-Length: 48\r\n
Content-Type: application/json\r\n
\r\n
The body wasn't in that first recv()! requests (urllib3, underneath) sends the headers in one write() and the body in a second one. This matches the trace in the TLS section: a 225-byte record for headers, then a 70-byte record for the body. TCP is a byte stream, so the server has to keep reading until it has Content-Length bytes. It can't assume one read equals one message.
POST /store HTTP/1.1 β request line: method, path, version
Host: localhost:8443 β which site (required in HTTP/1.1)
Content-Type: application/json β how to interpret the body
Content-Length: 48 β exactly how many body bytes follow
Connection: keep-alive β please don't close the TCP connection
β empty line: headers are over
{"text": "the quick brown fox", "word_count": 4} β body: exactly 48 bytes
The most important header for correctness is Content-Length (or Transfer-Encoding: chunked). It's the framing: how the receiver knows where the body ends on a stream that has no message boundaries. Bugs here cause some of the nastiest problems in proxies, such as truncated bodies, hanging requests and request smuggling.
You don't need a library to talk to Service A. Here's the whole request built from bytes over a raw socket:
import socket
body = b'{"text":"hello world"}'
req = (b"POST /message HTTP/1.1\r\nHost: localhost:5000\r\nContent-Type: application/json\r\n"
b"Content-Length: " + str(len(body)).encode() + b"\r\nConnection: close\r\n\r\n" + body)
s = socket.create_connection(("127.0.0.1", 5000))
s.sendall(req)
resp = b""
while (chunk := s.recv(4096)):
resp += chunk
print(resp.decode())
The response:
HTTP/1.1 201 CREATED
Server: Werkzeug/3.1.9 Python/3.12.3
Date: Mon, 30 Nov 2026 19:02:01 GMT
Content-Type: application/json
Content-Length: 94
Connection: close
{"id":2,"received_at":"2026-11-30T19:02:01.003268+00:00","text":"hello world","word_count":2}
The 201 came from Service B, passed through by Service A's return jsonify(r.json()), r.status_code. The Server: header shows Werkzeug, Flask's development server. In production you'd put Gunicorn or uWSGI behind a reverse proxy.
Pro tip: curl -v prints the request and response headers. curl --trace-ascii - prints every byte. When an API "returns nothing", these show whether the server sent Content-Length: 0, closed the connection early, or never answered.
| Average developer | Systems engineer | |
|---|---|---|
request.get_json() |
"Flask gives me the JSON." | "Werkzeug read until it had Content-Length bytes, checked Content-Type, and handed me parsed text." |
Connection: keep-alive |
Unnoticed | "The client offered to reuse the TCP+TLS connection. Our requests.post() threw that away by not using a Session." |
| A 400 Bad Request | "Client sent bad data." | "Bad JSON, a wrong Content-Type, or a framing bug (Content-Length not matching the body)? curl --trace-ascii will show which." |
A Python dict is a graph of objects in memory, full of pointers that mean nothing to any other process. Before it can leave the process, it must be serialized: turned into a flat sequence of bytes that the other side can rebuild. JSON is one such format. Protobuf, MessagePack and Avro are others.
Serialization happens in two steps that people often blur:
dict (Python objects) ββjson.dumps()βββΆ str (Unicode text) ββ.encode("utf-8")βββΆ bytes
{"text": "cafΓ© π"} '{"text": "cafΓ© π"}' 7b 22 74 65 β¦
import json
p = {"text": "cafΓ© π", "word_count": 2}
s = json.dumps(p) # default: ensure_ascii=True
print(s)
# {"text": "cafΓ© π", "word_count": 2} β 51 bytes
s2 = json.dumps(p, ensure_ascii=False)
print(s2.encode("utf-8").hex(" "))
# 7b 22 74 65 78 74 22 3a 20 22 63 61 66 c3 a9 20 f0 9f 9a 80 22 2c β¦ β 39 bytes
Look closely at the second hex dump:
| Text | Bytes | Why |
|---|---|---|
{"text" |
7b 22 74 65 78 74 22 |
ASCII characters are one byte each in UTF-8 |
Γ© |
c3 a9 |
U+00E9 needs 2 bytes in UTF-8 |
π |
f0 9f 9a 80 |
U+1F680 needs 4 bytes in UTF-8 |
Python's json.dumps escapes non-ASCII by default (Γ©, and the emoji as a surrogate pair π), so the output is pure ASCII and survives any byte-mangling middleware. requests and Flask's jsonify both produce valid JSON either way. The receiver decodes it to the same string.
Content-Length counts bytes, not characters. "cafΓ© π" is 6 characters but 10 UTF-8 bytes. Code that computes len(string) for Content-Length breaks the moment a user types an accent.
Both sides must agree on the encoding. If Service B decoded our bytes as Latin-1, Γ© (c3 a9) would become ΓΒ©. That's mojibake: correct bytes, wrong interpretation. JSON is defined as UTF-8, which is why Content-Type: application/json is enough.
Our word count is defined by str.split(), which splits on Unicode whitespace in the decoded string. If Service A counted on raw bytes, a non-breaking space (c2 a0) would be counted differently. Decoding happens at the edge, and logic runs on text.
Serialization has a CPU cost. For a 48-byte payload it's nothing. For 10 MB JSON documents, json.loads can take longer than the network transfer. That's the point where people switch to orjson or a binary format.
| Average developer | Systems engineer | |
|---|---|---|
json=payload |
"Send the dict." | "dumps β str β UTF-8 bytes β Content-Length in bytes β TLS record β TCP segments." |
| "Weird characters in the DB" | "Database bug." | "Which hop decoded with the wrong charset? Hex-dump the bytes at each boundary." |
| Payload size | "Small." | "48 bytes of JSON, 70 on the wire after TLS, plus about 200 bytes of HTTP headers. At small sizes, headers dominate." |
Your Python process runs in user space. It can't touch the network card, the disk, or another process's memory directly. Only the kernel can. The only door between them is the system call: a controlled jump into kernel code, with arguments checked on the way in.
βββββββββββββββββ user space βββββββββββββββββ
β Python β requests β urllib3 β ssl (OpenSSL)β encrypts the HTTP bytes
β write(5, buf, 70) β
βββββββββββββββββββββββββββββββ¬βββββββββββββββ
system call boundary β (CPU switches to kernel mode)
βββββββββββββββββββββββββββββββΌβββββββββββββββ
β kernel space β
β socket layer β TCP β IP β netfilter β β
β routing β queueing discipline β driver β
βββββββββββββββββββββββββββββββ¬βββββββββββββββ
βΌ
NIC (or loopback)
Every strace line in this article is one crossing of that boundary. Service A made dozens of syscalls to handle one request. Each costs anywhere from a few hundred nanoseconds to microseconds. That's why high-performance servers batch work (sendmmsg, io_uring) and why TLS can be moved into the kernel (kTLS). In our trace, OpenSSL actually checked for kTLS (setsockopt(5, SOL_TCP, TCP_ULP, "tls")), but the records were still encrypted in user space.
write(5, buf, 70)Here's what happens to those 70 bytes of encrypted JSON on the sending side:
write(fd 5, 70 bytes)
β
βΌ
1. Socket layer copy 70 bytes from user memory into the socket's
SEND BUFFER (sk_buff). write() returns as soon as
the copy is done. Nothing has hit the network yet!
β
βΌ
2. TCP assign sequence numbers, cut into segments β€ MSS,
respect the peer's receive window (flow control) and
the congestion window (cwnd). Keep a copy on the
retransmit queue until the peer ACKs it.
β
βΌ
3. IP add the IP header, pick a route (ip route get 127.0.0.1),
run netfilter hooks (iptables/nftables: firewall, NAT,
Docker and Kubernetes rules live here)
β
βΌ
4. Neighbour resolve the next hop's MAC address (ARP/NDP)
β
βΌ
5. qdisc the interface's queue (tc qdisc show). Traffic shaping
and fairness happen here.
β
βΌ
6. Driver + NIC place the packet in the NIC's TX ring buffer. The NIC
DMAs it from memory and puts it on the wire, then
raises an interrupt when it's done.
The receive side runs in reverse: the NIC DMAs the frame into a ring buffer, raises an interrupt, the kernel's NAPI poller pulls packets in batches, IP and TCP process them, data lands in the socket's receive buffer, and a thread blocked in read() wakes up.
Loopback (lo), which our lab uses, skips steps 4 and 6. The packet is handed straight back to the receive path. That's why our TCP connect took 0.2 ms and not 20 ms.
Every arrow above has a queue, and every queue can fill up. You can see a socket's buffers with ss -m:
$ ss -tlmi '( sport = :5000 )'
LISTEN 0 128 0.0.0.0:5000 0.0.0.0:*
skmem:(r0,rb131072,t0,tb16384,f0,w0,o0,bl0,d0) cubic cwnd:10
rb131072 is the receive buffer limit (128 KB) and tb16384 the send buffer (16 KB). These are the defaults from:
$ sysctl net.ipv4.tcp_rmem net.ipv4.tcp_wmem
net.ipv4.tcp_rmem = 4096 131072 33554432 # min, default, max (autotuned)
net.ipv4.tcp_wmem = 4096 16384 4194304
The kernel autotunes these upward for fast, long-distance connections. The maths that matters: throughput β€ window size Γ· round-trip time. A 128 KB window over a 100 ms link caps you at about 10 Mbit/s, however fast the link is.
| Queue | Where | Shows up as |
|---|---|---|
| Accept queue | listening socket | Recv-Q on LISTEN, ListenOverflows |
| Socket receive buffer | per connection | Recv-Q on ESTAB: the app isn't reading fast enough |
| Socket send buffer | per connection | Send-Q on ESTAB: the peer or the network isn't keeping up |
| qdisc | per interface | tc -s qdisc drops |
| NIC ring buffer | per interface | ethtool -S eth0 rx_missed / rx_dropped |
| Average developer | Systems engineer | |
|---|---|---|
write() returned |
"Data sent." | "Data copied into a kernel buffer. It may sit there, be retransmitted, or never arrive. Only an application-level response proves delivery." |
| Firewall rules | "Ops stuff." | "Netfilter hooks in the IP layer of every packet. Docker's port publishing and kube-proxy are just rules here." |
| Slow transfers over long distances | "Bad network." | "Window Γ· RTT. Check ss -ti for cwnd, rtt and retransmits before blaming the network." |
with db: really doesService B's insert is two lines of Python. Here is what the kernel saw while it ran: every file operation from Service B's thread during one request, with timestamps.
19:01:27.925308 pread64(3, β¦, 16, 24) = 16 read DB header: has anyone changed it?
19:01:27.925808 openat(β¦, "messages.db-journal", O_RDWR|O_CREATβ¦) = 6 create the ROLLBACK JOURNAL
19:01:27.926095 pwrite64(6, β¦, 512, 0) = 512 journal header
19:01:27.926304 pwrite64(6, "\r\0\0\0β¦", 4096, 516) = 4096 ORIGINAL copy of page 2 (the table)
19:01:27.926752 pwrite64(6, "SQLite format 3\0β¦", 4096, 4620) ORIGINAL copy of page 1 (the header page)
19:01:27.927008 fdatasync(6) = 0 β flush journal to disk
19:01:27.957659 openat(β¦, "lab", O_RDONLY|O_CLOEXEC) = 7 open the DIRECTORY
19:01:27.957852 fdatasync(7) = 0 β‘ flush directory (the journal's name)
19:01:27.970488 pwrite64(6, β¦, 12, 0) = 12 mark journal as complete
19:01:27.970631 fdatasync(6) = 0 β’ flush that
19:01:27.985765 pwrite64(3, "SQLite format 3\0β¦", 4096, 0) write NEW page 1 into messages.db
19:01:27.985957 pwrite64(3, "\r\0\0\0\1β¦", 4096, 4096) write NEW page 2 (with our row)
19:01:27.986092 fdatasync(3) = 0 β£ flush database to disk
19:01:27.993288 unlink("messages.db-journal") = 0 delete journal = COMMIT POINT
This is SQLite's default rollback journal mode (PRAGMA journal_mode returns delete). The idea:
1. Copy the ORIGINAL pages into a journal file, and make it durable.
2. Overwrite the pages in the database file, and make that durable.
3. Delete the journal. That single atomic operation is the commit.
Crash before step 3? On the next open, SQLite finds the journal and
copies the original pages back: a ROLLBACK.
Crash after step 3? The new pages are safely on disk.
Inserting one small row wrote 16 KB (four 4 KB pages: two into the journal, two into the database) and called fdatasync four times. Each one is a round trip to the storage device. From the first pread64 to the unlink took 68 ms in this run (under strace, on a WSL2 virtual disk). Durability is expensive, and it dominated the request.
write() vs fsync(): the page cacheWhy does SQLite need fdatasync at all, if it already called pwrite? Because write() doesn't write to disk.
process kernel disk
pwrite64(3, page) βββΆ PAGE CACHE (RAM)
page marked "dirty"
returns immediately βββ (microseconds)
β
β later: kernel flusher threads write
β dirty pages back (~5β30 s), orβ¦
βΌ
fdatasync(3) βββΆ force all dirty pages of fd 3 βββΆ storage controller
out NOW and wait for the βββΆ flash/platter
returns βββββββββββββββ device to confirm it's durable βββ "it's stored"
(milliseconds)
The page cache is why Linux file I/O feels fast: writes go to RAM, and reads of recently used data come from RAM. But if the machine loses power before the flusher runs, those writes are gone. Databases that promise durability (the D in ACID) must call fsync/fdatasync at commit time and wait for the device to confirm. fdatasync is a slightly cheaper fsync that skips flushing metadata such as modification time.
The directory fdatasync (β‘) is a subtle one that's easy to miss: creating a file changes the directory, and that change needs its own flush, or after a crash the journal file might not exist.
with db: cost about the same four fsyncs as one insert.PRAGMA journal_mode=WAL) appends changes to a write-ahead log instead of copying pages around. Combined with PRAGMA synchronous=NORMAL, a commit needs no fsync at all; the log is synced at checkpoints. That trades the durability of the last few transactions on power loss for much higher write throughput, and lets readers and a writer work concurrently.check_same_thread=False is a shortcut. Flask's threaded server can run two requests at once on the same connection object. SQLite's own locking keeps the file consistent, but sharing one connection across threads is fragile. Use a connection per thread or a lock.| Average developer | Systems engineer | |
|---|---|---|
INSERT |
"Saved to the DB." | "4 pages written via the page cache, 4 fdatasyncs, a journal created and unlinked. Durable when unlink returns." |
| Slow writes | "SQLite is slow." | "Each commit waits on the disk four times. Batch transactions, or use WAL with synchronous=NORMAL." |
| "Data lost after a crash" | "Corruption bug." | "Did something call write() without fsync()? Is the disk lying about its write cache? Is the database on a network filesystem with weak locking?" |
Now put it all together. One curl to Service A, followed through every layer. The timings come from the strace run (which slows every syscall down), so the absolute numbers are inflated but the proportions are honest.
t (ms) WHERE LAYER WHAT HAPPENS
ββββββ βββββββββββ βββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββββ
0.0 curl DNS "localhost" resolved from /etc/hosts (no network)
curl TCP SYN β SYN-ACK β ACK, completed by A's KERNEL,
connection parked in the accept queue of fd 3
0.0 A main thr. socket accept4(3) = 4 (client port 50046)
A process a new thread (6628) takes over this request
2.2 A thread HTTP recvfrom(4) = 167 bytes "POST /message HTTP/1.1β¦"
bytesβJSON Werkzeug parses headers, Flask decodes UTF-8 JSON
app len(text.split()) = 4 β YOUR CODE: ~Β΅s
7.0 A thread socket/TCP socket() = 5, connect(127.0.0.1:8443) EINPROGRESS
kernel handshakes with B's kernel; B: accept4(4) = 5
12.1 A thread file read rootCA.crt (the trust store)
14.6 A thread TLS write ClientHello (517 B)
16.4 A β B TLS ServerHello, Certificate, CertificateVerify, Finished
A verifies chain β Demo Root CA, SAN = localhost β
18.2 A thread TLS client Finished; session keys agreed (X25519)
19.0 A thread HTTP+TLS write 225 B (headers) + 70 B (48 B JSON body)
22.9 B thread SQLite pread header, create journal, 3 Γ pwrite
24.6 B thread disk fdatasync(journal) β
55.4 B thread disk fdatasync(directory) β ~68 ms of
68.2 B thread disk fdatasync(journal) β waiting on
83.6 B thread disk 2 Γ pwrite + fdatasync(messages.db) β the disk
90.9 B thread filesystem unlink(journal) β COMMIT β
92.6 B thread HTTP+TLS write 193 B (headers) + 124 B (102 B JSON body)
95.0 A thread HTTP sendto(4) response headers + body to curl
96.0 A thread TCP shutdown(4); connection β FIN β TIME-WAIT
A β B connection closed too: no keep-alive (no Session)
The time picture without strace, measured with curl -w straight at Service B:
$ curl -s -o /dev/null --cacert rootCA.crt -X POST https://localhost:8443/store \
-H 'Content-Type: application/json' -d '{"text":"a b c","word_count":3}' \
-w 'dns=%{time_namelookup} tcp=%{time_connect} tls=%{time_appconnect} ttfb=%{time_starttransfer}\n'
dns=0.000016 tcp=0.000224 tls=0.003521 ttfb=0.038511
DNS 0.02 ms β
TCP 0.2 ms β
TLS 3.3 ms ββ
server 35 ms ββββββββββββββββββββββββββββββββββ β almost all fsync
The word count, the "business logic", takes microseconds. The request is dominated by a TLS handshake that a Session would remove, and by disk flushes that batching or WAL would shrink. You can't see either from the Flask code. You can only see them by looking one layer down.
Pro tip: curl -w is the fastest latency triage tool you have. The gaps tell you the layer: time_connect high means network/TCP, time_appconnect - time_connect high means TLS (or a slow CA lookup), and time_starttransfer - time_appconnect high means the server itself.
Senior engineers don't debug faster because they guess better. They debug faster because they name the layer first, then pick the tool that sees that layer. Each error message below is a clue about which layer failed.
$ curl localhost:5001
curl: (7) Failed to connect to localhost port 5001 after 0 ms: Couldn't connect to server
>>> socket.create_connection(("127.0.0.1", 5001))
ConnectionRefusedError(111, 'Connection refused')
Layer: TCP / ports. Meaning: the packet reached the host, and the kernel answered the SYN with a RST because no socket is listening on that port. Note "after 0 ms": refusals are instant.
Systems thinking: this is good news. The network path works, and the host is up. Check, in order: is the process running (ps)? Is it listening on that port and address (ss -tlnp)? Did it bind to 127.0.0.1 when the client comes from another container or host? In Kubernetes: does the Service's targetPort match the container's port?
Contrast with a timeout: if connect() hangs for seconds, the SYN got no answer at all. Something dropped it silently: a firewall, a security group, a wrong IP, or a host that's down. Refused and timeout are different layers, and the difference saves you hours.
Service A talking to B without our Root CA, as with the default verify=True:
SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed:
unable to get local issuer certificate (_ssl.c:1000)'))
And with the right CA but the wrong address:
SSLError(SSLCertVerificationError(1, "[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed:
IP address mismatch, certificate is not valid for '127.0.0.2'. (_ssl.c:1000)"))
Layer: TLS. TCP worked, because you can't fail a certificate check without a connection. Read the tail of the message, which names the exact check that failed:
| Message tail | Cause | Fix |
|---|---|---|
unable to get local issuer certificate |
The client's trust store doesn't contain the issuing CA, or the server didn't send its intermediate | Configure the right CA bundle (verify=, REQUESTS_CA_BUNDLE, SSL_CERT_FILE), or make the server send the full chain |
certificate has expired |
notAfter has passed (or the client clock is wrong) |
Renew, and automate renewal. Check date on the client |
Hostname mismatch / IP address mismatch |
The name you dialled isn't in the SAN list | Connect by the right name, or reissue with the right SANs |
The universal debugging command shows the chain exactly as the server presents it:
$ openssl s_client -connect localhost:8443 -servername localhost </dev/null
depth=0 CN = service-b
verify error:num=20:unable to get local issuer certificate
verify error:num=21:unable to verify the first certificate
Verification error: unable to verify the first certificate
Add -CAfile rootCA.crt and it becomes Verification: OK. Never "fix" this with verify=False.
ConnectionError β¦ Failed to resolve 'service-b.invalid' ([Errno -2] Name or service not known)
Layer: DNS, before any TCP. No packet was ever sent to Service B. Errno -2 is EAI_NONAME, from getaddrinfo().
Systems thinking: test resolution the way the application does it. getent hosts NAME uses the same libc path as Python: /etc/nsswitch.conf, then /etc/hosts, then the resolvers in /etc/resolv.conf. dig talks to DNS directly and skips /etc/hosts, so the two can disagree.
getent hosts service-b # what the app will get
dig +short service-b # what DNS says
cat /etc/resolv.conf # which resolver, which search domains
In Kubernetes, look at ndots:5 in the pod's resolv.conf: a name like api.example.com is first tried with every search domain appended, turning one lookup into several. Slow DNS shows up as a large time_namelookup in curl -w.
Loss rarely produces an error. It produces slowness, because TCP quietly retransmits. The first retransmission timeout is at least 200 ms, and lost SYNs wait a full second or more.
nstat -az TcpRetransSegs # system-wide retransmit counter (watch it grow)
ss -ti dst 10.0.0.12 # per-connection: rtt, cwnd, retrans:X/Y
sudo tcpdump -i eth0 -nn host 10.0.0.12 # duplicate seq numbers = retransmissions
mtr -rwc 100 10.0.0.12 # loss and latency per hop
In Wireshark, the filter tcp.analysis.retransmission highlights every resend. Systems thinking: latency that clusters around 200 ms, 1 s or 3 s is the fingerprint of retransmission timers, not of slow code.
Decompose before you optimise. Our own system showed the method in section 12:
curl -w separates DNS, TCP, TLS and server time.top/htop shows CPU. State D in ps means it's waiting on disk. py-spy dump --pid PID shows the Python stack right now.strace -f -T -p PID shows the time spent in each syscall. In our case, fdatasync took 30 ms by itself.Recv-Q on the listener (not accepting fast enough) or on connections (not reading fast enough).Don't forget the "one layer below" for latency: a new TCP+TLS connection per request (no keep-alive) adds 2 round trips each time. Between regions that alone can be 150 ms.
OSError(24, 'Too many open files')
Layer: process resources. The process hit RLIMIT_NOFILE. Usually the limit isn't too low. Something is leaking: responses that are never closed, sockets that never get released, or files opened in a loop.
ls /proc/PID/fd | wc -l # how many now? Run it again in a minute
grep 'open files' /proc/PID/limits # the limit
ls -l /proc/PID/fd | awk '{print $NF}' | sed 's/:.*//' | sort | uniq -c | sort -rn
# β counts by type: "socket", "/var/log/app.log", "pipe" β¦ the leak is the big number
ss -tanp | grep "pid=PID" | awk '{print $1}' | sort | uniq -c # sockets by TCP state
A pile of CLOSE-WAIT sockets means your code got a FIN from the peer and never called close(). That's a leak in your application, not the network. A pile of ESTAB connections to one backend means a pool without a maximum size.
Symptom Layer First tool
ββββββββββββββββββββββββββββββββββ ββββββββββββ ββββββββββββββββββββββββββββββ
Failed to resolve / Name not known DNS getent hosts, dig, resolv.conf
Connection refused (instant) ports/TCP ss -tlnp on the server
Connection timed out (seconds) network/IP firewall, routes, tcpdump for SYNs
CERTIFICATE_VERIFY_FAILED TLS openssl s_client -showcerts
400 / 411 / hanging body HTTP framing curl -v / --trace-ascii
Mojibake, bad JSON bytes hex dump at each hop
Slow, no errors TCP/disk/CPU curl -w, ss -ti, strace -T, py-spy
Too many open files process /proc/PID/fd, ss state counts
Process "running" but frozen process ps STAT (D?), py-spy dump, strace -p
You don't learn these layers by reading about them. You learn them by running something and looking at it with the right tool, as we did in this article. For each topic below: what to understand, and the hands-on exercise that makes it stick.
| Topic | Understand | Do this |
|---|---|---|
| Linux | Processes, threads, signals, fds, /proc, users and permissions, systemd |
Run strace -f on a program you use daily. Read /proc/PID/status, fd/, limits, maps |
| Networking | IP addressing, subnets, routing, ARP, NAT, MTU | Draw your laptop's route to a website with ip route, ip neigh, traceroute |
| TCP/IP | Handshake, states, windows, congestion control, retransmission, TIME-WAIT | Capture a download with tcpdump. Find the handshake, window updates and FIN in Wireshark |
| TLS | Certificates, chains, SANs, the TLS 1.3 handshake, mTLS | Build your own Root CA (as above), then make B require client certificates too (mTLS) |
| DNS | Recursive vs authoritative, record types, TTLs, caching, search domains | dig +trace yourdomain.com. Break /etc/hosts on purpose and watch apps fail |
| Filesystems | Page cache, fsync, journaling, inodes, directory entries |
strace a SQLite insert in WAL vs rollback mode. Count the fsyncs |
| Containers | Namespaces, cgroups, overlay filesystems, veth pairs, bridges | Run a container, then find its process on the host with ps and enter its namespace with nsenter |
| Kubernetes | Pods, Services, kube-proxy, CoreDNS, CNI, probes | Trace one request from Ingress to Pod: which iptables/eBPF rules and which DNS lookups does it hit? |
| Observability | Logs, metrics, traces, the USE and RED methods | Add OpenTelemetry tracing to A and B and find the TLS and fsync time in a trace waterfall |
Pro tip: Build the lab from this article yourself. It is two small Python files and four OpenSSL commands. Then break it in every way listed in section 13, one at a time, and read the error at each layer. An afternoon of deliberate breakage teaches more than a month of reading.
"The application works" is where the systems engineer's curiosity starts, not where it ends.
When our Flask service returned {"word_count": 4}, a process was sleeping in accept(). The kernel completed a TCP handshake on its behalf. A thread read 167 bytes and parsed them as HTTP. Service A opened a second TCP connection, negotiated TLS 1.3 with an X25519 key exchange, and checked a certificate chain back to a Root CA it was told to trust. It wrapped 48 bytes of UTF-8 JSON in a 70-byte encrypted record. Service B, on the other side, copied two pages into a journal, waited on the disk four times, and deleted a file to make the commit durable. Everything after the word count is "infrastructure", and that's where the time, the failures and the scaling limits actually live.
You don't need to master every layer at once. You need the habit. Each time you write or debug something, ask:
What PROCESS is running this? ps, /proc/PID/status
What SOCKET is it using? ss -tanp, /proc/PID/fd
What PACKETS are on the wire? tcpdump, Wireshark
What PROTOCOL is being spoken? curl -v, openssl s_client
What KERNEL OPERATION is it waiting on? strace -f -T
What FILE does it end up in? strace -e trace=file,fsync, ls -l /proc/PID/fd
Ask those questions often enough and they stop being questions. You start seeing the layers automatically, the way the second engineer at the start of this article did. That's the difference between someone who can build an application and someone who can be trusted with a system.