TLS 1.3 Session Tickets: Rotation Handshake Herds and Stale Pools

Dark neon cover: a server box issuing two session tickets that fade after a rotation, a crowd of client arrows arriving in one burst against a queue, and a gauge labelled resumed share

TL;DR

  • A TLS 1.3 session ticket arrives after the handshake. 10 clients that copied SSLSocket.session the moment wrap_socket returned held a session with no ticket, and resumed 0 of 10 times.
  • Resumption on this stack cuts the handshake from 1.5 ms to 1.2 ms and the pair’s CPU from 2.34 to 2.02 ms, while total bytes barely move: the ticket the client presents costs 281 bytes upstream and the absent certificate saves 513 downstream. Most of the bytes in a full handshake here are not the protocol: they are the 1,216-byte post-quantum key share OpenSSL offers by default.
  • After a rotation 48 clients perform full handshakes: 1.6 ms each one at a time, 29.7 ms when all arrive together, and 27.8 ms with four in flight – the bound serialises the server’s work, it does not shorten the client’s wait.
  • A closed connection fails after the write: 24 of 24 reuses raised BrokenPipeError on the read. A pre-write poll turns all 24 of them into served requests once the close has landed, and none while it is still travelling; a pool timer below the server’s is what covers that gap – 80 ms against 100 absorbs a 20 ms round trip, 60 ms absorbs 40 ms.
  • The first response on a new connection returns 41.9 ms after the request unless the server socket sets TCP_NODELAY (0.16 ms); Nagle holds it behind the server’s own unacknowledged write. One host, one Python process, loopback: read the ratios, not the digits.

1. The host, the stack, and three baselines

TLS session resumption is usually described as a latency feature: the second handshake is cheaper than the first. The interesting part for a production pool is not the second handshake but the moment every client loses its ticket at once, and what a client does with a connection it believes is still open. Both questions were measured here, on loopback, with the standard library: a scripted server, a client built directly on ssl.SSLContext, a TCP relay that counts and timestamps every byte in both directions, and the kernel’s own view of the socket from TCP_INFO.

ItemMeasured valueHow it was read
Kernel6.12.8+ on x86_64platform.release()
CPUIntel(R) Xeon(R) Platinum 8488C, 2 vCPUs/proc/cpuinfo
Python3.12.16, CPythonplatform.python_version()
TLS libraryOpenSSL 3.5.7 9 Jun 2026ssl.OPENSSL_VERSION
Key-exchange groups offered11 extensions, lead group X25519MLKEM768ServerHello parsed from the relay’s copy
ssl names for ticket keysnum_tickets onlydir(ssl.SSLContext) filtered for ticket
Certificate librarycryptography 50.0.2used to mint the two certificates
perf_counter step192 nssmallest non-zero delta in a 200,000-call spin
TCP connect0.06 ms median, 0.08 ms p95400 connects
Request round trip0.07 ms median, 0.10 ms p95500 requests on one connection
Socket pair echo, one thread1.2 µs100-byte echo sent and received on the calling thread
Socket pair echo, two threads30.1 µs median, 50.6 p95the same echo, the other end served by a second thread
Segment size (MSS)41,024 bytes to send on the client, 44,736 on the accepted socket; 1,859 and 1,478 to receiveTCP_INFO at both ends of one connection
EC P-256 certificate599 PEM bytes, 399 DERCertificateBuilder
RSA-2048 certificate1,131 PEM bytes, 795 DERsame subject
Table 1: The host. A full TLS 1.3 handshake here is 1.5 ms, which is a small multiple of the request round trip on an established connection – so on loopback the protocol cost is clearly visible, and a queue of handshakes is visible as a multiple of it.

Three baselines anchor every later number. A TCP connect costs 0.06 ms; a request on an already-negotiated connection costs 0.07 ms; an in-process echo on a socket pair costs 1.2 µs with both ends on the calling thread – a kernel copy and two syscalls – and 30.1 µs when the other end is a thread that has to be woken, which is the floor under any measurement whose two ends are threads, as every probe on this page is. The segment size is a property of one socket, not of the host: one connection reported 41,024 bytes to send on the client and 44,736 on the accepted socket, and a plain socket changed its own value after a single 70,000-byte write. Section 6 quotes the MSS of the socket it measured.

The certificate is the other number most byte comparisons get wrong. It is a single 399-byte leaf with no chain. A browser-facing deployment usually sends two or three certificates, several kilobytes, and then the certificate rather than the protocol decides what a handshake weighs. Every byte figure below is the protocol’s own share on a self-signed leaf.

Out of scope: One host, loopback, one Python process with two vCPUs. Absolute milliseconds belong to this machine; the ratios are what transfers, and each table says which of the two it is reporting. A client and a server in the same process share a GIL and a CPU budget, so every CPU figure on this page is the cost of both ends together, not the server’s share alone.

2. What a handshake costs, and what resumption does not save

Six configurations carry the ladder: TLS 1.3 and TLS 1.2, each with an EC P-256 and an RSA-2048 certificate, and the two TLS 1.3 runs again with the group pinned to X25519 – 200 handshakes per arm. The arms are interleaved round by round with the order swapped, after 40 discarded rounds, because otherwise the arm that runs second inherits a warmer machine and the bias lands exactly on the difference being compared. A full handshake uses a context that has never held a session – a context handed one keeps resuming from it – and every figure is a median with a p95 beside it, not a maximum.

ConfigurationFull p50Full p95Resumed p50Full CPUResumed CPUFull bytesResumed bytes
EC P-256 · 1.3 · X25519MLKEM7681.5 ms1.9 ms1.2 ms2.34 ms2.02 ms3,3863,154
EC P-256 · 1.3 · x255191.3 ms1.7 ms0.97 ms2.14 ms1.77 ms1,091823
RSA-2048 · 1.3 · X25519MLKEM7681.7 ms2.1 ms1.2 ms2.64 ms2.00 ms3,9773,153
RSA-2048 · 1.3 · x255191.6 ms2 ms0.93 ms2.43 ms1.72 ms1,672838
EC P-256 · 1.21.3 ms1.7 ms0.59 ms1.89 ms1.39 ms1,131661
RSA-2048 · 1.21.6 ms2.1 ms0.61 ms2.25 ms1.41 ms1,712671
Table 2: 200 handshakes per latency figure, one arm of each kind per round with the order alternating; CPU is the per-round time.process_time delta, both ends in one process, 200 rounds per arm after 40 discarded warmup rounds; bytes are a complete handshake read from a counting proxy before the client writes a single request byte, 16 samples each. The group printed in each configuration is the one the ServerHello chose, not the one the client hoped for.

Note: The wire column is the surprise. On TLS 1.3 resumption the client sends 281 bytes more than in a full handshake because it presents a ticket, and the server sends 513 bytes less because it presents no certificate; the two nearly cancel, leaving 6.9% off the total. TLS 1.2 behaves as advertised, because its resumed handshake carries neither a certificate nor a ticket of that size. Resumption is a CPU and round-trip trade on this stack, not a bandwidth trade – and a pool that resumes to save bytes has chosen the wrong reason.

The post-quantum key share in the middle of the comparison

The first row and the second row are the same certificate, the same version and the same code; the only difference is the group the client was allowed to offer. A default OpenSSL 3.5 client offers X25519MLKEM768 first and sends a 1,216-byte key share for it, which makes its ClientHello 1,473 bytes against 239 when set_ecdh_curve("X25519") narrows the offer and the server agrees on x25519. Over the whole handshake that is 2,295 bytes, and it is not free in time either: 0.21 ms on a full handshake and 0.23 ms on a resumed one. The two arms pay the same toll, which is what a share the client builds on every handshake should look like: resumption skips the certificate, not the key exchange. It also explains why the saving from resumption is a nearly fixed number of milliseconds on this host – the signature it removes – even though the handshake around it got more expensive. Any article that quotes “TLS 1.3 costs N bytes” without naming the group it is quoting is quoting one stack’s default; the control above is how to tell the protocol’s share from the library’s.

Start with the gap the table shows between the first row and the TLS 1.2 row: 1.5 ms for a default TLS 1.3 client against 1.3 ms. The byte column offers an explanation, and it is the wrong one: a default TLS 1.3 handshake carries 3,386 bytes against TLS 1.2’s 1,131, which reads like the price of the newer protocol. Pin the group and the explanation falls: TLS 1.3 then sends 1,091 bytes, 40 fewer than TLS 1.2, and its clock barely moves: 1.28 ms against 1.27. The bytes that made TLS 1.3 look expensive were the hybrid share; what is left is a CPU difference the other way, 2.14 ms against 1.89, spent on this stack’s TLS 1.3 path – the key schedule and the encrypted handshake. A ranking built on either column alone is wrong twice: once for the group it did not name and once for the end it charged.

The certificate comparison needed the same treatment. Compared at the same group, the RSA certificate costs 0.29 ms of CPU per full handshake over the EC one, and nothing measurable after resumption: 1.72 ms against 1.77, a gap the round-to-round spread swallows. That is the point of the next measurement. One RSA-2048 PSS signature takes 0.36 ms to produce and 33 µs to verify, while an ECDSA P-256 signature takes 30 µs to produce and 0.08 ms to verify: verification is actually cheaper for RSA, so the handshake gap is not the client checking anything – it is the server’s private-key signature, 0.33 ms of it, which accounts for the 0.29 ms gap – the signature loop and the handshake are not the same instrument, so the two numbers need not agree to the last digit, only in size. Capacity planning follows from that: an RSA certificate is a per-full-handshake cost on the server’s CPU, and resumption removes it because a resumed handshake carries no certificate to sign for.

What a ticket does not remove: A resumed handshake here still carries a key exchange: its server flight is 1,345 bytes, and the 513 bytes it lacks against the full handshake’s 1,858 are the certificate and the signature over the handshake. What resumption saves is that signature – 13% of the pair’s CPU here – and the ticket the client sends still carries a 1,216-byte hybrid share of its own.

3. The ticket that arrives after the handshake

In TLS 1.2 the session is part of the handshake: the server sends a session id or a ticket, and the client can use it the moment the handshake returns. In TLS 1.3 the ticket is sent after the handshake, as application data, and a client that does not read from the socket never processes it. The difference is easy to measure: copy the session the instant wrap_socket returns, ask the stack whether it can resume, and then wait.

What the client doesSession can resumeResumed on the next connect
handshakes, then closes without reading (a health check)0 of 200 of 20
handshakes, waits 100 ms, reads nothing, closes10 of 10 ticketless0 of 10
handshakes and reads the response, then stores the sessionyesyes
repeats that on the new session, five timesyes5 of 6 handshakes resumed
Table 3: The same server, the same client context, four client behaviours. The session object exists in every case – SSLSession is not None – but it carries no ticket until the client reads the post-handshake message.

Note: The session at handshake completion reports has_ticket False, an empty id (0 bytes) and a lifetime hint of 0; after the response is read the same fields report has_ticket True, an id of 32 bytes, and the hint then reads 7,200 seconds. Polling the socket for the ticket during a handshake that has already finished finds it after 1.2 ms – the delay is not the network but the client not having called recv.

That single ordering rule explains the most common reason a TLS pool never resumes: it stores the session where the handshake completes, which is the natural place to put it, and stores an object that cannot resume. A pool that stores it after the first response resumes every time. A client that opens connections to check a server is healthy – connect, close, repeat – never collects a session at all, and a pool that copies that pattern inherits the behaviour.

"""Where a resumable session is kept, and what disqualifies one.

A TLS 1.3 ticket arrives after the handshake, so ``SSLSocket.session`` is a usable
session only once ``has_ticket`` says so; a TLS 1.2 session is usable as soon as it has an
id. ``SessionStore`` enforces that with one rule - :func:`resumable` - so a pool cannot
store the object a client copies too early.

The store is bounded and evicts least-recently-used entries. It is not persisted: an
``SSLSession`` cannot be serialised, and a process that restarted has a new ticket key on
the server side anyway.
"""
from __future__ import annotations
import ssl
def resumable(session: ssl.SSLSession | None) -> bool:
    """True when the stack would actually resume with this session.

    ``has_ticket`` is False for a TLS 1.3 session copied at handshake completion, and an
    empty ``id`` is what a TLS 1.2 session without a ticket or session id looks like.
    """
    if session is None:
        return False
    return bool(session.has_ticket or len(session.id))

The store refuses a session it cannot use instead of accepting it and failing later. The refusal is counted, so a pool that has been storing ticketless sessions shows a rejected counter that keeps climbing while its resumed share stays at zero.

num_ticketsRecords after the handshakeBytes after the handshakeSession resumes
04 (handshake flight)6160
158671
2 (the default)61,1171
481,6171
Table 4: One server at four ticket counts, with a handler that sends no application data so every record after the ServerHello is either the encrypted handshake flight or a ticket. The extra record costs about 250 bytes each; at zero the client never gets a session at all. The count also turns out to matter for section 6: each ticket is one more small write the server has not had acknowledged when it answers the request.

When there is nothing to resume: Tickets can be disabled and resumption still works in TLS 1.2 through the session-id cache, but not in TLS 1.3: with num_tickets = 0 the client holds nothing to present and every connection is a full handshake. A pool cannot compensate for a server that sends no tickets.

4. Whose key makes a ticket valid

A ticket is encrypted with a key held by the SSLContext that issued it. Build a second context – a restarted process, a new worker, a reloaded configuration – and every ticket from the first context is unreadable, whatever the certificate says. The two variables are easy to confuse, so the probe changes them one at a time.

Server the client meetsCertificateResumedAfter one new handshake
the same contextsame20 of 20–
a second contextsame (5449ac5f712e6178)0 of 2020 of 20
a second contextdifferent (026965c64d6c520a)0 of 2020 of 20
a second context, TLS 1.2same0 of 10–
Table 5: Twenty resume attempts per row against a second listener, with the dead ticket offered every time so a refusal cannot be mistaken for a recovery. The fingerprint in the certificate column is the first eight bytes of the DER certificate’s SHA-256, measured before and after the switch.

Note: Same certificate and different certificate behave identically: 0 resumptions out of 20 in both cases. The certificate is not what makes a ticket valid – the ticket key is – so a restarted process under an unchanged certificate refuses every old ticket exactly as a changed one does. TLS 1.2 reaches the same outcome by the same mechanism rather than a different one: on OpenSSL’s default settings a TLS 1.2 server issues tickets as well, and the session this probe primed for that row carries one (has_ticket True, a 32-byte id), so the second context refuses it for the reason a 1.3 one does – a ticket key it does not hold. The “the session cache lives on the server” explanation describes only the session-id case: with tickets turned off, TLS 1.2 resumes from a cache inside the server, a new context starts with an empty cache, and the client has nothing the new context can honour. Both routes end in a full handshake; which name the server gave the session is what decides the mechanism.

What a real rotation does instead

A new SSLContext is the crudest form of rotation: every ticket it issued dies at the same instant, and this table is the measurement of that – the second context resumed 0 of the 20 old tickets it was offered, twice, with the certificate byte-identical. Servers that take ticket rotation seriously do not cut over; they overlap. OpenSSL exposes a ticket-key callback that receives the key name in the client’s ticket and may return an old key for decryption while new tickets are sealed with the current one; nginx takes a list of ssl_session_ticket_key files, uses the first to encrypt and any of the others to decrypt; Go’s SetSessionTicketKeys takes a slice with the same meaning, and rotating means moving the old key to the back of the slice before dropping it. The shape is always the same: issue with the new key, accept both for at least one ticket lifetime, then retire the old one.

Python’s ssl gives a program none of that. The module that issued the tickets in this article exposes exactly one name containing ticket – num_tickets, the count – and nothing that names, sets or lists a ticket key: the probe reads dir(ssl.SSLContext) for the table above rather than trusting the docs. So a Python server that builds a new context for a certificate reload, a worker restart or a redeploy performs a hard cutoff, and the honest engineering move is to plan the cutover instead of wishing it were an overlap: bound and jitter the reconnects (section 5), and put the overlap in the proxy that terminates TLS, where the API exists.

The ticket lifetime is the one knob people reach for at this point, and it belongs to the other kind of rotation. In an overlap, a shorter lifetime than the interval between rotations is exactly right: it bounds how long an old key has to stay loaded to decrypt what it issued, so the decrypt window is one ticket lifetime wide. Against a hard cutoff it buys nothing. The cutoff invalidates every ticket the old context ever issued at the instant the context is replaced – this table measures that with a byte-identical certificate – so a ticket with two hours left and a ticket with two seconds left die together. A Python server could not set the lifetime anyway: it is not in the module’s surface, and the value the session object reports is OpenSSL’s default, 7,200 seconds, which this probe read rather than chose. What a cutoff needs is not a shorter ticket but a client that can absorb one full handshake per connection without turning it into a lost request.

Two consequences follow. First, recovery is cheap and fast: one full handshake per client stores a new ticket, and every later connection resumes – 20 of 20 in the table. The damage is the moment of the rotation, not the minutes after it. Second, presenting a dead ticket does not cost the fallback handshake its round trip: measured in the same round, alternating which arm runs first, the handshake that offered a refused ticket was slower than the plain one by 0.15 ms at the median, slower in 159 of 200 paired rounds, with the middle of the distribution between -0.10 ms and 0.39 ms. That is a real but small cost – the server has to look up the key and reject the binder before it starts over – and it is reported with its spread because a difference this size needs the paired design to be believed at all.

The second context in this table is also what a second worker process is. Unless the operator hands every worker the same ticket key – the overlap above, at the layer that supports it – a client resumes only with the worker that issued its ticket, so a pool spread across workers sees its resumed share fall as the worker count rises. The table measures the rotation; it cannot measure the load balancer in front of it.

The stack also binds a session to the context that created it: presenting a valid ticket through a different client SSLContext fails before the network is touched, 5 of 5 times, with the error Session refers to a different SSLContext. A pool that builds a client context per connection therefore has a cache it can never fill.

The client helper is the whole of the client side – one socket, one wrap_socket that is handed the session, and a timer around it – and it is printed once, in the appendix, with the rest of the harness rather than here. A ticket key that changed is invisible to it: the client learns about the rotation only when the server refuses the ticket, which is the next section.

5. Forty-eight reconnects after one rotation

A rotation is not one event per client. Every client that holds a ticket loses it at the same instant, and every one of them reconnects on its next request. For a pool of forty-eight connections that is forty-eight full handshakes, and the arrival pattern decides how the queue is distributed: what the server pays per handshake, and what each client waits before its first byte. Those are two different numbers here, and every case is run three times so that a single run cannot decide the table.

Arrival shapeHandshake p50Handshake p95Client p50Client p95Peak in flightWall time
one at a time1.6 ms1.9 ms1.6 ms1.9 ms181.7 ms
all at once29.7 ms45.5 ms29.7 ms45.5 ms753.5 ms
jittered over 100 ms1.8 ms3.1 ms1.8 ms3.1 ms4106.7 ms
jittered over 400 ms1.7 ms2.3 ms1.7 ms2.3 ms3405.7 ms
at most 2 in flight2 ms2.8 ms29.2 ms51.6 ms258.6 ms
at most 4 in flight3.5 ms5.3 ms27.8 ms47.5 ms454.5 ms
at most 8 in flight6.8 ms11.7 ms29.7 ms48.9 ms655.2 ms
at most 16 in flight15.7 ms19.1 ms30.2 ms47 ms855.9 ms
Table 6: 48 clients, one request each, every ticket dead, each shape run 3 times and the median run reported. Handshake is the median client’s own connect to first byte; client is the same client timed from the moment it was free to connect, so it includes any wait at the limiter. Peak in flight is the server’s own counter.

Note: Read the two latency columns against each other, because the limiter is where a table like this usually lies. Bounding the queue at four does what it says at the handshake: 3.5 ms against 29.7 ms for the unbounded burst, 8.6 times better, with the server’s own counter never above 4 handshakes in flight against 7 for the burst. Those two – the handshake’s cost and the server’s peak – are the numbers this probe measured. It does not make the client’s request faster. The client that waits for a slot spends the difference queued: its total is 27.8 ms against 29.7 ms unbounded, most of the handshake’s gain gone, and the queue accounts for 8.0 times the handshake it is waiting for. Two in flight is no better: 29.2 ms per client. So a limiter does not reduce waiting; it moves the waiting from the handshake into the client’s queue.

What that queue protects is the part this experiment can only infer. The peak counter says the process runs four handshakes at once instead of seven, and the CPU figure in section 2 says what each one costs, so a bound of four caps the CPU a rotation can take from the process. Whether that keeps another workload in the same process responsive is a different measurement: here the client and the server are one process on two cores, no second request stream runs beside the burst, and this probe never timed a bystander. The honest claim is a bounded peak and a queue that lands on the clients, not a measured protection of unrelated traffic.

What shortens the client’s wait is spreading the arrivals: jitter over 400 ms gives 1.7 ms per client, 16.9 times better than the burst, and jitter over 100 ms gives 1.8 ms with the whole burst finished in 106.7 ms. The bound of sixteen shows what the extra slots buy: the server runs 4.5 times the handshake it ran at four, while the client total moves 1.1 times. Past the point where the bound protects the server, the additional slots are paid for by the server and not collected by the clients.

Arrival shape, no rotationWall timep50p95Resumed
one at a time63.4 ms1.3 ms1.6 ms48
all at once50.1 ms28.6 ms42 ms48
jittered over 400 ms405.5 ms1.5 ms2.1 ms48
at most 4 in flight51.6 ms3.2 ms4.8 ms48
Table 7: The same four shapes against the server that issued the tickets. Every handshake resumes, and the queue still costs: 28.6 ms for the burst against 1.3 ms one at a time. A resumption is cheaper than a full handshake, not free, and forty-eight of anything at once is a queue.

The control also settles what a limit is for. Resumption alone would not remove the burst, because a resumed handshake still performs a key exchange and still occupies the process; only the shape of the arrivals decides how much of the machine is busy at once. That is why the limiter in the package bounds handshakes rather than retries: the retry policy decides what happens to a failed request, the limiter decides how many requests fail at the same instant – and, as the table shows, the cost of that protection is paid by the clients in the queue, so it belongs in front of a server that would otherwise saturate, not in front of a client that wants a fast answer.

"""The delay between a rotation and a client's reconnect.

A rotation invalidates every ticket at the same instant, so without a delay every client
reconnects at the same instant and each one waits behind the others (probe 04, Table 6).
The functions here draw the delay; they do not sleep, so a caller can schedule the wait
wherever its runtime schedules waits.

Every function takes the random draw as an argument instead of calling ``random``, which
is what makes the distribution testable rather than merely plausible.
"""
from __future__ import annotations
import random
def spread_delays(count: int, spread_s: float = 0.4, seed: int = 21) -> list[float]:
    """One uniform delay per client across a fixed window, from a seeded generator.

    A fixed window, not an exponential one: the reconnect is not backing off from a
    failing server, it is avoiding a simultaneous arrival at a server that is healthy.
    """
    if count < 0:
        raise ValueError("count must be non-negative")
    if spread_s < 0:
        raise ValueError("spread_s must be non-negative")
    generator = random.Random(seed)
    return [generator.uniform(0.0, spread_s) for _ in range(count)]

The delay is drawn, not slept, so a caller can schedule the wait wherever its runtime schedules waits – a thread, an event loop, a timer wheel. A fixed window rather than an exponential backoff is deliberate: the reconnect is not backing off from a failing server, it is avoiding a simultaneous arrival at a server that is healthy, so the window stays as wide as the spread the operator chose. This is the lever the table says actually shortens a client’s wait; the limiter that does the bounding is a counting semaphore with a close state, printed in the appendix.

The same module carries the two curves that belong to a server that is failing rather than to a crowd: a jittered one whose ceiling doubles with each attempt, so a client that keeps failing waits longer each time, and a decorrelated one that draws the next delay between the base and three times the previous one, which lets a lucky fast client stay fast and a slow one drift further out. Neither is on this page in full – the appendix prints the module – because the measurement above is about the window, and one curve is enough to show where the window lives.

6. The first byte after a handshake, and the 40 ms that hides there

A measurement of a burst that stops at the first response byte is measuring the application as well as the handshake, and on this host the application adds a fixed cost that dwarfs the handshake: about forty milliseconds before the first byte of a small response arrives, unless one socket option is set. It appeared while measuring section 5 and had to be isolated, because it is the same forty milliseconds on every new connection a rotation creates. The isolation is the interesting part: the option tells you which algorithm, the kernel’s counters tell you which socket, and one control below shows how a fast reading can be an artefact of the server closing the connection.

CaseFirst byte p50First byte p95StalledUnacked at the writeResponse bytes
full handshake41.9 ms42.2 ms30 of 3031 of 3187
full handshake, TCP_NODELAY on the server0.16 ms0.29 ms0 of 3020 of 3187
full handshake, option on the client only41.8 ms42.1 ms30 of 3031 of 3187
full handshake, one ticket0.15 ms0.33 ms0 of 300 of 3187
full handshake, no tickets41.9 ms42.4 ms30 of 300 of 3187
resumed handshake0.14 ms0.20 ms0 of 301 of 3187
resumed handshake, TCP_NODELAY on the server0.13 ms0.26 ms0 of 301 of 3187
2 KB response, connection kept open41.7 ms42 ms30 of 3031 of 312,085
2 KB response, connection closed after the write0.21 ms0.26 ms0 of 3031 of 312,085
response that fills a segment0.19 ms0.28 ms0 of 3031 of 3165,085
two requests on one connection41.6 ms41.9 ms30 of 3031 of 6187
4 KB request, small response41.7 ms42.1 ms30 of 3031 of 3187
Table 8: 30 connections per case, each with a full or resumed handshake and one request. “Stalled” counts first bytes later than 20 ms, because the stall is bimodal – a connection waits or it does not. “Unacked at the write” is the kernel’s count of unacknowledged segments on the accepted socket, read from TCP_INFO immediately before the server writes its response.

Note: The pattern identifies the mechanism, and the relay identifies the socket. Nagle’s algorithm holds a small write while something the same socket wrote earlier is still unacknowledged, and on this host the server still has an unacknowledged segment when its handler answers: the kernel reports one at 31 of 31 writes, and the relay stamps the client’s request at 2.3 ms and the response at 43.1 ms – the server held it 40.9 ms. Set TCP_NODELAY on the accepted socket and the stall goes (0.16 ms against 41.9 ms); set it on the client socket instead and it stays (41.8 ms), because the option belongs to the socket doing the writing. A single ticket escapes it – the counter reads nothing outstanding and the response leaves at once, 0.15 ms – and so does a resumed handshake, which stalled in 0 of 30 connections: a resumed flight is small and is acknowledged before the handler answers. With no tickets at all the delay does not disappear, it changes socket: OpenSSL on the client writes its Finished and then the request, and the relay sees the request only at 43.8 ms (41.6 ms after the client’s own sendall returned).

Two more rows say what does not matter. Size is not the trigger: a 2 KB response waits as long as a 64-byte one. What can make a probe report otherwise is where the connection ends: a handler that returns straight after sendall lets the thread close the socket, and close() flushes what Nagle is holding. The same response on a connection that stays open waits 41.7 ms, and on one closed after the write it arrives in 0.21 ms: 198 times faster, because the close pushed it. A response whose first segment is full leaves at once (0.19 ms): 65,085 bytes against the 44,736-byte MSS that socket reported, so the segment is complete and Nagle has nothing to hold. A second request on the same connection is answered in 0.26 ms, because by then nothing is outstanding. The forty-millisecond timer itself is the kernel’s delayed-ACK maximum, which this probe did not instrument; what is measured is the stall, the socket that held the bytes, and the conditions that remove it.

Why this matters more than the handshake: The stall changes the arithmetic of section 2. On a server without TCP_NODELAY a new connection costs 41.9 ms before the first byte and a resumed one costs 0.14 ms, so the saving resumption delivers at the first byte is 145 times the saving the handshake alone made – two effects of the same resumption, not two independent wins, and the rotation in section 5 creates exactly the connections that pay the first one.

The fix is one setsockopt on each accepted socket, or a runtime that sets it for every socket it accepts, and the measurement is worth keeping because the symptom is misleading: a p50 that sits at forty milliseconds with a fast handshake looks like an application problem, and the two conditions that remove it – TCP_NODELAY or a resumed handshake – point at the socket layer rather than at the code that queries the database. The control that closes the connection is the one to remember when reading someone else’s benchmark: a fast first byte on a connection that is about to be closed may be the close doing the work.

7. Reusing a connection the server has already closed

A pool keeps a connection alive between requests. The server closes it at an idle timeout that the client may not know, and the next request meets a socket that looks open and is not. What the client observes depends on how far past the boundary the reuse lands, and the probe records the two stages of the request separately, because almost everything written about this names the wrong one.

Idle before reuseServedEmpty readRead errorKernel stateCaught by the poll
20 ms24 of 240024 established0 of 24
60 ms24 of 240024 established0 of 24
95 ms24 of 240024 established0 of 24
100 ms (the timeout)016821 established9 of 24
105 ms002424 close-wait24 of 24
160 ms002424 close-wait24 of 24
Table 9: 24 pooled connections per row, each used once, then reused after the stated idle time against a server whose idle timeout is 100 ms. A 0 is a measured outcome, not a missing cell. The write stage failed 0 times at every row – the column does not exist because the measurement does not have one. The last column is a second pass over the same reuse, through the pool with its pre-write poll on: connections it discarded before a byte was written.

Note: Below the timeout every reuse is served. At the boundary the outcome stops being predictable: of 24 connections, 16 came back as an empty read and 8 with an error on the read, so the request and the server’s close are racing and the row is the race. Five milliseconds past the timeout the outcome is settled: the kernel has already recorded the peer’s close, the socket is in close-wait when the pool reaches for it (24 of 24 at 105 ms), the request is written without complaint, and the read raises BrokenPipeError 24 times out of 24. Across the whole probe – the sweep plus the retry and the two comparative runs – not one write failed: the write-stage count is 0 in every row. The failure a pool actually meets arrives after the bytes have left.

What the client seesWhere it happensWas the request executed?What a pool may do
poll reports the peer closed before the writebefore the bytes leaveno – nothing was sentdiscard it, open a new connection, and count it
BrokenPipeError from sendallbefore the bytes leavenodiscard and retry at once, on a new connection
write returns, read raises BrokenPipeErrorafter the write, when the peer’s kernel answers with a resetunknownreport it unless the request is repeatable
write returns, read returns nothingthe peer’s FIN arrived before the request didunknown to the clientthe same, and a retry needs a new connection
read raises SSLEOFErrorthe same as the line above, with suppress_ragged_eofs=Falseunknownthe same
Table 10: Five outcomes and the only question that matters. The second line is the one most retry advice is written for, and it is the one this host did not produce once: the kernel accepts a write on a half-closed socket and reports the fault on the next read, so “retry when the write fails” is a policy for a failure that rarely arrives. The first line needs no write at all, and it is the one a pool can produce on purpose (below). With Python’s default suppress_ragged_eofs=True the last two lines are indistinguishable: the truncated stream is reported as an empty read.

The mechanism is the one a plain close() produces. The server’s handler times out and the thread returns, the socket is closed with SO_LINGER off (measured: l_onoff 0) and no close_notify, so the peer sends a FIN and the client’s kernel moves the connection to close-wait without telling the application. A write on a close-wait socket is legal – the direction towards the peer is still open – so the kernel accepts it and sends it; the server has no socket any more, so its kernel answers with a reset, and the client’s next call returns EPIPE. That is why the second write and the read fail and the first does not: the first request may even have been delivered. When the request instead arrives while the server’s socket still exists, the data sits unread and the close turns into a reset immediately, which is the empty-read half of the boundary row. Both are races against the same timer, and the environment decides which one a given connection meets.

The distinction can be recovered. With suppress_ragged_eofs=False the same reuse at the boundary raises SSLEOFError 13 times out of 20, and BrokenPipeError on the read 7 times. A server that shuts down cleanly with unwrap() sends a close_notify instead, and then all 8 reads come back empty without an error: a pool that turns suppression off can tell “the peer said goodbye” from “the peer vanished”, which is the difference between an orderly removal and a fault.

Whatever the diagnosis, the repair ends in a new connection, and there are two ways to get there. The expensive way is to write and find out: 24 of 24 pooled connections were dead after the idle timeout – all of them at the read stage – and all 24 retried requests succeeded, at a median of 1.7 ms including the new handshake. The cost of the retry is one handshake, and for a request that may have executed the cost of the retry is a duplicate, which is why the pool below asks the caller whether the request was repeatable instead of guessing. A session ticket is what makes that retry cheap in CPU: the new connection resumes instead of paying for another certificate.

The repair before the write: ask whether the socket is still alive

The cheap way asks the kernel a question before anything is sent: has the peer closed while this connection sat idle? That is the check urllib3 ships as is_connection_dropped, and the function below is the same idea written for ssl.SSLSocket. Two details are worth naming here because they are what the code cannot say by itself: SSLSocket.recv refuses flags, so the peek urllib3 uses is not available and the answer has to come from poll; and readable alone is not enough, because a socket with a session ticket the client has not read yet is readable too – the flag that means a half-close is POLLRDHUP, and discarding on plain readability would throw away a live connection.

The function is small enough to state without printing it twice, and the appendix prints it in full with the rest of pool.py: connection_is_dropped(connection) -> bool answers False at once when select has no poll; otherwise it registers the descriptor for POLLIN beside POLLHUP, POLLERR, POLLNVAL and POLLRDHUP, polls with a zero timeout, and answers True only when an event comes back carrying one of the closed bits. The rest of the function is the comment above that mask: which platform has which name, and why an older interpreter degrades to writing and finding out.

That judgment is Linux-only, and on Linux it needs CPython 3.6 or newer: select.POLLRDHUP is absent from the 3.5 documentation and present in the 3.6 one, so on an older interpreter getattr(select, "POLLRDHUP", 0) is 0, the mask loses the half-close bit and the function answers False instead of calling a readable socket closed. Windows has no select.poll at all and macOS has no POLLRDHUP. On all of them the pool falls back to writing and finding out – slower, and never wrong in the direction of discarding a live connection. Everything measured here was measured on Linux with both names present.

The measurement is the same reuse as the table above, run through the pool twice, once with the check and once without. Without it, every reuse at or past the timeout came back as AmbiguousRequest: 24 of 24 at 105 ms, because the write succeeded and the read failed. With it, 24 of 24 were discarded before a byte was written, and every request was served on a new connection: 24 served, 0 ambiguous, no retry spent. The poll costs 0.82 µs at the median on a live connection (2,000 calls, p95 0.86 µs), so the price of asking is a rounding error against the 1.5 ms handshake it avoids.

At the timeout itself the poll is only as good as the race. In the 100 ms row it caught 9 of 24 – the closes that had already arrived – and the other 15 were written to and ended ambiguous, as they do with the check off. Five milliseconds later the kernel had always recorded the close and the poll missed none of them. That boundary is where the check earns its place, and it is also where its ceiling shows: a close the client has not received yet is a close no poll can report.

That is not a detail of loopback. A server’s close is not visible when the server makes it; it is visible when the FIN arrives, one one-way latency later. Here the whole request round trip is 0.07 ms, so the gap between the poll and the truth is a syscall. Between two hosts it is the latency: a few milliseconds across a data centre, tens across a country, hundreds across an ocean – and the poll answers about the past for all of it. The harness can reproduce that, because a relay is allowed to hold the FIN back: FinDelayRelay forwards every byte as it arrives and delays only the server’s close, which is exactly what distance does to it.

Every row below is past the server’s idle timeout, so the server has closed in all of them, and the poll is taken 30 ms after that timer would have expired. A hold shorter than the margin has landed by the time the poll asks and a longer one has not, so five holds bracket the boundary instead of two points asserting it.

FIN heldCaught at the pollAmbiguous after the writeSocket at the pollRetired by an 80 ms timerAmbiguous with the timer
0 ms12 of 12012 close-wait12 of 120
5 ms12 of 12012 close-wait12 of 120
20 ms12 of 12012 close-wait12 of 120
50 ms0 of 121212 established12 of 120
100 ms01212 established12 of 120
Table 11: 12 reuses per row, each past a 100 ms server idle timeout and inside a hold of the stated length on the FIN. The first four columns are the bare socket; the last two are the same reuses through the pool with its own idle timeout set to 80 ms. “Ambiguous” means the write was accepted and the read then failed or returned nothing, so the client cannot say whether the request ran.

The middle columns are the sweep’s answer: at 20 ms the poll caught every connection, and at 50 ms it caught none – the socket was still established at the poll, every write was accepted, and all 12 requests ended ambiguous. The width of the window is the one-way latency the close needs to arrive, and no client-side test narrows it, because at the moment of the poll the connection genuinely is open.

The repair that does not depend on the FIN is a timer the client owns. TLSConnectionPool gained one: idle_timeout_s stamps every connection with clock when it is parked, and a connection that has sat idle for that long is closed when it is next taken – before the liveness test is ever consulted, because a connection the pool closed itself cannot be one the server removed first. Set it below the server’s idle timeout and leave the difference wide enough for a whole round trip – both directions, because the client parks one one-way latency after the server sent the answer and the next request needs another to arrive – plus the server’s own timer granularity, and the failure class disappears instead of being filtered after the fact. At 80 ms against a 100 ms server, that is the last two columns of the table: 12 of 12 connections retired at the take and 0 ambiguous requests at every hold in the sweep, including the 100 ms one that the poll alone could not see at all.

from __future__ import annotations
from .session import SessionKey
def _take(self, key: SessionKey) -> tuple:
    """The newest idle connection for ``key``, and how many were retired to reach it.

    A connection past ``idle_timeout_s`` is closed here rather than handed out: the
    caller asked for one that has not sat too long, and a connection the pool closed
    itself cannot be one the server removed first. The retired ones are counted, so a
    pool whose server timeout is shorter than its own shows a rising ``retired_idle``
    and an ``ambiguous`` count that keeps up with it.
    """
    retired = 0
    while True:
        with self._lock:
            bucket = self._idle.get(key)
            if not bucket:
                return None, retired
            connection, parked = bucket.pop()
            self.stats.idle_now -= 1
        if (self.idle_timeout_s is not None
                and self.clock() - parked >= self.idle_timeout_s):
            self._close_socket(connection)
            with self.stats.lock:
                self.stats.closed_idle += 1
                self.stats.retired_idle += 1
            retired += 1
            continue
        return connection, retired

That method is the whole of it: pop under the lock, compare the park time with the clock, close and count when the timer has expired, and return only a connection the pool still owns. What it costs is one handshake for each connection retired early – the handshake a discard would have needed anyway – and what it spends is the connection that would have been reused in the gap between the two timers, which is why the margin is a setting rather than a constant: a datacentre can afford a few milliseconds, an ocean needs hundreds.

That the margin is a round trip and not a one-way delay is measured, not argued. The relay above holds only the close; the one below delays every byte it forwards, in both directions, and the close with them – a FIN that left 100 ms into the server’s clock cannot arrive before the round trip that carries it. Each row parks a connection and reuses it 79 ms later – just inside the client’s 80 ms timer, so that timer never fires and the server’s 100 ms clock decides alone. The sweep runs twice, once for each margin, and is printed as two tables: under the 80 ms timer the reuse comes 79 ms after the park, under the 60 ms timer 59 ms after it, still a millisecond inside that one, so both arms leave the server’s clock to decide and the only thing that differs between them is the margin. Each arm measured the round trip its own relay inserted, in its own run, and each table prints the figure that arm took – the same 15 ms leg came back 30.5 ms in one run and 30.6 ms in the other – so a row’s clock closes to a tenth of a millisecond only against the trip it was measured with.

One-way delayRound trip insertedServer’s clock, 80 ms timerServed, 80 ms timerAmbiguous, 80 ms timer
0 ms0.1 ms79.1 ms12 of 120 of 12
5 ms10.4 ms89.4 ms12 of 120 of 12
10 ms20.6 ms99.6 ms12 of 120 of 12
15 ms30.5 ms109.5 ms0 of 1212 of 12
25 ms50.6 ms129.6 ms0 of 1212 of 12
Table 12: 12 reuses in each row, parked and reused 79 ms after the last answer with the pool’s timer at 80 ms, through a relay that delays both directions and the close by the row’s one-way latency, against a server idle timeout of 100 ms. The round-trip column is what this arm measured on that path, and the clock column is its hold plus that figure: 79 plus 30.5 is 109.5 in the row where the margin breaks. A “Discarded at the poll” column is left out on purpose: the pre-write test condemned 0 of 12 connections in every row here, so it would be a column of zeros.

Without a delay the request reaches the server well inside its timer and is served: 79.1 ms on the server’s clock. At 5 and 10 ms one way the round trip grows to 10.4 ms and 20.6 ms, the request lands at 89.4 ms and 99.6 ms on the server’s clock, and both rows are still served – the second with almost nothing to spare. At 15 ms the same request lands at 109.5 ms, the server has closed, the FIN has not arrived, the poll finds an open socket, and 12 of 12 requests end ambiguous. That is the margin breaking, and it breaks where the round trip passes what the hold left of the server’s timer: 21 ms at this timer setting, which 20.6 fits and 30.5 does not.

The last row is not an exception, and the arithmetic of the first one says why. The server’s FIN departs 100 ms into the server’s own clock, and that clock started one one-way latency before the client parked: on the client’s clock the close leaves at 100 ms plus that latency. The poll is taken 79 ms after the park, which on the same clock is that latency plus 79 ms. Subtract the two and the latency cancels: the close is 21 ms behind the poll at every distance, so the poll condemns 0 of 12 reuses in the 25 ms row and at every other one, and the far rows are ambiguous for the reason the near ones are. A relay that forwarded a close the moment it saw it, instead of one one-way latency later, would hand the client a FIN that had overtaken the round trip, and the far rows would read as served by a poll that never ran in time – that is the instrument answering, not the path. The relay on this page therefore delays the close as well as the bytes, its unit test asserts the delay, and the table above is what is left when it does.

One-way delayRound trip insertedServer’s clock, 60 ms timerServed, 60 ms timerAmbiguous, 60 ms timer
0 ms0.1 ms59.1 ms12 of 120 of 12
5 ms10.3 ms69.3 ms12 of 120 of 12
10 ms20.4 ms79.4 ms12 of 120 of 12
15 ms30.6 ms89.6 ms12 of 120 of 12
25 ms50.5 ms109.5 ms0 of 1212 of 12
Table 13: the same reuse with the pool’s timer at 60 ms and the take 59 ms after the park. This arm took its own round trips, so its clock column closes the same way one row further out: 59 plus 30.6 is 89.6 on the path the pair above failed. Nothing here was discarded at the poll either, and the same subtraction says why: the close is 41 ms behind the poll in every row of it.

The second table is the same reuse with twice the margin. Against 100 ms the hold leaves 41 ms of the server’s timer, so the round trip has that much room instead of 21 ms: at 15 ms one way the request lands at 89.6 ms and all 12 reuses are served, where the 80 ms arm had already landed past the timeout and come back ambiguous; at 25 ms it lands at 109.5 ms and 12 of 12 are ambiguous again. The pool’s timer retired 0 connections in that arm and in the other, because the reuse is a millisecond inside it in both: what the second table measures is not the timer firing but the room the setting leaves, and doubling the margin doubles the round trip it survives. A timer number means nothing without the server’s; the margin, and whether a round trip fits in it, is the whole decision.

What the poll cannot promise: A server that closes between the poll and the write – or while the close is still travelling – leaves exactly the failure the poll was there to prevent, and no client-side test can see it: hold the FIN for 100 ms and the poll misses 12 of 12 – and the timer that retires the connection before the write misses none of them. Three things answer that, cheapest first: the idle timeout keeps the client from offering a connection the server may have retired; the poll discards the ones that were retired early; and the idempotency key makes a retry legal for the residue both miss. A pool with one of the three has traded one failure for another.

The pool returns one of two things and never a guess. A request that met a connection the poll had condemned goes out on a new one and reports itself as stale; a request whose failure the pool can place before the write is retried; a request whose fate is unknown is reported as AmbiguousRequest unless the caller declared it repeatable. The result carries how many attempts it took, whether the connection was reused and whether a stale one was discarded. The branches that separate those cases are in TLSConnectionPool.execute, printed in the appendix with the rest of the package.

8. The package, and what each file decides

The code is one small package, tlspool: 6 modules, 797 lines, and 138 tests in 7 files, the last file holding the relay the round-trip table is measured through to its contract. Each module answers one question from the sections above and imports no framework: the pool takes a connector callable, the limiter takes a number, the store takes a session.

ModuleOwnsPublic surfaceTested by
session.pywhat counts as a resumable session, and a bounded storeSessionStore, resumable25 tests
limiter.pythe bound on handshakes, and its two statesHandshakeLimiter19 tests
backoff.pythe reconnect delay after a rotationfull_jitter, decorrelated, spread_delays22 tests
pool.pyreuse, the two failure stages, the idle timer, the countersTLSConnectionPool.execute, idle_timeout_s, AmbiguousRequest45 tests
report.pythe resumed share and one health predicateresumption_report, healthy10 tests
Table 14: The package. The counts are per-file totals of the 138-test suite reported by pytest -q, and its other two files are outside this table: test_integration.py, whose 14 tests each run against a real loopback server – 9 through the suite’s server fixture and 5 that start their own, 6 in-process threaded servers in all because the rotation test runs two – and test_relay.py, which holds the relay behind the round-trip table to the property that table depends on: a close is delayed at least one one-way latency before the client can see it. Nothing in the integration file asserts against a mock of the TLS layer.

The store is four operations and one rule, and its code is printed in the appendix rather than here: put returns False for a session the stack cannot resume, so the caller learns immediately instead of after a rotating front end never hits; entries are bounded and evict in least-recently-used order; and every operation refuses to run after close() instead of silently reviving a closed object. The counters – hits, misses, rejected, evicted – are the four numbers that explain a resumed share that will not move.

The counters are deliberately separate from the snapshot. PoolStats holds counters a probe can increment under its own lock, and snapshot derives the three ratios a dashboard wants – opened, resumed share and reuse failures – so a metric is never stored in two representations that can disagree.

Two rules the probes forced: The retry after a stale connection opens a new connection instead of taking the next idle one, because during a rotation every idle connection is dead and a retry that draws another one spends its attempt on the same fault. And one stale connection drops its siblings, because a rotation, a restart and an idle timeout all end a server’s connections together – keeping the survivors only moves the cost to the next request.

9. The same workload, six clients, one rotation

The end-to-end probe runs 240 requests on 8 workers in two halves, and restarts the server on the same port between them. Every client runs the identical work; they differ in what they keep, in what they are allowed to repeat, and in whether an idle connection is tested before it is written to. Both the median and the mean are printed for the half after the restart, because with eight workers sharing eight connections the two answer different questions and quoting one against the other is how a table like this ends up saying more than it measured.

ClientServedFailuresHandshakesp50 afterMean after
one connection per request1200 (it cannot have a stale connection)1206.6 ms6.6 ms
pooled, no retry, poll on120080.65 ms1 ms
pooled, one retry, keyed, poll on120080.66 ms1 ms
pooled, one retry, keyed, poll off120080.60 ms0.97 ms
pooled, one retry, unkeyed, poll on120080.36 ms0.89 ms
pooled, one retry, unkeyed, poll off1182 AmbiguousRequest80.57 ms0.92 ms
Table 15: 240 requests, half GET and half POST, split into two halves of 8 workers; the columns describe the half that runs after the restart. Handshakes are the post-restart total counted by the new server, whose idle timeout is longer than the run. The last four rows are the same pool twice over: “keyed” means every POST carries an idempotency key, “poll on” means an idle connection is tested before it is written to. Every ratio in the text is quoted twice, once against the median and once against the mean.

Note: Three numbers carry the argument, each against its own statistic. Pooling removes 93% of the handshakes: 120 against 8 in the second half, and 8 in the first. The mean request is 6.4 times faster (6.6 ms against 1 ms) and the median one 9.9 times (6.6 ms down to 0.66 ms), which is a wide gap for the same experiment – keep reading. The whole run burns 365.9 ms of CPU as one connection per request against 51.1 ms pooled – 86% less, for the same work.

The gap between those two multiples is the reason both are printed. With 8 workers sharing 8 pooled connections, a request either lands on a warm connection or waits for the handshake that creates one, so the median sits on whichever of the two costs happens to be more common and moves between runs, while the mean carries the handshakes’ weight. Quote the mean for capacity and the median for what a typical request saw – and never one row’s median against another row’s mean, which is not a measurement of anything.

The rotation is where the clients separate, and it separates them by the poll before it separates them by the key. Every client with the poll on served all 120 of its requests: a restart closes the connections a pool is holding, which is the one kind of close the check was built for, so the first request after the restart discarded the dead socket and ran on a new connection. The only row that reports a failure is the one with neither the poll nor the key: it wrote into sockets the server had closed and could not tell whether the write had been executed, so it reported 2 ambiguous writes instead of guessing. With the poll off and the key on, the same failures arrived and the retry covered them: 4 retries, no loss.

What this run does not show is the key being decisive, and that is the honest reading. A restart is the easy rotation: the server has finished closing before the traffic resumes, so the poll sees every dead connection, and with it switched on the unkeyed pool reported 0 ambiguous requests – the same number the keyed pool reported. The race the key covers is a write that lands after the poll, on a connection closed in between, or a close still in flight; a single restart is too small to resolve it, and the row that does show it is the one with the poll off (2 reported unkeyed, none keyed). For the size of that window when the close is still travelling, section 7 held the FIN back deliberately: 12 of 12 requests met it, and none of them had a poll that could have told.

What the restart does not prove: A rotation is cheap to survive and expensive to survive badly. The damage is one full handshake per connection (8 here), and the choice is what happens to the requests that arrive while those handshakes are in flight: retried, queued behind a bound, or reported as ambiguous. A restart makes that choice visible and an in-flight close hides it, which is why the pool needs the poll, the idle timeout and the key together rather than the one the last run happened to exercise.

The report is one function, printed in the appendix: resumption_report(stats, full_ms, resumed_ms) -> dict takes the pool’s counter snapshot and the two measured handshake costs, and returns the connection count, the resumed share, the reuse failures, the ambiguous requests, the handshake time and the time resumption saved. healthy is the predicate over that dict – a resumed share above its threshold and no ambiguous request – which is the one pair a dashboard should page on.

The report takes the two handshake costs as arguments instead of assuming them, so the number it prints moves with the measurement rather than with a constant in the module. On this host a resumed handshake saves 13% of the CPU and 19% of the wall time; on a server without TCP_NODELAY the saving is far larger, which is why the cost is an argument and not a constant.

  1. Store a session only after a response has been read, and only when the stack reports a ticket or an id – a rejected session in the store is a bug to fix, not a cache miss.
  2. Set the client pool’s idle timeout below the server’s – 80 ms against 100 ms here. A connection the client retired itself is known to be closed, so the request never meets the ambiguity at all: with the FIN held 100 ms the poll alone left 12 of 12 reuses ambiguous and the timer left 0. What it costs is the handshake a discard would have needed anyway. And the margin has to be a whole round trip, not one leg: the client parks its connection one one-way latency after the server sent the answer, and the next request needs another to arrive. At 15 ms one way, the 80-against-100 ms pair in section 7 put 12 of 12 reuses straight into the ambiguous band; the same latency under a 60-against-100 ms pair was served 12 times out of 12, because 40 ms of margin clears the 30.6 ms round trip that arm measured, while 20 ms does not clear the 30.5 ms its own arm measured.
  3. Test a pooled connection before writing to it – a liveness poll, not a blind write. The write that follows a close succeeds and only the read finds out, and that failure is the ambiguous one: in the reuse probe 24 of 24 connections past the idle timeout ended as AmbiguousRequest without the test and 0 with it, at a cost of 0.82 µs per reuse. The test is Linux’s, with CPython 3.6 or newer: where select.poll or POLLRDHUP is missing it returns False and the write finds out.
  4. Attach an idempotency key to every write that can be retried, or accept that a dead pooled connection turns that write into an ambiguity your client has to report rather than retry. The poll above narrows the window to the gap between the poll and the write – one syscall on loopback, one one-way latency on a network, which is how 12 of 12 held FINs escaped it – and the idle timeout keeps the client out of that gap; neither closes it.
  5. Bound concurrent handshakes to protect the server, and jitter the reconnects to protect the clients: on two vCPUs and 48 clients the bound of 4 held the handshakes in flight to 4 from 7 without shortening the client’s wait, while jitter over 100 ms cut the client’s wait 16.9 times.

Frequently asked questions

Why does my pool never resume, even though it stores the session?

Because it stores the session too early. In TLS 1.3 the ticket arrives after the handshake as application data, so SSLSocket.session at handshake completion carries no ticket: 10 of 10 sessions copied at that moment could not resume, and 0 resumed. Store the session after the first response has been read, and check has_ticket (or a non-empty id for TLS 1.2) before keeping it. A health check that connects, closes and never reads collects nothing at all.

Does rotating the certificate invalidate every session?

Not the certificate by itself – the context that holds the ticket key. A rotation that reaches the process as a new context – a restart, a reload, a new worker – refuses every old ticket even when the certificate is byte-identical: here it refused all 20 tickets, exactly as a second context with a different certificate did, and 0 of 20 resumed in both cases. Recovery is one full handshake per client: 20 of 20 later attempts resumed.

Is a resumed handshake cheaper in bytes as well as in CPU?

Barely, on this stack. The client presents a ticket that costs 281 bytes more than a full ClientHello, and the server sends no certificate, which saves 513 bytes; the total falls by 6.9 %. What resumption really buys is CPU (13% of the pair’s cost here) and, on a server without TCP_NODELAY, the first-byte stall measured in section 6. How many bytes a full handshake weighs is mostly a question about the key-exchange group your library offers: X25519MLKEM768 adds 2,295 bytes here.

Why does the first response on a new connection take 40 ms?

Nagle’s algorithm holds a small write while an earlier write on the same socket is unacknowledged, and after a TLS 1.3 handshake there is usually such a write: the server’s session ticket. Measured: 41.9 ms without TCP_NODELAY on the accepted socket and 0.16 ms with it, while a connection the server keeps open waits 41.7 ms for a 2 KB response and a response that fills one full segment leaves in 0.19 ms. A probe that closes the socket right after writing looks fast for the wrong reason: the close flushes the held bytes.

Is BrokenPipeError on a pooled connection safe to retry?

Only when it comes from the write, which is rarer than the advice suggests: in 24 reuses across a 100 ms idle boundary and every comparative run around it, not one write failed – the kernel accepted the bytes and the failure came on the read as EPIPE. A failure after the write – an empty read or SSLEOFError – is ambiguous, and retrying that is a decision about idempotency, not about the socket. The way out is a liveness test before writing: a zero-timeout poll for POLLRDHUP reports the peer’s close, and discarding the connection then costs 0.82 µs. It is a Linux test, and on Linux it needs CPython 3.6 or newer – on an older interpreter POLLRDHUP is missing, as it is on macOS, and Windows has no select.poll at all, so on each of those the function answers False and the write finds out. Set the pool’s idle timeout below the server’s as well: that retires the connection before the write instead of asking about it, and in section 7 it left 0 ambiguous requests of 12 with the FIN held 100 ms, where the poll alone left 12. Keep the margin a whole round trip, not one leg: a reuse just under the client’s timer still needs a one-way latency to reach the server, and the client parked its connection a one-way latency after the server’s last write, so the margin has to carry two of them – at 15 ms per direction 12 of 12 reuses came back ambiguous, and on the same path 12 of 12 were served once the timer sat 40 ms below the server’s instead: plan with the margin and not with the timer. In the sweep, reuse at the server’s idle boundary produced 16 empty reads and 8 read errors out of 24 attempts; five milliseconds past it, 24 of 24 ended ambiguous without the poll and 0 with it, because the poll discarded every one before the write.

Why does my client see an empty read instead of SSLEOFError?

Because ssl defaults to suppress_ragged_eofs=True, which reports a truncated stream as an empty read. Pass suppress_ragged_eofs=False to wrap_socket and the same reuse raises SSLEOFError (13 of 20 at the boundary), while a server that sent a close_notify still returns an empty read without an error (8 of 8). That difference is the difference between a fault and an orderly close.

How many handshakes should one process be allowed to run at once?

Enough to keep the peak in flight below what the process can serve, and no more than that helps the clients. With 48 clients on two vCPUs, a bound of 4 returned each client in 27.8 ms, against 30.2 ms at a bound of 16 and 29.7 ms unbounded, while the handshake the server ran at once grew from 3.5 ms to 15.7 ms. The queue was doing the waiting either way. Measure it; do not copy this number, which belongs to two cores on loopback.

Should the reconnect after a rotation be jittered or bounded?

Both, for different reasons. Jitter is what shortens a client’s wait: over 100 ms it gave 1.8 ms per client with the burst finished in 106.7 ms, and over 400 ms it gave 1.7 ms at a wall time equal to the spread. A bound is what protects the server: it held the handshake in flight to 4 and returned every client in 27.8 ms – protection, not speed. Use the bound in front of a server that would saturate, and jitter on the clients that would arrive together.

What does the end-to-end run actually show?

That the poll, the retry and the key answer three different questions, and that a restart only asks the first. Pooling cut the handshakes from 120 to 8 and the mean request from 6.6 ms to 1 ms. With the pre-write poll on, every client served every request, because a restart closes the connections a pool holds before the traffic resumes and the poll is built for exactly that; with the poll off, the failures arrived at the read stage and the key decided what happened next – 2 unkeyed writes were reported rather than retried, and the keyed pool retried 4 and lost none. A close still in flight is the case neither the poll nor the retry can see; section 7 held one back and 12 of 12 requests met it.

How do I rotate ticket keys without logging every client out at once?

Overlap the keys where the server lets you, and plan the cutover where it does not. OpenSSL, nginx and Go all take a current key plus one or more older keys, encrypt with the current one and accept the old ones for decryption, so a client that presents an older ticket still resumes; the old key is retired after a ticket lifetime, and a lifetime shorter than the interval between rotations is what keeps that window narrow. Python’s ssl exposes no such API – its only name containing ticket is num_tickets, and there is no lifetime setting either – so a new SSLContext is a hard cutoff: every ticket still valid at that instant dies with it, whatever its remaining lifetime, and every client pays one full handshake. Bound and jitter those reconnects, and test a pooled connection before writing through it, because the cutoff either kills the connection too or leaves a client holding a ticket the server will refuse.

TechBobby Engineering writes one reproduced production failure per article, with the probes behind every number. The session store, the handshake limiter and the pool ship as the tlspool package in the appendix, with its 138-test suite; the TechBobby Stack is the tooling map these runbooks hang on.

10. Deploy order

The order matters more than any single setting, because each step makes the next one true. Ship the server first: a pool that retries against a server that sends no tickets has nothing to resume, a bound in front of a server without TCP_NODELAY only queues requests that still wait forty milliseconds for their first byte, and a rotation behind a proxy that cannot overlap its ticket keys hands every client a dead ticket at once. Then the client: store the ticket, set the pool’s idle timeout below the server’s, test a pooled connection before writing through it, bound the handshakes, jitter the reconnects, allow one retry – and last the idempotency key on every write that can be repeated.

The evidence for the order is in the tables. The ticket is what makes a resumed share possible at all (1.2 ms against 1.5 ms); the liveness test is what keeps a stale connection from turning into an ambiguous write (0 ambiguous at 105 ms with it against 24 without); the bound is what caps how many handshakes the server runs at once – the burst peaked at 7 and ran each one in 29.7 ms, against a peak of 4 and 3.5 ms at the bound of four; jitter is what keeps the clients from paying for the queue; the idle timeout is what keeps a client from offering a connection the server may already have retired; and the idempotency key is what lets the retry be automatic. Without the key the same retry policy, with the poll off, reports 2 ambiguous writes; with it, none – and for a close still in flight the poll cannot help at all, which section 7 measured as 12 of 12. A deploy that ships the retry before the key has shipped a duplicate-order bug with a nicer name.

The rotation itself has a procedure, and it is the one the ticket-key section argues for: overlap where the terminating layer supports it – new key issuing, old key still decrypting for at least one ticket lifetime – and, where it does not, treat the cutover as a planned event with the bound and the jitter already in place. Either way, watch the resumed share through the rotation: it should dip for one handshake per client and come back, and a share that stays near zero afterwards means the tickets are being issued by a context the clients never meet again.

One monitoring rule follows from the same measurements: alert on the resumed share and on reuse failures, not on handshake count. A pool that has lost its tickets shows a resumed share near zero while every request still succeeds, and nothing in a latency graph separates that from a healthy pool on a fast network – until the next rotation arrives all at once.

The numbers behind the order are reproducible in one process: every probe here runs on a loopback server that the same script starts and stops, and every figure on the page is read from a JSON record the probe wrote. Where the page explains a mechanism it did not instrument – the kernel’s delayed-ACK timer, the derivation of a ticket key, the choices OpenSSL makes inside a flight – it names the measurement that stands in for it, and the argument is built on that measurement rather than on the explanation.

Reproducing this

The appendix prints the package and the harness module every probe imports. What it does not print is the probes that drive them, so here is the inventory, and nothing on this page depends on a file that is neither printed nor listed.

  • Nine probe scripts. 00_host.py feeds Table 1, the API names and the offered groups; 01_handshake.py Table 2 and the signature costs; 02_ticket.py Tables 3 and 4; 03_context.py Table 5 and the paired dead-ticket measurement; 04_rotation.py Tables 6 and 7; 05_firstbyte.py Table 8 and the relay timeline; 06_reuse.py Tables 9, 10, 11, 12 and 13; 07_endtoend.py Table 15; 08_tests.py Table 14 and the test counts. Each writes one JSON record, and every number in the prose is read from those records at build time.
  • Two certificates minted by cryptography: EC P-256 (599 PEM bytes) and RSA-2048 (1,131 PEM bytes), both valid for two days with localhost and 127.0.0.1 in the subject alternative names.
  • The harness, common.py, printed in full: certificate minting, the TLS server with its per-connection facts, the byte-counting and timestamping relay, the two latency relays – FinDelayRelay, which holds only the server’s close, and DelayRelay, which delays every byte in both directions – the ClientHello and ServerHello parsers, the TCP_INFO reader, the client helper and the record writer.
  • Settings that are fixed rather than swept: 48 clients, 3 runs per arrival shape and seed 21 for the rotation probe; 100 ms idle timeout and 24 connections per delay in the reuse sweep, with the pool’s timer at 80 ms and the round-trip sweep’s reuse 79 ms after the park, run again with that timer at 60 ms and the reuse 59 ms after it; 240 requests on 8 workers, half GET and half POST, for the end-to-end run. The key-exchange control is one call, set_ecdh_curve("X25519"), on the client context.
  • The suite runs with PYTHONPATH=module:sandbox python3 -m pytest -q module/tlspool/tests. All 14 integration tests start a real loopback server, so a change that makes the pool pass while OpenSSL stops resuming fails the suite rather than the next incident.

Appendix: the tlspool source, and the harness it runs on

What counts as a resumable session: session.py
"""Where a resumable session is kept, and what disqualifies one.

A TLS 1.3 ticket arrives after the handshake, so ``SSLSocket.session`` is a usable
session only once ``has_ticket`` says so; a TLS 1.2 session is usable as soon as it has an
id. ``SessionStore`` enforces that with one rule - :func:`resumable` - so a pool cannot
store the object a client copies too early.

The store is bounded and evicts least-recently-used entries. It is not persisted: an
``SSLSession`` cannot be serialised, and a process that restarted has a new ticket key on
the server side anyway.
"""
from __future__ import annotations

import collections
import ssl
import threading

SessionKey = tuple[str, int]


def resumable(session: ssl.SSLSession | None) -> bool:
    """True when the stack would actually resume with this session.

    ``has_ticket`` is False for a TLS 1.3 session copied at handshake completion, and an
    empty ``id`` is what a TLS 1.2 session without a ticket or session id looks like.
    """
    if session is None:
        return False
    return bool(session.has_ticket or len(session.id))


class SessionStore:
    """A bounded, thread-safe cache of resumable sessions, one per endpoint."""

    def __init__(self, max_entries: int = 256) -> None:
        if max_entries < 1:
            raise ValueError("max_entries must be at least 1")
        self.max_entries = max_entries
        self._entries: collections.OrderedDict[SessionKey, ssl.SSLSession] = (
            collections.OrderedDict())
        self._lock = threading.Lock()
        self._closed = False
        self.hits = 0
        self.misses = 0
        self.rejected = 0
        self.evicted = 0

    def put(self, key: SessionKey, session: ssl.SSLSession | None) -> bool:
        """Store ``session`` if it can resume. Returns False when nothing was stored.

        A ticketless session is counted in ``rejected`` rather than raising: a caller that
        copies the session too early is a bug to measure, not one to crash on.
        """
        if not isinstance(key, tuple) or len(key) != 2:
            raise TypeError("a session key is (host, port)")
        if not isinstance(key[0], str) or not isinstance(key[1], int):
            raise TypeError("a session key is (host, port)")
        with self._lock:
            # Checked under the lock so a ``close()`` that lands between the check and the
            # store cannot leave an entry in a store that has already been emptied.
            if self._closed:
                raise RuntimeError("session store is closed")
            if not resumable(session):
                self.rejected += 1
                return False
            self._entries[key] = session
            self._entries.move_to_end(key)
            if len(self._entries) > self.max_entries:
                self._entries.popitem(last=False)
                self.evicted += 1
        return True

    def get(self, key: SessionKey) -> ssl.SSLSession | None:
        with self._lock:
            if self._closed:
                raise RuntimeError("session store is closed")
            session = self._entries.get(key)
            if session is None:
                self.misses += 1
                return None
            self._entries.move_to_end(key)
            self.hits += 1
            return session

    def discard(self, key: SessionKey) -> None:
        with self._lock:
            if self._closed:
                raise RuntimeError("session store is closed")
            self._entries.pop(key, None)

    def __len__(self) -> int:
        with self._lock:
            return len(self._entries)

    def stats(self) -> dict:
        with self._lock:
            return {"stored": len(self._entries), "hits": self.hits, "misses": self.misses,
                    "rejected": self.rejected, "evicted": self.evicted,
                    "closed": self._closed}

    def close(self) -> None:
        """Drop every session and refuse further use. Closing twice is an error."""
        with self._lock:
            if self._closed:
                raise RuntimeError("session store is already closed")
            self._entries.clear()
            self._closed = True

    @property
    def closed(self) -> bool:
        return self._closed
The bound on concurrent handshakes: limiter.py
"""A bound on how many handshakes may be in flight at once.

The reason is probe 04: after a ticket-key rotation every pooled client performs a full
handshake at the same moment, and the queue that forms costs far more per client than the
handshakes do (Table 6 of the article). A limiter cannot make the handshakes cheaper; it
decides who waits, and it makes the queue visible in ``stats()`` instead of hiding it in a
tail latency graph.

The object has two states - open and closed. Closing refuses new acquisitions, wakes the
waiters with a :class:`RuntimeError`, and leaves releases alone so a caller in a
``finally`` block is not punished for finishing. The waiters are woken by the same
condition variable that admits them, so a close reaches a thread that is queued without a
timeout and not only one that was going to time out anyway.
"""
from __future__ import annotations

import threading
import time


class HandshakeLimiter:
    """A counting semaphore with a state machine and counters worth alerting on."""

    def __init__(self, max_in_flight: int = 4) -> None:
        if max_in_flight < 1:
            raise ValueError("max_in_flight must be at least 1")
        self.max_in_flight = max_in_flight
        self._condition = threading.Condition()
        self._in_flight = 0
        self._queued = 0
        self._peak = 0
        self._acquired = 0
        self._released = 0
        self._timeouts = 0
        self._refused = 0
        self._closed = False

    def acquire(self, timeout: float | None = None) -> bool:
        """Take a slot. Returns True, or False on timeout; raises when closed.

        A caller that is waiting when ``close()`` runs is refused with
        :class:`RuntimeError` rather than left to wait for a slot that will not be freed.
        """
        deadline = None if timeout is None else time.monotonic() + timeout
        with self._condition:
            if self._closed:
                self._refused += 1
                raise RuntimeError("limiter is closed")
            self._queued += 1
            try:
                while self._in_flight >= self.max_in_flight:
                    if self._closed:
                        self._refused += 1
                        raise RuntimeError("limiter is closed")
                    if deadline is None:
                        self._condition.wait()
                        continue
                    remaining = deadline - time.monotonic()
                    if remaining <= 0:
                        self._timeouts += 1
                        return False
                    self._condition.wait(remaining)
                self._in_flight += 1
                self._acquired += 1
                self._peak = max(self._peak, self._in_flight)
                return True
            finally:
                self._queued -= 1

    def release(self) -> None:
        """Give a slot back. Releasing more than was acquired is an error."""
        with self._condition:
            if self._in_flight <= 0:
                raise RuntimeError("release without a matching acquire")
            self._in_flight -= 1
            self._released += 1
            self._condition.notify()

    def close(self) -> None:
        """Refuse new acquisitions and wake every waiter. A second close is an error."""
        with self._condition:
            if self._closed:
                raise RuntimeError("limiter is already closed")
            self._closed = True
            self._condition.notify_all()

    @property
    def closed(self) -> bool:
        return self._closed

    @property
    def in_flight(self) -> int:
        return self._in_flight

    def wait_idle(self, timeout: float = 5.0) -> bool:
        """Block until no handshake is in flight, or the timeout passes."""
        deadline = time.monotonic() + timeout
        with self._condition:
            while self._in_flight:
                remaining = deadline - time.monotonic()
                if remaining <= 0:
                    return False
                self._condition.wait(remaining)
            return True

    def stats(self) -> dict:
        with self._condition:
            return {"max_in_flight": self.max_in_flight, "in_flight": self._in_flight,
                    "queued": self._queued, "peak_in_flight": self._peak,
                    "acquired": self._acquired, "released": self._released,
                    "timeouts": self._timeouts, "refused": self._refused,
                    "closed": self._closed}
The reconnect delay after a rotation: backoff.py
"""The delay between a rotation and a client's reconnect.

A rotation invalidates every ticket at the same instant, so without a delay every client
reconnects at the same instant and each one waits behind the others (probe 04, Table 6).
The functions here draw the delay; they do not sleep, so a caller can schedule the wait
wherever its runtime schedules waits.

Every function takes the random draw as an argument instead of calling ``random``, which
is what makes the distribution testable rather than merely plausible.
"""
from __future__ import annotations

import random


def full_jitter(attempt: int, base_s: float = 0.05, cap_s: float = 1.0,
                draw: float = 0.5) -> float:
    """Uniform in ``[0, min(cap, base * 2**attempt)]``; ``draw`` is the uniform sample."""
    if attempt < 0:
        raise ValueError("attempt must be non-negative")
    if not 0.0 <= draw <= 1.0:
        raise ValueError("draw must be inside [0, 1]")
    ceiling = min(cap_s, base_s * (2 ** attempt))
    return draw * ceiling


def decorrelated(previous_s: float, base_s: float = 0.05, cap_s: float = 1.0,
                 draw: float = 0.5) -> float:
    """Uniform in ``[base, min(cap, previous * 3)]``; the second attempt upward."""
    if previous_s <= 0:
        raise ValueError("previous delay must be positive")
    if not 0.0 <= draw <= 1.0:
        raise ValueError("draw must be inside [0, 1]")
    low = base_s
    high = max(low, min(cap_s, previous_s * 3))
    return low + draw * (high - low)


def spread_delays(count: int, spread_s: float = 0.4, seed: int = 21) -> list[float]:
    """One uniform delay per client across a fixed window, from a seeded generator.

    A fixed window, not an exponential one: the reconnect is not backing off from a
    failing server, it is avoiding a simultaneous arrival at a server that is healthy.
    """
    if count < 0:
        raise ValueError("count must be non-negative")
    if spread_s < 0:
        raise ValueError("spread_s must be non-negative")
    generator = random.Random(seed)
    return [generator.uniform(0.0, spread_s) for _ in range(count)]
The pool, its two failure stages and its counters: pool.py
"""A TLS connection pool whose failures are named.

Five things a pool must do that a dictionary of sockets does not:

  * keep a session only once it is resumable, and offer it on the next handshake;
  * bound how many handshakes are in flight at once, because a rotation makes them all
    arrive together (probe 04);
  * retire an idle connection on its own clock, before the peer can, so a request never
    meets one the server has already closed (probe 06);
  * ask the kernel whether an idle connection is still alive before writing to it, so a
    socket the peer closed is discarded instead of being spent on a request (probe 06);
  * tell a request that never left the client from one that may have been executed -
    a pooled connection the server already closed fails at one of two stages, and only
    the second is ambiguous (probe 06);
  * retry the first stage without asking, and refuse to guess at the second unless the
    caller declared the request idempotent.

``execute`` is the whole interface. Everything else is bookkeeping a dashboard reads.
"""
from __future__ import annotations

import collections
import select
import threading
import time
from dataclasses import dataclass, field
from typing import Callable

from .limiter import HandshakeLimiter
from .session import SessionKey, SessionStore


def connection_is_dropped(connection) -> bool:
    """True when the peer has closed, so a write would go nowhere.

    This is urllib3's ``is_connection_dropped`` idea in the form a TLS socket allows.
    urllib3 tests a pooled socket with ``select`` and ``recv(1, MSG_PEEK)``: a peer that
    closed its half makes the descriptor readable, and the peek returns ``b""`` without
    consuming anything. ``ssl.SSLSocket.recv`` refuses flags, so the same question is put
    to ``poll`` instead, and the flag that answers it is ``POLLRDHUP``: a peer that sent a
    FIN leaves the descriptor readable with data "available" that is really end-of-file,
    while readable alone is data - a pending ticket, for instance.

    The judgment works on Linux, and on Linux it needs CPython 3.6 or newer: it needs both
    names together, and the second one arrived late enough to be missing:

    * Windows has no ``select.poll`` (``select.select`` only). The function returns False
      before it touches the descriptor, so the pool simply writes and finds out - the
      correct but slower path - instead of raising ``AttributeError``.
    * macOS has ``poll`` but no ``POLLRDHUP``. A peer's bare FIN is then a fact the flags
      this function may use do not name, so it answers False and lets the read decide
      rather than guessing from readability, which is also what data looks like.
    * CPython before 3.6 exposes no ``select.POLLRDHUP`` at all: the 3.5 documentation
      lists ``POLLIN``, ``POLLPRI``, ``POLLOUT``, ``POLLERR``, ``POLLHUP`` and
      ``POLLNVAL`` and the 3.6 documentation adds the half-close flag. There
      ``getattr(select, "POLLRDHUP", 0)`` is 0, the mask loses the one bit that names a
      peer's FIN, and the function answers False - the same degradation as macOS.

    On both platforms the test degrades to "cannot tell", never to "wrongly discarded":
    a live connection is never condemned on a platform without the flag. Even on Linux
    the check is advisory, not a guarantee - the peer can close between the poll and the
    write, or while the close is still travelling, and the write then succeeds until the
    read (probe 06). It exists to keep the common case - a connection idle for longer than
    the server's timeout - from turning into an ambiguous request, not to replace the
    idempotency key that makes a retry safe.
    """
    poll_class = getattr(select, "poll", None)
    if poll_class is None:
        return False
    # POLLRDHUP is the flag that means a half-close; it exists on Linux from CPython 3.6,
    # so on an older interpreter the lookup yields 0 and the mask is only the hard errors.
    peer_gone = (select.POLLHUP | select.POLLERR | select.POLLNVAL
                 | getattr(select, "POLLRDHUP", 0))
    fileno = getattr(connection, "fileno", None)
    if not callable(fileno):
        return False
    try:
        descriptor = fileno()
    except (OSError, ValueError):
        return True
    try:
        poller = poll_class()
        poller.register(descriptor, select.POLLIN | peer_gone)
        events = poller.poll(0)
    except (OSError, ValueError):
        return True
    if not events:
        return False
    return bool(events[0][1] & peer_gone)


class PoolClosed(RuntimeError):
    """The pool was closed; nothing else will be opened through it."""


class AmbiguousRequest(RuntimeError):
    """The request may have reached the server, and its answer is not known.

    Raised instead of retrying when a connection failed *after* the request was written
    and the caller did not declare the request idempotent.
    """

    def __init__(self, key: SessionKey, error: BaseException | None = None) -> None:
        super().__init__(f"request on {key[0]}:{key[1]} may have been executed: {error!r}")
        self.key = key
        self.error = error


@dataclass
class Result:
    """What one ``execute`` call did, in enough detail to be logged and asserted on."""

    answer: bytes
    reused: bool
    attempts: int
    retried: bool
    opened: bool
    elapsed_ms: float
    stale: bool = False


@dataclass
class PoolStats:
    opened_full: int = 0
    opened_resumed: int = 0
    reuse_attempts: int = 0
    reuse_ok: int = 0
    reuse_race_write: int = 0
    reuse_race_read: int = 0
    retries: int = 0
    ambiguous: int = 0
    stale_detected: int = 0
    retired_idle: int = 0
    closed_idle: int = 0
    peak_idle: int = 0
    idle_now: int = 0
    lock: threading.Lock = field(default_factory=threading.Lock, repr=False)

    def snapshot(self) -> dict:
        with self.lock:
            data = {name: getattr(self, name) for name in (
                "opened_full", "opened_resumed", "reuse_attempts", "reuse_ok",
                "reuse_race_write", "reuse_race_read", "retries", "ambiguous",
                "stale_detected", "retired_idle", "closed_idle", "peak_idle",
                "idle_now")}
        opened = data["opened_full"] + data["opened_resumed"]
        data["opened"] = opened
        data["resumed_share"] = (round(data["opened_resumed"] / opened, 3)
                                 if opened else 0.0)
        data["reuse_failures"] = data["reuse_race_write"] + data["reuse_race_read"]
        return data


class TLSConnectionPool:
    """Bounded idle connections per endpoint, one session per endpoint, bounded handshakes.

    ``connect`` is a callable ``(key, session) -> socket``: it performs the TCP connect and
    the TLS handshake and returns an object with ``sendall``, ``recv``, ``close``,
    ``session_reused`` and ``session`` - an ``ssl.SSLSocket`` qualifies. Injecting it is
    what lets the unit tests drive failures that a real server cannot produce on demand.

    ``liveness`` is the pre-write test, :func:`connection_is_dropped` by default. Pass
    ``None`` to turn it off - which is how probe 06 measures what the check is worth.

    ``idle_timeout_s`` is the pool's own idle timeout. Every connection is stamped with
    ``clock`` when it is parked, and one that has sat idle for that long is closed when it
    is next taken, before ``liveness`` is consulted: a client that retires a connection
    before the server does knows it is closed, where a peer's close is only a fact once the
    FIN has arrived. Set it below the server's idle timeout and leave the difference wide
    enough for one round trip plus the server's timer granularity - both directions, because
    the connection is parked one one-way latency after the server's last write and the next
    request needs another to reach it, so a reuse just under this timer still lands a whole
    round trip later on the server's clock (probe 06 measures the band that opens when the
    margin is shorter). ``None`` (the default) keeps the pool on ``liveness`` alone.
    """

    def __init__(self, connect: Callable, sessions: SessionStore | None = None,
                 limiter: HandshakeLimiter | None = None, max_idle: int = 8,
                 max_attempts: int = 2, clock=time.monotonic,
                 liveness: Callable | None = connection_is_dropped,
                 idle_timeout_s: float | None = None) -> None:
        if max_idle < 0:
            raise ValueError("max_idle must be non-negative")
        if max_attempts < 1:
            raise ValueError("max_attempts must be at least 1")
        if idle_timeout_s is not None and idle_timeout_s <= 0:
            raise ValueError("idle_timeout_s must be positive or None")
        self.connect = connect
        self.sessions = sessions if sessions is not None else SessionStore()
        self.limiter = limiter if limiter is not None else HandshakeLimiter(4)
        self.max_idle = max_idle
        self.max_attempts = max_attempts
        self.clock = clock
        self.liveness = liveness
        self.idle_timeout_s = idle_timeout_s
        self._idle: dict[SessionKey, collections.deque] = {}
        self._lock = threading.Lock()
        self._closed = False
        self.stats = PoolStats()

    # ------------------------------------------------------------------ internals
    def _check_open(self) -> None:
        if self._closed:
            raise PoolClosed("pool is closed")

    def _take(self, key: SessionKey) -> tuple:
        """The newest idle connection for ``key``, and how many were retired to reach it.

        A connection past ``idle_timeout_s`` is closed here rather than handed out: the
        caller asked for one that has not sat too long, and a connection the pool closed
        itself cannot be one the server removed first. The retired ones are counted, so a
        pool whose server timeout is shorter than its own shows a rising ``retired_idle``
        and an ``ambiguous`` count that keeps up with it.
        """
        retired = 0
        while True:
            with self._lock:
                bucket = self._idle.get(key)
                if not bucket:
                    return None, retired
                connection, parked = bucket.pop()
                self.stats.idle_now -= 1
            if (self.idle_timeout_s is not None
                    and self.clock() - parked >= self.idle_timeout_s):
                self._close_socket(connection)
                with self.stats.lock:
                    self.stats.closed_idle += 1
                    self.stats.retired_idle += 1
                retired += 1
                continue
            return connection, retired

    def _put(self, key: SessionKey, connection) -> None:
        spill = None
        with self._lock:
            # The closed test happens under the lock, so a request that finishes while
            # ``close()`` is running cannot park its connection in a pool that has already
            # been emptied - it is closed here instead of being leaked.
            if self._closed or self.max_idle == 0:
                # ``max_idle == 0`` is a supported configuration - one handshake per
                # request - and it must close the connection rather than index an empty
                # deque.
                spill = connection
            else:
                bucket = self._idle.setdefault(key, collections.deque())
                if len(bucket) >= self.max_idle:
                    spill = bucket.popleft()[0]
                    self.stats.idle_now -= 1
                bucket.append((connection, self.clock()))
                self.stats.idle_now += 1
                self.stats.peak_idle = max(self.stats.peak_idle, self.stats.idle_now)
        if spill is not None:
            self._close_socket(spill)
            with self.stats.lock:
                self.stats.closed_idle += 1

    @staticmethod
    def _close_socket(connection) -> None:
        try:
            connection.close()
        except OSError:
            pass

    def _open(self, key: SessionKey, session):
        """One handshake, through the limiter, with the session the store holds."""
        with self.stats.lock:
            if session is not None:
                self.stats.reuse_attempts += 1
        if not self.limiter.acquire():
            # ``acquire`` returns False only when it was given a timeout; the pool passes
            # none, so this is a guard against releasing a slot the pool never took.
            raise RuntimeError("the handshake limiter granted no slot")
        try:
            connection = self.connect(key, session)
        finally:
            self.limiter.release()
        with self.stats.lock:
            if getattr(connection, "session_reused", False):
                self.stats.opened_resumed += 1
                self.stats.reuse_ok += 1
            else:
                self.stats.opened_full += 1
        return connection

    def _drop_idle(self, key: SessionKey) -> int:
        """Close every idle connection for ``key``.

        A pooled connection that turns out to be stale says something about its siblings:
        they were opened against the same server, and a rotation, a restart or an idle
        timeout ends all of them together. Keeping them means the next request spends its
        first attempt on the same fault.
        """
        with self._lock:
            bucket = self._idle.pop(key, None)
            if not bucket:
                return 0
            dropped = [connection for connection, _ in bucket]
            self.stats.idle_now -= len(dropped)
            self.stats.closed_idle += len(dropped)
        for connection in dropped:
            self._close_socket(connection)
        return len(dropped)

    def _remember(self, key: SessionKey, connection) -> None:
        """Store the session the exchange produced, if the stack says it can resume."""
        try:
            self.sessions.put(key, connection.session)
        except (RuntimeError, AttributeError):
            # A closed store or a socket without a session is not a request failure.
            pass

    # ------------------------------------------------------------------ interface
    def execute(self, key: SessionKey, payload: bytes, idempotent: bool = False,
                read: Callable | None = None) -> Result:
        """Send ``payload`` on a pooled connection for ``key`` and return the answer.

        An idle connection is tested before it is written to: one the peer has closed is
        discarded and the request is made on a new connection, with ``stale`` set on the
        result. A failure that still arrives - the first stage if it happened before the
        request was written - is retried once, and a failure after the write is reported
        as :class:`AmbiguousRequest` unless ``idempotent`` allows the retry.
        """
        self._check_open()
        if not payload:
            raise ValueError("payload must not be empty")
        if not isinstance(key, tuple) or len(key) != 2:
            raise TypeError("key is (host, port)")
        started = self.clock()
        attempts = 0
        retried = False
        fresh_needed = False
        last_error: BaseException | None = None
        while attempts < self.max_attempts:
            attempts += 1
            # After a failure the retry opens a new connection instead of taking another
            # idle one: during a rotation every pooled connection is dead, and a retry
            # that draws the next dead one spends its attempt on the same fault.
            connection, retired = (None, 0) if fresh_needed else self._take(key)
            # A connection the pool retired on its own clock is already the stale one the
            # caller is warned about; the poll below then runs on nothing, not on it.
            stale = retired > 0
            if connection is not None and self.liveness is not None and self.liveness(connection):
                # The peer closed while the connection sat idle. A write on that socket
                # would succeed and the read would fail, which is the ambiguous case: the
                # request is therefore moved to a new connection before it is sent.
                self._close_socket(connection)
                self._drop_idle(key)
                with self.stats.lock:
                    self.stats.stale_detected += 1
                connection = None
                stale = True
            pooled = connection is not None
            if connection is None:
                session = self.sessions.get(key)
                try:
                    connection = self._open(key, session)
                except Exception as exc:  # noqa: BLE001 - the caller decides
                    last_error = exc
                    fresh_needed = True
                    if attempts < self.max_attempts:
                        retried = True
                        continue
                    raise
            # Stage one: the write. A failure here means the server never saw the request.
            try:
                connection.sendall(payload)
            except (OSError, ValueError) as exc:
                self._close_socket(connection)
                if pooled:
                    self._drop_idle(key)
                with self.stats.lock:
                    self.stats.reuse_race_write += int(pooled)
                last_error = exc
                fresh_needed = True
                if attempts < self.max_attempts:
                    retried = True
                    continue
                raise
            # Stage two: the read. A failure here is ambiguous for a write.
            try:
                answer = read(connection) if read is not None else connection.recv(65536)
            except (OSError, ValueError) as exc:
                self._close_socket(connection)
                if pooled:
                    self._drop_idle(key)
                with self.stats.lock:
                    self.stats.reuse_race_read += int(pooled)
                    self.stats.ambiguous += int(not idempotent)
                if idempotent:
                    # A repeatable request that failed at the read stage may be sent
                    # again; when the attempts are gone the error is what the network
                    # said, not an ambiguity about what the server did.
                    fresh_needed = True
                    if attempts < self.max_attempts:
                        retried = True
                        last_error = exc
                        continue
                    raise
                raise AmbiguousRequest(key, exc) from exc
            if not answer:
                self._close_socket(connection)
                if pooled:
                    self._drop_idle(key)
                with self.stats.lock:
                    self.stats.reuse_race_read += int(pooled)
                    self.stats.ambiguous += int(not idempotent)
                if idempotent:
                    fresh_needed = True
                    if attempts < self.max_attempts:
                        retried = True
                        continue
                    raise ConnectionError("peer closed the connection without an answer")
                raise AmbiguousRequest(key, None)
            self._remember(key, connection)
            self._put(key, connection)
            with self.stats.lock:
                if retried:
                    self.stats.retries += 1
            return Result(answer=answer, reused=bool(getattr(connection, "session_reused", False)),
                          attempts=attempts, retried=retried, opened=not pooled,
                          elapsed_ms=(self.clock() - started) * 1000, stale=stale)
        raise AssertionError(f"unreachable: {last_error!r}")

    def close(self) -> None:
        """Close every idle connection and refuse further work. A second close is an error."""
        with self._lock:
            if self._closed:
                raise RuntimeError("pool is already closed")
            self._closed = True
            idle = [connection for bucket in self._idle.values()
                    for connection, _ in bucket]
            self._idle.clear()
            self.stats.idle_now = 0
        for connection in idle:
            self._close_socket(connection)
        if not self.limiter.closed:
            self.limiter.close()

    @property
    def closed(self) -> bool:
        return self._closed

    def snapshot(self) -> dict:
        data = self.stats.snapshot()
        data["limiter"] = self.limiter.stats()
        data["sessions"] = self.sessions.stats()
        data["closed"] = self._closed
        return data
The resumed share and the health predicate: report.py
"""Resumption accounting: turn the pool's counters into the ratio worth alerting on.

A pool that opens a connection per request can report a 100 % handshake rate and look
busy; a pool with a rotation problem reports a resumed share that never recovers. One
number - the resumed share of handshakes, with the reuse failures beside it - separates
the two, and a second number says what the handshakes cost in time.
"""
from __future__ import annotations


def resumption_report(stats: dict, full_ms: float = 0.0, resumed_ms: float = 0.0) -> dict:
    """Summarise ``PoolStats.snapshot()`` plus the two measured handshake costs.

    ``full_ms`` and ``resumed_ms`` are supplied by whoever measured them - probe 01 here -
    so the report never invents a cost it did not observe.
    """
    opened = stats.get("opened", 0)
    resumed = stats.get("opened_resumed", 0)
    full = stats.get("opened_full", 0)
    return {
        "connections": opened,
        "full_handshakes": full,
        "resumed_handshakes": resumed,
        "resumed_share": round(resumed / opened, 3) if opened else 0.0,
        "reuse_failures": stats.get("reuse_failures", 0),
        "ambiguous_requests": stats.get("ambiguous", 0),
        "handshake_time_ms": round(full * full_ms + resumed * resumed_ms, 3),
        "time_saved_ms": round(resumed * max(0.0, full_ms - resumed_ms), 3),
    }


def healthy(report: dict, minimum_share: float = 0.8) -> bool:
    """A single predicate for a dashboard: resumption holds and nothing was ambiguous."""
    return (report.get("resumed_share", 0.0) >= minimum_share
            and report.get("ambiguous_requests", 0) == 0)
The package’s exported names: __init__.py
"""tlspool: a small TLS connection pool that keeps sessions, bounds handshakes, and names
its failures.

The three pieces are independent on purpose:

``SessionStore``
    holds a session only after the stack says it can resume;
``HandshakeLimiter``
    bounds concurrent handshakes, so a ticket-key rotation does not become a burst;
``TLSConnectionPool``
    reuses an idle connection, retries a request that never left the client, and refuses
    to guess about one that may have reached the server.

Measured numbers behind the defaults are in the article: the reconnect herd after a
rotation (probe 04), and the two ways a pooled connection the server already closed can
fail (probe 06) - only the failure after the write is ambiguous, and it is reported rather
than retried unless the caller declared the request repeatable.
"""
from __future__ import annotations

from .backoff import decorrelated, full_jitter, spread_delays
from .limiter import HandshakeLimiter
from .pool import AmbiguousRequest, PoolClosed, PoolStats, Result, TLSConnectionPool
from .report import healthy, resumption_report
from .session import SessionStore, resumable

__all__ = [
    "AmbiguousRequest",
    "HandshakeLimiter",
    "PoolClosed",
    "PoolStats",
    "Result",
    "SessionStore",
    "TLSConnectionPool",
    "decorrelated",
    "full_jitter",
    "healthy",
    "resumable",
    "resumption_report",
    "spread_delays",
]
The harness every probe imports: common.py
"""Harness shared by every probe: certificates, a counting TLS server, a client, and records.

Nothing here decides what a probe measures. Three pieces are load-bearing:

``TLSServer``
    One ``SSLContext``, one accept loop, one thread per connection. It records what the
    handshake itself reports - ``session_reused``, the negotiated version, the cipher - so
    every resumption claim in the article is read from the stack that ran, not inferred
    from timing.

``CountingProxy``
    A loopback TCP relay that counts bytes in both directions and can be snapshotted
    between phases. A client that handshakes through the proxy and reads the counter
    before writing anything gets the handshake's exact wire size, certificate included.
    It can also keep a copy of what it forwarded, which is how ``client_hello`` and
    ``server_hello_group`` read the groups a handshake actually offered and negotiated.

``tcp_info``
    The kernel's own account of a live connection - state, MSS, unacknowledged bytes -
    read from ``TCP_INFO``. The Nagle and reuse probes need it because the socket's
    behaviour and the application's error are two different facts.

``FinDelayRelay`` / ``DelayRelay``
    Two TCP relays that turn latency into a setting. ``FinDelayRelay`` forwards every byte
    as it arrives and holds only the server's close, so a probe can ask what a poll sees
    while the FIN is still travelling; ``DelayRelay`` delays every byte in both directions,
    so a probe can ask what a round trip does to the margin between the client's idle timer
    and the server's.

``make_cert``
    Two independent key pairs, EC P-256 and RSA-2048, with ``127.0.0.1``/``localhost`` in
    the subject alternative names and a two-day life. A rotation is a second call.
"""
from __future__ import annotations

import datetime
import json
import pathlib
import random
import socket
import ssl
import struct
import threading
import time

from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec, rsa
from cryptography.x509.oid import NameOID

HERE = pathlib.Path(__file__).resolve().parent
ROOT = HERE.parent
CERTS = ROOT / "certs"
RESULTS = ROOT / "results"


# --------------------------------------------------------------------------- records
def write_record(name: str, payload: dict) -> pathlib.Path:
    """One probe, one JSON file; keys sorted so a diff between runs is readable."""
    RESULTS.mkdir(exist_ok=True)
    path = RESULTS / f"{name}.json"
    path.write_text(json.dumps(payload, indent=1, sort_keys=True) + "\n", encoding="utf-8")
    print(f"wrote {path} ({path.stat().st_size} bytes)")
    return path


def percentiles(values: list[float], digits: int = 3) -> dict:
    """The five numbers the tables print, from one list, never from a running guess."""
    if not values:
        return {"n": 0}
    ordered = sorted(values)
    def pick(fraction: float) -> float:
        index = min(len(ordered) - 1, max(0, round(fraction * (len(ordered) - 1))))
        return round(ordered[index], digits)
    return {
        "n": len(ordered),
        "min": round(ordered[0], digits),
        "p50": pick(0.50),
        "p90": pick(0.90),
        "p95": pick(0.95),
        "p99": pick(0.99),
        "max": round(ordered[-1], digits),
        "mean": round(sum(ordered) / len(ordered), digits),
    }


# --------------------------------------------------------------------------- certs
def make_cert(name: str, key_type: str = "ec", days: int = 2) -> dict:
    """Write ``certs/<name>.pem`` and ``.key``; return the facts the article quotes."""
    CERTS.mkdir(exist_ok=True)
    if key_type == "ec":
        key = ec.generate_private_key(ec.SECP256R1())
    elif key_type == "rsa":
        key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
    else:
        raise ValueError(key_type)
    subject = x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, "localhost"),
        x509.NameAttribute(NameOID.ORGANIZATION_NAME, "TechBobby Test"),
    ])
    now = datetime.datetime.now(datetime.timezone.utc)
    certificate = (
        x509.CertificateBuilder()
        .subject_name(subject)
        .issuer_name(subject)
        .public_key(key.public_key())
        .serial_number(x509.random_serial_number())
        .not_valid_before(now - datetime.timedelta(minutes=5))
        .not_valid_after(now + datetime.timedelta(days=days))
        .add_extension(x509.SubjectAlternativeName([
            x509.DNSName("localhost"),
            x509.IPAddress(__import__("ipaddress").IPv4Address("127.0.0.1")),
        ]), critical=False)
        .add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True)
        .sign(key, hashes.SHA256())
    )
    cert_path = CERTS / f"{name}.pem"
    key_path = CERTS / f"{name}.key"
    cert_path.write_bytes(certificate.public_bytes(serialization.Encoding.PEM))
    key_path.write_bytes(key.private_bytes(
        serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8,
        serialization.NoEncryption()))
    key_size = 256 if key_type == "ec" else 2048
    return {
        "name": name,
        "key_type": key_type,
        "key_size": key_size,
        "serial": certificate.serial_number,
        "not_valid_days": days,
        "cert_bytes": len(cert_path.read_bytes()),
        "key_bytes": len(key_path.read_bytes()),
        "cert_path": str(cert_path),
        "key_path": str(key_path),
        "sha256": certificate.fingerprint(hashes.SHA256()).hex(),
    }


def cert_pair(name: str) -> tuple[str, str]:
    return str(CERTS / f"{name}.pem"), str(CERTS / f"{name}.key")


# --------------------------------------------------------------------------- wire parsing
GROUP_NAMES = {23: "secp256r1", 24: "secp384r1", 25: "secp521r1", 29: "x25519",
               30: "x448", 256: "ffdhe2048", 257: "ffdhe3072",
               0x11EC: "X25519MLKEM768", 0x11EB: "SecP256r1MLKEM768",
               0x6399: "X25519Kyber768Draft00"}


def handshake_messages(data: bytes) -> list[tuple[int, bytes]]:
    """The handshake messages in a captured stream, TLS records unwrapped.

    A handshake message may be split across records, so the record payloads are joined
    before the messages are cut out of them.
    """
    stream = bytearray()
    index = 0
    while index + 5 <= len(data):
        length = int.from_bytes(data[index + 3:index + 5], "big")
        if data[index] == 22:
            stream += data[index + 5:index + 5 + length]
        index += 5 + length
    messages: list[tuple[int, bytes]] = []
    cursor = 0
    while cursor + 4 <= len(stream):
        kind = stream[cursor]
        size = int.from_bytes(stream[cursor + 1:cursor + 4], "big")
        messages.append((kind, bytes(stream[cursor + 4:cursor + 4 + size])))
        cursor += 4 + size
    return messages


def extensions_from(body: bytes, start: int) -> dict[int, bytes]:
    """The extension block of a ClientHello or ServerHello, by extension type."""
    total = int.from_bytes(body[start:start + 2], "big")
    index = start + 2
    end = min(len(body), index + total)
    found: dict[int, bytes] = {}
    while index + 4 <= end:
        kind = int.from_bytes(body[index:index + 2], "big")
        size = int.from_bytes(body[index + 2:index + 4], "big")
        found[kind] = body[index + 4:index + 4 + size]
        index += 4 + size
    return found


def client_hello(data: bytes) -> dict:
    """What a ClientHello offered: the groups it can agree on and the shares it sent."""
    for kind, body in handshake_messages(data):
        if kind != 1:
            continue
        index = 2 + 32
        index += 1 + body[index]                       # legacy session id
        index += 2 + int.from_bytes(body[index:index + 2], "big")
        index += 1 + body[index]
        found = extensions_from(body, index)
        groups: list[int] = []
        if 10 in found:
            block = found[10]
            end = 2 + int.from_bytes(block[0:2], "big")    # also length-prefixed
            groups = [int.from_bytes(block[i:i + 2], "big")
                      for i in range(2, min(end, len(block)) - 1, 2)]
        shares = []
        if 51 in found:
            block = found[51]
            end = 2 + int.from_bytes(block[0:2], "big")   # the list is length-prefixed
            cursor = 2
            while cursor + 4 <= min(end, len(block)):
                group = int.from_bytes(block[cursor:cursor + 2], "big")
                size = int.from_bytes(block[cursor + 2:cursor + 4], "big")
                shares.append({"group": group, "name": GROUP_NAMES.get(group, str(group)),
                               "bytes": size})
                cursor += 4 + size
        return {"bytes": len(body) + 4, "extensions": len(found),
                "supported_groups": [GROUP_NAMES.get(group, str(group)) for group in groups],
                "key_shares": shares}
    return {}


def server_hello_group(data: bytes) -> dict:
    """The key-exchange group the server chose, read from its ServerHello."""
    for kind, body in handshake_messages(data):
        if kind != 2:
            continue
        index = 2 + 32
        index += 1 + body[index]
        index += 3                                      # cipher suite, compression
        found = extensions_from(body, index)
        if 51 in found:
            group = int.from_bytes(found[51][0:2], "big")
            return {"group": GROUP_NAMES.get(group, str(group)), "id": group}
        return {"group": "none", "id": 0}
    return {}


def offer_of(port: int, context: ssl.SSLContext,
             session: ssl.SSLSession | None = None) -> dict:
    """One handshake through a capturing relay: what was offered and what was agreed."""
    proxy = CountingProxy(port, capture=True)
    try:
        tls = context.wrap_socket(socket.create_connection(("127.0.0.1", proxy.port)),
                                  server_hostname="localhost", session=session)
        hello = client_hello(proxy.captured_up())
        agreed = server_hello_group(proxy.captured_down())
        tls.close()
    finally:
        proxy.close()
    return {"client_hello": hello, "server_hello": agreed}


# contexts -------------------------------------------------------------------------
def server_context(cert: str = "ec", version: str = "TLSv1_3", num_tickets: int | None = None,
                   session_tickets: bool = True) -> ssl.SSLContext:
    """A server context, pinned to one version so a comparison isolates one variable."""
    context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    context.load_cert_chain(*cert_pair(cert))
    context.minimum_version = getattr(ssl.TLSVersion, version)
    context.maximum_version = getattr(ssl.TLSVersion, version)
    if version == "TLSv1_2" and not session_tickets:
        context.options |= ssl.OP_NO_TICKET
    if num_tickets is not None:
        context.num_tickets = num_tickets
    return context


def client_context(version: str = "TLSv1_3", verify: bool = False,
                   curve: str | None = None) -> ssl.SSLContext:
    """A client that trusts nothing by default; the probe measures the handshake, not PKI.

    ``curve`` pins the key-exchange group. On OpenSSL 3.5 the default offer includes the
    post-quantum hybrid ``X25519MLKEM768``; pinning ``X25519`` removes it from the offer,
    which is the control probe 01 uses to price the hybrid share.
    """
    context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
    context.minimum_version = getattr(ssl.TLSVersion, version)
    context.maximum_version = getattr(ssl.TLSVersion, version)
    if curve:
        context.set_ecdh_curve(curve)
    if verify:
        context.load_verify_locations(str(CERTS / "ec.pem"), str(CERTS / "ec.pem"))
        context.check_hostname = True
    else:
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE
    return context


# --------------------------------------------------------------------------- server
class TLSServer:
    """An accept loop over one ``SSLContext``, with per-connection facts recorded.

    ``handler(tls)`` runs in its own thread after the handshake; the default answers one
    read with one write. ``idle_s`` bounds how long a handler waits for a read before the
    connection is closed - the knob probe 06 uses to build a reuse race.
    """

    def __init__(self, context: ssl.SSLContext, handler=None, idle_s: float = 30.0,
                 label: str = "", keepalive: bool = False, nodelay: bool = False,
                 port: int = 0):
        self.context = context
        self.handler = handler or (self.keepalive_echo if keepalive else self.echo_once)
        self.nodelay = nodelay
        self.idle_s = idle_s
        self.label = label
        self.lock = threading.Lock()
        self.accepted = 0
        self.handshakes = 0
        self.resumed = 0
        self.handshake_errors: dict[str, int] = {}
        self.handler_errors: dict[str, int] = {}
        self.idle_closes = 0
        self.versions: dict[str, int] = {}
        self.ciphers: dict[str, int] = {}
        self.active = 0
        self.peak_active = 0
        self.handshaking = 0
        self.peak_handshaking = 0
        self.closed = threading.Event()
        self.connections: set[socket.socket] = set()
        self.tls_connections: set[ssl.SSLSocket] = set()
        self.sock = socket.socket()
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.bind(("127.0.0.1", port))
        self.sock.listen(128)
        self.sock.settimeout(0.05)
        self.port = self.sock.getsockname()[1]
        self.thread = threading.Thread(target=self._accept, daemon=True)
        self.thread.start()

    # the default handler -----------------------------------------------------
    RESPONSE = b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: keep-alive\r\n\r\nok"

    def echo_once(self, tls: ssl.SSLSocket) -> None:
        data = tls.recv(65536)
        if data:
            tls.sendall(self.RESPONSE)

    def keepalive_echo(self, tls: ssl.SSLSocket) -> None:
        """Answer every request on the connection until the peer closes or idles out."""
        while True:
            data = tls.recv(65536)
            if not data:
                return
            tls.sendall(self.RESPONSE)

    def _accept(self) -> None:
        while not self.closed.is_set():
            try:
                conn, _ = self.sock.accept()
            except socket.timeout:
                continue
            except OSError:
                return
            threading.Thread(target=self._serve, args=(conn,), daemon=True).start()

    def _serve(self, conn: socket.socket) -> None:
        if self.nodelay:
            try:
                conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
            except OSError:
                pass
        with self.lock:
            self.accepted += 1
            self.active += 1
            self.peak_active = max(self.peak_active, self.active)
            self.connections.add(conn)
        tls = None
        with self.lock:
            self.handshaking += 1
            self.peak_handshaking = max(self.peak_handshaking, self.handshaking)
        try:
            conn.settimeout(self.idle_s)
            tls = self.context.wrap_socket(conn, server_side=True)
        except (ssl.SSLError, OSError, ConnectionError) as exc:
            # A refused or abandoned handshake is a result here, not a crash: probe 05
            # counts these and probe 06 depends on them.
            with self.lock:
                name = type(exc).__name__
                self.handshake_errors[name] = self.handshake_errors.get(name, 0) + 1
                self.active -= 1
                self.handshaking -= 1
            try:
                conn.close()
            except OSError:
                pass
            return
        with self.lock:
            self.handshaking -= 1
            self.handshakes += 1
            self.tls_connections.add(tls)
            if tls.session_reused:
                self.resumed += 1
            self.versions[tls.version()] = self.versions.get(tls.version(), 0) + 1
            cipher = tls.cipher()[0] if tls.cipher() else "none"
            self.ciphers[cipher] = self.ciphers.get(cipher, 0) + 1
        try:
            self.handler(tls)
        except socket.timeout:
            with self.lock:
                self.idle_closes += 1
        except (ssl.SSLError, OSError, ConnectionError) as exc:
            with self.lock:
                name = type(exc).__name__
                self.handler_errors[name] = self.handler_errors.get(name, 0) + 1
        finally:
            with self.lock:
                self.active -= 1
                self.connections.discard(conn)
                self.tls_connections.discard(tls)
            try:
                tls.close()
            except OSError:
                pass

    def stats(self) -> dict:
        with self.lock:
            return {
                "accepted": self.accepted,
                "handshakes": self.handshakes,
                "resumed": self.resumed,
                "full": self.handshakes - self.resumed,
                "handshake_errors": dict(self.handshake_errors),
                "handler_errors": dict(self.handler_errors),
                "idle_closes": self.idle_closes,
                "versions": dict(self.versions),
                "ciphers": dict(self.ciphers),
                "peak_active": self.peak_active,
                "peak_handshaking": self.peak_handshaking,
            }

    def reset(self) -> None:
        with self.lock:
            self.accepted = self.handshakes = self.resumed = 0
            self.peak_active = self.active
            self.peak_handshaking = self.handshaking
            self.handshake_errors.clear()
            self.handler_errors.clear()
            self.idle_closes = 0

    def close(self) -> None:
        self.closed.set()
        try:
            self.sock.close()
        except OSError:
            pass
        self.thread.join(timeout=2.0)

    def abort(self) -> None:
        """Close the listener and every live connection: what a restart does to a pool."""
        self.closed.set()
        try:
            self.sock.close()
        except OSError:
            pass
        with self.lock:
            live = list(self.tls_connections) + list(self.connections)
        for conn in live:
            try:
                conn.shutdown(socket.SHUT_RDWR)
            except OSError:
                pass
            try:
                conn.close()
            except OSError:
                pass
        self.thread.join(timeout=2.0)


# --------------------------------------------------------------------------- proxy
class CountingProxy:
    """A TCP relay that counts every byte it forwards, per direction.

    The handshake's wire size is the counter delta between the client's ``wrap_socket``
    returning and its first application write - read through :meth:`snapshot`, which
    returns ``(client_bytes, server_bytes)``.
    """

    def __init__(self, target_port: int, capture: bool = False):
        self.target_port = target_port
        self.up = 0
        self.down = 0
        self.capture = capture
        self.up_bytes = bytearray()
        self.down_bytes = bytearray()
        self.started = time.perf_counter()
        self.events: list[tuple[float, str, int]] = []
        self.lock = threading.Lock()
        self.stop = threading.Event()
        self.sock = socket.socket()
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.bind(("127.0.0.1", 0))
        self.sock.listen(32)
        self.sock.settimeout(0.05)
        self.port = self.sock.getsockname()[1]
        threading.Thread(target=self._accept, daemon=True).start()

    def _accept(self) -> None:
        while not self.stop.is_set():
            try:
                client, _ = self.sock.accept()
            except socket.timeout:
                continue
            except OSError:
                return
            try:
                server = socket.create_connection(("127.0.0.1", self.target_port))
            except OSError:
                client.close()
                continue
            threading.Thread(target=self._pump, args=(client, server, True), daemon=True).start()
            threading.Thread(target=self._pump, args=(server, client, False), daemon=True).start()

    def _pump(self, src: socket.socket, dst: socket.socket, upward: bool) -> None:
        try:
            while True:
                chunk = src.recv(65536)
                if not chunk:
                    break
                with self.lock:
                    if upward:
                        self.up += len(chunk)
                        if self.capture:
                            self.up_bytes += chunk
                    else:
                        self.down += len(chunk)
                        if self.capture:
                            self.down_bytes += chunk
                    if self.capture:
                        self.events.append(((time.perf_counter() - self.started) * 1000,
                                            "up" if upward else "down", len(chunk)))
                dst.sendall(chunk)
        except OSError:
            pass
        finally:
            try:
                dst.shutdown(socket.SHUT_WR)
            except OSError:
                pass

    def snapshot(self) -> tuple[int, int]:
        with self.lock:
            return self.up, self.down

    def captured_up(self) -> bytes:
        with self.lock:
            return bytes(self.up_bytes)

    def captured_down(self) -> bytes:
        with self.lock:
            return bytes(self.down_bytes)

    def now_ms(self) -> float:
        """Milliseconds since this relay started, so a probe can stamp its own calls."""
        return (time.perf_counter() - self.started) * 1000

    def timeline(self) -> list[dict]:
        """Every chunk that crossed the relay, with the millisecond it crossed."""
        with self.lock:
            return [{"ms": round(when, 2), "direction": direction, "bytes": size}
                    for when, direction, size in self.events]

    def reset(self) -> None:
        with self.lock:
            self.up = self.down = 0

    def records(self) -> list[tuple[int, int]]:
        """TLS records seen downstream as ``(content_type, payload_length)``."""
        with self.lock:
            data = bytes(self.down_bytes)
        out: list[tuple[int, int]] = []
        index = 0
        while index + 5 <= len(data):
            length = int.from_bytes(data[index + 3:index + 5], "big")
            out.append((data[index], length))
            index += 5 + length
        return out

    def close(self) -> None:
        self.stop.set()
        try:
            self.sock.close()
        except OSError:
            pass


class FinDelayRelay:
    """A TCP relay that holds the server's FIN back by a fixed time.

    A close is not visible to the client when the server performs it; it becomes visible
    when the FIN arrives, one one-way latency later. On loopback that latency is
    microseconds, which is what makes the window a pre-write poll leaves look like one
    syscall wide. This relay turns the latency into a setting: bytes cross immediately,
    but when the server's side ends - an orderly FIN or a reset to a write - the relay
    waits ``fin_delay_s`` before it shuts the client's write side, exactly as a network
    with that one-way latency would. ``held`` counts how many closes it delayed.

    Both of its sockets carry ``TCP_NODELAY``. An instrument must not add a stall of its
    own: without the flag the relay's forwarding of a response split into two records paid
    a delayed-ACK pause of about forty milliseconds, which is the effect section 6
    measures and the one thing a relay between client and server must not invent.
    """

    def __init__(self, target_port: int, fin_delay_s: float = 0.0):
        self.target_port = target_port
        self.fin_delay = fin_delay_s
        self.held = 0
        self.lock = threading.Lock()
        self.stop = threading.Event()
        self.sock = socket.socket()
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.bind(("127.0.0.1", 0))
        self.sock.listen(32)
        self.sock.settimeout(0.05)
        self.port = self.sock.getsockname()[1]
        threading.Thread(target=self._accept, daemon=True).start()

    def _accept(self) -> None:
        while not self.stop.is_set():
            try:
                client, _ = self.sock.accept()
            except socket.timeout:
                continue
            except OSError:
                return
            try:
                server = socket.create_connection(("127.0.0.1", self.target_port))
            except OSError:
                client.close()
                continue
            for side in (client, server):
                try:
                    side.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
                except OSError:
                    pass
            threading.Thread(target=self._pump, args=(client, server, True),
                             daemon=True).start()
            threading.Thread(target=self._pump, args=(server, client, False),
                             daemon=True).start()

    def _pump(self, src: socket.socket, dst: socket.socket, upward: bool) -> None:
        ended = False
        try:
            while True:
                chunk = src.recv(65536)
                if not chunk:
                    ended = True
                    break
                dst.sendall(chunk)
        except OSError:
            ended = True
        finally:
            if ended and not upward and self.fin_delay:
                with self.lock:
                    self.held += 1
                time.sleep(self.fin_delay)
            try:
                dst.shutdown(socket.SHUT_WR)
            except OSError:
                pass

    def close(self) -> None:
        self.stop.set()
        try:
            self.sock.close()
        except OSError:
            pass


class DelayRelay:
    """A TCP relay that delays every byte it forwards by one one-way latency.

    Where :class:`FinDelayRelay` delays only the close, this delays the whole path, in
    both directions, which is what distance does to a request and its answer: a client
    that parks a connection one one-way latency after the server sent it, and reuses it a
    given time later, is a whole round trip further along the server's own idle clock than
    its own timer says. The relay is the only way to make that difference measured rather
    than argued: with ``one_way_s = 0.015`` the request and the response each take 15 ms, so
    a request written 79 ms after the park arrives at the server 109 ms into the server's
    own clock - the 79 ms hold plus a 30 ms round trip - and the server's 100 ms timeout
    has already fired.

    One ``sleep`` per forwarded chunk, in the chunk's own thread: a request is one chunk
    and a response is one or two, so the round trip grows by two one-way delays and not by
    one. Both sockets carry ``TCP_NODELAY`` for the reason :class:`FinDelayRelay` gives -
    an instrument must not add a stall of its own.

    The close is a chunk too. When a pump reads end-of-file - the peer's FIN, or a reset
    on a write - it waits the same one-way latency before it shuts the far side's write
    end. Without that wait the relay hands the client a close the server sent one hundred
    milliseconds into its clock as if distance had not applied to it, and the probe then
    measures a network where the FIN overtakes the round trip: a close that left late
    arrives early. ``held`` counts the closes this relay delayed.
    """

    def __init__(self, target_port: int, one_way_s: float = 0.0):
        self.target_port = target_port
        self.one_way = one_way_s
        self.forwarded = 0
        self.held = 0
        self.lock = threading.Lock()
        self.stop = threading.Event()
        self.sock = socket.socket()
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.bind(("127.0.0.1", 0))
        self.sock.listen(32)
        self.sock.settimeout(0.05)
        self.port = self.sock.getsockname()[1]
        threading.Thread(target=self._accept, daemon=True).start()

    def _accept(self) -> None:
        while not self.stop.is_set():
            try:
                client, _ = self.sock.accept()
            except socket.timeout:
                continue
            except OSError:
                return
            try:
                server = socket.create_connection(("127.0.0.1", self.target_port))
            except OSError:
                client.close()
                continue
            for side in (client, server):
                try:
                    side.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
                except OSError:
                    pass
            threading.Thread(target=self._pump, args=(client, server, True),
                             daemon=True).start()
            threading.Thread(target=self._pump, args=(server, client, False),
                             daemon=True).start()

    def _pump(self, src: socket.socket, dst: socket.socket, upward: bool) -> None:
        ended = False
        try:
            while True:
                chunk = src.recv(65536)
                if not chunk:
                    ended = True
                    break
                # The delay belongs to the chunk, in the direction it travels: a request
                # waits one one-way latency towards the server, a response one back.
                if self.one_way:
                    time.sleep(self.one_way)
                dst.sendall(chunk)
                with self.lock:
                    self.forwarded += 1
        except OSError:
            ended = True
        finally:
            # The close travels the same path at the same speed as the bytes before it.
            if ended and self.one_way:
                with self.lock:
                    self.held += 1
                time.sleep(self.one_way)
            try:
                dst.shutdown(socket.SHUT_WR)
            except OSError:
                pass

    def close(self) -> None:
        self.stop.set()
        try:
            self.sock.close()
        except OSError:
            pass


# --------------------------------------------------------------------------- kernel view
TCP_STATES = {1: "ESTABLISHED", 2: "SYN_SENT", 3: "SYN_RECV", 4: "FIN_WAIT1", 5: "FIN_WAIT2",
              6: "TIME_WAIT", 7: "CLOSE", 8: "CLOSE_WAIT", 9: "LAST_ACK", 10: "LISTEN",
              11: "CLOSING"}


def tcp_info(sock) -> dict:
    """The kernel's own report on a connection, from Linux's ``TCP_INFO``.

    The offsets are those of ``struct tcp_info``: the state byte first, then 32-bit
    fields, of which the MSS (16), the receive MSS (20), the unacknowledged byte count
    (24), the smoothed round trip in microseconds (68) and the congestion window (80)
    are the ones these probes read. A platform without the option gets an empty dict
    and the probe records that it could not see.
    """
    try:
        raw = sock.getsockopt(socket.IPPROTO_TCP, 11, 104)
    except (OSError, AttributeError):
        return {}
    if len(raw) < 84:
        return {}
    def field(offset: int) -> int:
        return int.from_bytes(raw[offset:offset + 4], "little")
    return {"state": TCP_STATES.get(raw[0], str(raw[0])), "snd_mss": field(16),
            "rcv_mss": field(20), "unacked": field(24), "rtt_us": field(68),
            "snd_cwnd": field(80)}


def max_segment(sock) -> int:
    """``TCP_MAXSEG``: the segment size the connection is using, as the kernel reports it."""
    try:
        return int(sock.getsockopt(socket.IPPROTO_TCP, socket.TCP_MAXSEG))
    except (OSError, AttributeError):
        return -1


def so_linger(sock) -> dict:
    """``SO_LINGER``: zero means close returns at once and the kernel sends a FIN first."""
    try:
        raw = sock.getsockopt(socket.SOL_SOCKET, socket.SO_LINGER, 8)
    except (OSError, AttributeError):
        return {}
    on_off, seconds = struct.unpack("ii", raw)
    return {"onoff": on_off, "linger_s": seconds}


# --------------------------------------------------------------------------- client
def connect(port: int, context: ssl.SSLContext | None = None, session: ssl.SSLSession | None = None,
            hostname: str = "localhost", timeout: float = 10.0,
            suppress_ragged_eofs: bool = True) -> tuple[ssl.SSLSocket, float]:
    """Connect and handshake; return the socket and the handshake's wall time in ms."""
    context = context or client_context()
    raw = socket.create_connection(("127.0.0.1", port), timeout=timeout)
    started = time.perf_counter()
    try:
        tls = context.wrap_socket(raw, server_hostname=hostname, session=session,
                                  suppress_ragged_eofs=suppress_ragged_eofs)
    except BaseException:
        raw.close()
        raise
    return tls, (time.perf_counter() - started) * 1000


def request(tls: ssl.SSLSocket, body: bytes = b"GET / HTTP/1.1\r\nHost: localhost\r\n\r\n") -> bytes:
    """One request and one read; the response body is not parsed on purpose."""
    tls.sendall(body)
    return tls.recv(65536)


def drain(tls: ssl.SSLSocket, seconds: float = 0.05) -> bytes:
    """Read whatever arrives for ``seconds``; this is how a session ticket is collected."""
    tls.settimeout(seconds)
    chunks = []
    try:
        while True:
            chunk = tls.recv(65536)
            if not chunk:
                break
            chunks.append(chunk)
    except (socket.timeout, ssl.SSLError, OSError):
        pass
    return b"".join(chunks)


def close(tls: ssl.SSLSocket) -> None:
    try:
        tls.close()
    except OSError:
        pass


# --------------------------------------------------------------------------- helpers
def worker_map(function, items: list, workers: int) -> list:
    """Run ``function`` over ``items`` on ``workers`` threads, results in input order."""
    results: list = [None] * len(items)
    index = iter(range(len(items)))
    lock = threading.Lock()

    def pull() -> None:
        while True:
            with lock:
                position = next(index, None)
            if position is None:
                return
            results[position] = function(items[position])

    threads = [threading.Thread(target=pull, daemon=True) for _ in range(max(1, workers))]
    for thread in threads:
        thread.start()
    for thread in threads:
        thread.join()
    return results


def seeded_delays(count: int, spread_s: float, seed: int = 21) -> list[float]:
    """Full-jitter reconnect delays for a herd, drawn once so a rerun is comparable."""
    generator = random.Random(seed)
    return [generator.uniform(0.0, spread_s) for _ in range(count)]

Take the next step


Keep reading

Get the next essay and every new code pack before anyone else — subscribe to the weekly letter. Free tier first, always.