TL;DR
- Twelve requests, cut at the fourth arrival: one GOAWAY with a true cutoff admits 4, answers all 4 and hands 8 back as safe retries – 12 executions, nothing duplicated, 142.1 ms. A silent close leaves all 12 unknowable and runs 16 executions, 4 of them twice.
- hyper-h2 ends the connection on the frame, so a drain for it writes the frame last. With a 0.20 s deadline the door closes at 201.7 ms and the frame waits for the last answer: 24 of 24 kept, 0 lost – against 19 of 24 when the frame went out at the deadline.
- The two-frame handshake answers all 12 at that instant for 378.7 ms more drain, and is the one shape that admits a stream created after it opened. A hold with no deadline is ended by the load, not the drain: 100 admitted and 1,032 ms of drain.
- 120 clients, one second of refusals: 77 arrivals in one 50 ms window without jitter, 20 with full jitter; a 10 % retry budget turns a 3.0-times amplifier into 1.1 and costs 33 points of success on a half-failing upstream. One loopback host, one Python process, 10,000 draws: read the ratios, not the digits.
1. The host, the stack, and what was measured
A GOAWAY is the last thing a server says on a connection, and every retry decision after it depends on one field. This page measures that dependency on real loopback connections, with a server scripted to stop at an exact moment and a client written at frame level, so no answer depends on what a library happens to do. The measurements appear as the functions that produced them; the appendix prints every file, and Reproducing this says what is not printed.
| Item | Measured value | How it was read |
|---|---|---|
| Kernel | 6.12.8+ on x86_64 | platform.release() |
| CPU | Intel(R) Xeon(R) Platinum 8488C, 3 vCPUs | /proc/cpuinfo |
| Python | 3.12.16, CPython | platform.python_version() |
| HTTP/2 library | hyper-h2 4.4.1 | server and the library client |
time.perf_counter step | 166 ns | smallest non-zero delta in a 2 ms spin |
| One request round trip | 1.3 ms median, 1.7 ms p90 | 30 requests, new connection per request |
| Socket pair round trip | 19.2 µs | 100-byte echo on socketpair |
| HEADERS frame on the wire | 34 bytes | one HPACK block, data_to_send() after the preface |
| Listen backlog | queue 4,096, SYN queue 128 | somaxconn, tcp_max_syn_backlog |
| Orphaned FIN_WAIT2 timer | 60 s | tcp_fin_timeout |
The client is the part worth explaining. hyper-h2 moves its connection state to CLOSED when it reads a GOAWAY, so an answer that arrives afterwards is a protocol error rather than a response – a real behaviour, measured in section 5, that cannot be allowed to decide a protocol measurement. The client used for sections 3 to 6 is a frame reader: the client preface, one HPACK-encoded HEADERS frame of 34 bytes per request, then a loop that keeps reading past the GOAWAY.
Out of scope: One host, loopback, no switch, no load balancer. Three trials per configuration; the tables print the trial the other two agreed with, and where a count moved the spread is in the sentence. Absolute times belong to this machine – the ratios are what transfers. hyper-h2 4.4.1 on CPython 3.12.16.
2. Four ways to stop a connection, and one way to lie about it
Every deploy, scale-in and node drain ends connections that carry work. Four shapes are defensible, and they differ in one thing: what they leave the client able to tell from “done, answer lost”. A fifth turns up often enough to measure – a GOAWAY naming the streams already finished while the handlers keep running. RFC 9113 calls the field the highest stream the sender might have taken some action on, so that frame is not a smaller promise but a false one. One choice sits outside the table because it is not a different frame: a hold can keep admitting, and section 5 measures what that buys and what it costs.
| Server does | What the client receives | What it can conclude | Measured | § |
|---|---|---|---|---|
| closes the socket | EOF, no frame | every unanswered stream is ambiguous: it may have run | 12 of 12 ambiguous | 4 |
| stops starting, sends one GOAWAY naming the last stream started, finishes it | GOAWAY, then the answers it promised | above the cutoff: never started, so a retry is safe | 8 safe to retry, 12 executions, 0 duplicated | 4, 5 |
| stops starting, finishes what it started, then sends that GOAWAY | the answers, then one GOAWAY naming them | the same verdicts, delivered before the frame | 4 of 4 kept by hyper-h2 | 4, 5 |
| stops starting, GOAWAY 2^31-1, grace, GOAWAY naming the last stream started | two GOAWAY frames | nothing refused, so a stream created while the first frame travelled is admitted; unanswered at the second frame means ambiguous | 12 answered, 520.8 ms | 4, 6 |
| not a shape to copy: one GOAWAY naming the streams answered, handlers running | a cutoff below work it started | streams above the cutoff called unprocessed although they ran | 4 duplicated executions | 4 |
3. The number in the frame, and the four verdicts it allows
RFC 9113 section 6.8 defines one field a retry decision can use: last_stream_id, “the highest-numbered stream identifier for which the sender of this frame might have taken some action on or might yet take action on”. Every stream above it was not processed. Every stream at or below it is unknown – it may have run, and the answer may sit in a buffer the peer will never read. The field is not a report of what has finished: a server that sets it to its last answer describes neither what it started nor what it will not touch.
Answered or not, and above the cutoff or not, give four verdicts. The two that cost money are the last: a stream at or below the cutoff without an answer is ambiguous, and whether repeating it is safe is a property of the request, not of the frame.
| Stream | Answered | Repeatable | Verdict | What the client may do |
|---|---|---|---|---|
| any | yes | either | ANSWERED | nothing |
| above the cutoff | no | either | RETRY_SAFE | retry on a new connection without asking |
| at or below | no | yes | RETRY_IDEMPOTENT | retry, because a repeat has no extra effect |
| at or below | no | no | UNRETRYABLE | report the ambiguity; a human or a compensating action decides |
from __future__ import annotations
from dataclasses import dataclass
@dataclass(frozen=True)
class GoAway:
"""The two fields of a GOAWAY frame a retry decision needs."""
last_stream_id: int
error_code: int = NO_ERROR
def __post_init__(self) -> None:
if not 0 <= self.last_stream_id <= MAX_STREAM_ID:
raise ValueError("last_stream_id is out of range")
@property
def reconnects(self) -> bool:
return self.error_code in RECONNECTABLE
@property
def accepts_everything(self) -> bool:
"""True for the first frame of a graceful drain: no new streams, nothing refused."""
return self.last_stream_id == MAX_STREAM_ID
def verdict(self, stream_id: int, answered: bool, idempotent: bool) -> str:
"""What the client may do with one stream once this frame has arrived.
``idempotent`` means "safe to repeat": either the method is idempotent or the
request carries an idempotency key the server deduplicates on. A stream at or
below the cutoff without a response is exactly the case where guessing costs
a duplicated side effect.
"""
if stream_id <= 0:
raise ValueError("stream ids start at 1")
if answered:
return ANSWERED
if stream_id > self.last_stream_id:
return RETRY_SAFE
return RETRY_IDEMPOTENT if idempotent else UNRETRYABLE
The order of the two tests is the point. Above the cutoff is retryable even for a POST, because the server never ran it; at or below is not, because it may have. A client that collapses both into “GOAWAY means retry” duplicates exactly the requests whose answers were slowest – the ones most likely to be the writes that mattered – and it does so against a server that told the truth.
4. Twelve streams, six shutdowns, and the executions behind them
One connection, twelve requests at once, each handler holding its stream for 0.05 s plus 0.03 s per arrival, so the answers arrive in order. The cut lands on one event in every row: the fourth request arriving. Four streams have started, eight sit in the server’s buffer, and each shape does what it does – honest single frame, held frame, a held frame that reads its buffer first, the handshake, the silent close, the false frame. Every stream the client did not see answered is retried on a second connection, which the server serves normally. Nothing else varies: same requests, same instant, same retry rule.
The server counts executions, not responses: its handler records that it ran before it sleeps, so a request whose answer never left the process still counts – and that is exactly the request the client cannot see. The client counts verdicts from Table 3.
| Shutdown | Started | Answered | Safe to retry | Ambiguous | Retried | Executed | Drain |
|---|---|---|---|---|---|---|---|
| socket closed, no GOAWAY | 4 | 0 | 0 | 12 | 12 | 16 | 0 |
| one GOAWAY, true cutoff | 4 | 4 | 8 | 0 | 8 | 12 | 142.1 ms |
| hold the work, then one GOAWAY, true cutoff | 4 | 4 | 8 | 0 | 8 | 12 | 141.7 ms |
| hold the frame, read the buffer, then one GOAWAY, true cutoff | 12 | 12 | 0 | 0 | 0 | 12 | 393.8 ms |
| two GOAWAYs, grace 0.50 s | 12 | 12 | 0 | 0 | 0 | 12 | 520.8 ms |
| one GOAWAY, false cutoff | 4 | 0 | 12 | 0 | 12 | 16 | 10.5 ms |
Rows two and three are the same frame in a different order. Both announce last-stream-id 7 – the fourth stream they admitted – both leave 8 streams above it that may be retried without asking, and both execute 12 requests for 12 units of work. Only delivery differs: 4 late answers in the second row, 0 in the third – which decides whether a hyper-h2 client keeps them (section 5).
Row four is the same single frame with one setting changed: it leaves the door open while it reads, so the eight requests sitting in its buffer are admitted, answered, and named – 12 answers and a cutoff of 23, at the cost of the slowest handler’s 393.8 ms against 142.1 ms. So the twelve-against-four split in rows two and three is when the cutoff was taken, not a limit of one frame: a single frame can carry every stream that reached the server before it was written. What it cannot do is admit the one stream created after it – the race Table 8 measures, and the reason the handshake exists.
Row five is the handshake. Its first frame refused nothing, so the eight streams already on the wire are started, answered, and named by the second frame – 12 answers, nothing left to retry, and a socket held 378.7 ms longer than row two’s. What that extra drain buys is one stream, written while the first frame travelled: the race in Table 8.
Row six is the failure mode. It announces stream 0 – nothing had been answered when the drain opened – while 4 streams it started are running, and it closes 10.5 ms later, so the client never sees their answers. The client believes the specification and retries 12; the server runs 4 of them a second time, and 4 executions become 16 after the retry. The frame was well formed and the error code was right; only the execution counter shows it lied – and a client that would not repeat a POST after a silent close retries all four without hesitating.
from __future__ import annotations
from h2kit import NO_ERROR, Cut
def plan(mode: str, trigger: str) -> Cut:
where = TRIGGERS[trigger]
if mode == "silent":
return Cut(mode="silent", stagger=STAGGER_S, **where)
if mode == "strict":
return Cut(mode="strict", stagger=STAGGER_S, close_after_s=0.01, **where)
if mode == "wait":
return Cut(mode="wait", stagger=STAGGER_S, close_after_s=0.0, **where)
if mode == "buffer":
# The same single frame as ``wait``, one setting apart: the door stays open while
# it reads, so the eight requests already in the read buffer are admitted and
# answered, and the frame written at the end names all twelve.
return Cut(mode="wait", stagger=STAGGER_S, close_after_s=0.01, keep_admitting=True,
**where)
if mode == "immediate":
return Cut(mode="immediate", stagger=STAGGER_S, close_after_s=0.01,
error_code=NO_ERROR, **where)
return Cut(mode="graceful", stagger=STAGGER_S, grace_s=GRACE_S, close_after_s=0.02,
**where)
One trigger dictionary – the fourth arrival – builds all six rows, so the mode is the only thing that changes. Every shape, the false one included, stops opening streams at that instant: same admissions, same work, only the figure in the frame differs.
from __future__ import annotations
import time
from dataclasses import dataclass, field
from typing import Callable
@dataclass
class Drain:
"""The server half: stop admitting at the cutoff, and keep answering what was admitted.
Four phases - ``accepting``, ``grace``, ``draining`` and ``closed`` - and the two frames
of RFC 9113 section 6.8 fall between the first three. ``accepting`` is normal service. ``begin()`` writes the first frame - last-stream-id
2^31-1, which refuses nothing - and opens ``grace``: a stream that arrives now was
created before the client could read that frame, so it is admitted, answered, and
covered by the cutoff that follows. ``stop_admitting()`` (or the deadline passing)
moves to ``draining``: nothing new starts, the answers keep going out, and the frame
is still unwritten. ``finish()`` writes that cutoff and moves to ``closed``; a stream
that arrives after it is above the number and is not started.
``should_start`` is the whole discipline in one line: it refuses only once the cutoff
has been announced, so the number in the second frame is true - every stream the
server started is at or below it, and every stream above it was never started.
Two frames or one. ``begin()`` then ``finish()`` is the handshake of RFC 9113 section
6.8, and it is what admits the client's in-flight tail. ``finish()`` alone - it opens
the drain itself - announces the same true cutoff without a grace, and that cutoff is
taken at that instant: a stream the client created while that one frame was in flight
is above it and gets refused. So the handshake buys the tail and costs the grace; the
single frame costs the retries and saves the grace. Neither is safe for a hyper-h2
client to read first, because it ends that client's connection on the first GOAWAY -
hold the frame until the answers are out for it.
The hold, and the deadline it needs. ``hold()`` opens the drain and writes nothing:
keep serving, then write one true cutoff when the work is done. It is the only shape a
server can use when the client is hyper-h2, and it has a weakness the two-frame
handshake does not have - during the hold no frame has gone out, so nothing has told
a well-behaved client (Go, nghttp2, gRPC) to stop creating streams. Under steady load
the arrivals do not end, and a hold with no deadline therefore does not end either.
``deadline_s`` is what bounds it: once it has passed, ``should_start`` refuses, the
cutoff written next names the highest stream that did start, and a stream refused here
is above that number - still the truth the field promises. The deadline bounds the
deploy; the work that was in flight when it passed is answered as usual.
Closing admission and writing the frame are two steps, not one. ``stop_admitting()``
closes the door at the deadline and leaves the frame unwritten until
``finish()``: the answers for the streams already admitted go out first, and the frame
that ends the connection comes after them. For a frame reader the two orders look the
same, but hyper-h2 moves to CLOSED on the frame and raises on the next one, so a frame
written at the deadline throws away the tail it was about to deliver - the streams
that started just before it and are still being answered. Refusing at the deadline and
naming them in the frame ten milliseconds later costs those ten milliseconds and keeps
every answer.
"""
grace_s: float = 0.05
deadline_s: float = 0.0
clock: Callable[[], float] = time.monotonic
phase: str = "accepting"
highest_started: int = 0
highest_finished: int = 0
opened_at: float = 0.0
began_at: float = 0.0
overdue: bool = False
started: set[int] = field(default_factory=set, repr=False)
def should_start(self, stream_id: int) -> bool:
"""Admit a stream unless admission is closed or the deadline has passed.
During ``grace`` this returns True on purpose: the first frame promised the
client that nothing was refused, and a stream that arrives now is one it created
before it could read that frame. Refusing it here would make the first frame a
lie and the second cutoff lower than the work actually done.
The deadline is the other side of that: a hold with no frame out has told the
client nothing, so under load the arrivals never stop. Once ``deadline_s`` has
passed the drain refuses, and the cutoff it writes next covers every stream that
did start - the refused one is above it, which is what the field promises.
``stop_admitting()`` closes admission the same way without waiting for the clock.
"""
if self.phase in ("draining", "closed"):
return False
if self.expired:
self.overdue = True
return False
self.note_started(stream_id)
return True
def note_started(self, stream_id: int) -> None:
if stream_id > self.highest_started:
self.highest_started = stream_id
self.started.add(stream_id)
def note_finished(self, stream_id: int) -> None:
if stream_id > self.highest_finished:
self.highest_finished = stream_id
def hold(self) -> None:
"""Open the drain without writing a frame: keep admitting while the clock runs.
This is the single-frame shape a hyper-h2 fleet needs - say nothing, serve, then
announce one true cutoff - and the clock it starts is the one ``deadline_s`` is
measured against.
"""
if self.phase == "closed":
raise RuntimeError("drain already finished")
if self.phase == "grace":
return
self.phase = "grace"
self.began_at = self.clock()
def stop_admitting(self) -> None:
"""Close admission without writing a frame: answer what was admitted, then finish.
This is the half of the deadline that is not the frame. Called when the deadline
passes (or when a drain decides to stop early), it makes ``should_start`` refuse
while the answers for the streams already admitted are still going out; the frame
that names them is written by ``finish()`` afterwards. A stream refused here is
above the cutoff that frame will carry, so the client may retry it - and a client
that only learns it at the frame still learns it before the connection closes.
"""
if self.phase == "closed":
raise RuntimeError("drain already finished")
if self.phase == "accepting":
self.hold()
self.phase = "draining"
def begin(self) -> int:
"""Open the drain and return the first GOAWAY's last-stream-id.
Only a drain that is still admitting can make the first frame's promise, which is
that nothing was refused. Once ``stop_admitting()`` or the deadline has closed
the door the frame to write is the cutoff, and a 2^31-1 here would tell the client
that no stream was turned away while every stream that arrives is turned away -
so a closed door raises instead of returning a frame that would be false, and
``finish()`` is the call that fits it. Calling it again during the grace is
harmless: the first frame is already out and is named the same way.
"""
if self.phase == "closed":
raise RuntimeError("drain already finished")
if self.phase == "draining":
raise RuntimeError(
"admission is already closed: the frame to write is finish()'s cutoff, "
"not a first frame that would refuse nothing")
if self.phase == "grace":
return MAX_STREAM_ID
self.hold()
return MAX_STREAM_ID
@property
def admitting(self) -> bool:
"""True while a stream that arrives may still be started."""
return self.phase in ("accepting", "grace") and not self.expired
@property
def admission_closed(self) -> bool:
"""True once no further stream may start, whether or not the frame is out."""
return self.phase in ("draining", "closed") or self.expired
@property
def expired(self) -> bool:
"""True once the hold's deadline has passed; nothing may start after it."""
return self.deadline_s > 0 and bool(self.began_at) and self.elapsed_s() >= self.deadline_s
def elapsed_s(self) -> float:
return 0.0 if not self.began_at else self.clock() - self.began_at
def finish(self) -> int:
"""Announce the cutoff and close the drain; returns its last-stream-id.
The number is the highest stream started, including the ones admitted during the
grace or before the deadline passed. After this call a stream that arrives is
above the cutoff and is refused.
"""
if self.phase == "closed":
raise RuntimeError("drain already finished")
if self.phase == "accepting":
self.hold()
self.phase = "closed"
return self.highest_started
def drain_complete(self) -> bool:
"""True when every stream that was started has been answered."""
return self.phase == "closed" and self.highest_finished >= self.highest_started
The other instant. Cut the same connection when the fourth answer has gone out instead, and all 12 streams were admitted before the drain opened: nothing is left to refuse, and the only question is how much of the admitted work each shape still delivers.
| Shutdown | Started | Answered | Safe to retry | Ambiguous | Retried | Executed | Duplicated | Drain |
|---|---|---|---|---|---|---|---|---|
| socket closed, no GOAWAY | 12 | 4 | 0 | 8 | 8 | 20 | 8 | 0.20 ms |
| one GOAWAY, true cutoff | 12 | 12 | 0 | 0 | 0 | 12 | 0 | 242.1 ms |
| hold the work, then one GOAWAY, true cutoff | 12 | 12 | 0 | 0 | 0 | 12 | 0 | 241.4 ms |
| two GOAWAYs, grace 0.50 s | 12 | 12 | 0 | 0 | 0 | 12 | 0 | 521.4 ms |
| one GOAWAY, false cutoff | 12 | 4 | 8 | 0 | 8 | 20 | 8 | 10.6 ms |
Every honest shape answers all 12 and retries nothing, and the handshake’s whole trace is the clock: 242.1 ms for one frame, 521.4 ms for two. A silent close answers the 4 streams that had finished and leaves 8 ambiguous – 8 duplicated executions once the retry carries a key. The false frame runs up the same bill (8 retried, 20 executions, 8 duplicated effects): a false cutoff adds no cost of its own, it adds certainty. The silent close leaves the client guessing, and a client that respects the ambiguity will not repeat a POST it cannot rule out; the frame tells it the retry is safe, and all eight run again.
Note: the drain column runs from the cut to the socket closing – in-flight work plus a close delay for the single-frame shapes, a timer for the false row (whose socket closes while handlers run), and the 0.50 s grace plus the delay for the double GOAWAY, which waits it out whether or not the handlers are done.
5. What the client library does with the frame
Production Python clients use hyper-h2 rather than a frame reader – directly, or through httpx, httpcore, hypercorn or grpclib. The four shapes that deliver answers were run twice, one client each, against identical servers and the same cut; the deadline hold is run twice more, with the frame at the deadline and once behind the answers it names.
| Shutdown | Answers written | Frame reader kept | hyper-h2 kept | Library error |
|---|---|---|---|---|
| one GOAWAY, true cutoff | 4 | 4 | 0 | ProtocolError |
| hold the work, then one GOAWAY | 4 | 4 | 4 | none |
| hold, keep admitting, then one GOAWAY | 12 | 12 | 12 | none |
| two GOAWAYs | 12 | 12 | 0 | ProtocolError |
| hold, deadline 0.20 s, frame at the deadline | 24 | 24 | 19 | ProtocolError |
| hold, deadline 0.20 s, frame after the answers | 24 | 24 | 24 | none |
ProtocolError on the next frame. The third row writes its frame last, after every stream it admitted has been answered, so there is nothing for the library to reject – and nothing bounds that wait except the deadline section 5 measures. The last two rows are that deadline at work, one stream every 10 ms for 1.0 s, and they differ only in where the frame sits: at the deadline, or behind the answers it names.A fleet of hyper-h2 clients needs its answers before the frame. That client hangs up on the GOAWAY and calls the next frame a protocol error, so the single-GOAWAY shape delivers 0 of the 4 answers it wrote, and the two-frame handshake – correct, and right for Go, nghttp2 and gRPC, which read the frame the way RFC 9113 writes it – delivers 0 of 12 here, because the first frame is the one hyper-h2 acts on. Holding the frame keeps every one (4 of 4), at the price of a client not told to stop until the drain ends – and of the streams that arrive meanwhile: a hold that stopped admitting at the cut would have only its 4 answers to deliver while 12 requests were in flight.
And a limit on that claim: nothing here runs Go, nghttp2 or gRPC, so their keeping the connection open past the first frame is RFC 9113 section 6.8 and each project’s own documentation and behaviour, not a measurement in this article – the clients executed here are the two in Table 6, a Python hyper-h2 client and a raw-socket frame reader.
That leaves the third row – serve everything, write one true frame at the end – and it has a limit the table cannot show. While it holds the frame, a client that respects GOAWAYs has heard nothing: Go, nghttp2 and gRPC stop creating streams when they read one, so before it arrives they keep sending. The hold is therefore bounded by the workload, not by the drain. In probe 10 a client opened a stream every 10 ms and kept going for 1.0 s: the drain admitted all 100 of them, wrote its frame 1,012 ms after the hold opened – when the arrivals stopped, not when the work did – and closed 1,032 ms after hold() started. Nothing in that drain decided to end; the client did.
So the hold needs a deadline, and the deadline has to be two things at once: when admission stops, and not when the connection ends. At 0.20 s on the same run the server stopped admitting 201.7 ms after the cut – 24 streams in, 24 answered, the 5 that arrived afterwards refused and every one of them above the cutoff – and wrote its frame at 251.8 ms, once the last admitted handler had answered. The cost is plain: work in flight when the deadline passes is answered, and anything created after it is handed back for a retry instead of absorbed.
Where that frame sits is not cosmetic, and a frame reader cannot see why. At the deadline the last admitted handlers are still running, so a frame written then is followed by the answers it promised – and hyper-h2 has already moved to CLOSED and raises on the next one. The same load read by hyper-h2 prices the two orders: with the frame written at the deadline it kept 19 of the 24 answers it was owed and lost 5 with a ProtocolError; with the frame held until they were written it kept 24 of 24 and lost 0. The wait is one handler – 50.1 ms between the door closing and the frame here – and the streams above the cutoff are retry-safe either way.
The rule to carry away: RFC 9113’s two-frame handshake is the standard shape, and a client that reads both frames should keep it. A server whose clients end the connection on the first frame holds its single frame while it keeps admitting, and puts a deadline on that hold – admission closed first, the frame after the answers it has to deliver. Follow that and every drain has a clock even when nothing else stops it: the grace between the handshake’s frames, or the deadline on the hold.
The number in the frame is invisible to this client: it hangs up on the GOAWAY itself, so a false cutoff and a true one cost it the same answers. What the false frame costs is decided afterwards, by whoever retries – 4 duplicated executions in Table 4.
from __future__ import annotations
import struct
def frame(kind: int, flags: int, stream_id: int, payload: bytes = b"") -> bytes:
return struct.pack(">I", len(payload))[1:] + bytes([kind, flags]) + \
struct.pack(">I", stream_id & 0x7FFFFFFF) + payload
def parse_frame(header: bytes) -> tuple[int, int, int, int]:
length = int.from_bytes(header[0:3], "big")
return length, header[3], header[4], int.from_bytes(header[5:9], "big") & 0x7FFFFFFF
That reader is the mechanism: nine bytes of frame header, a length, a type, a flags byte and a stream id with its high bit masked off. A frame whose payload has not arrived waits in the buffer, and a stream is classified only on a HEADERS or DATA frame with END_STREAM, an RST_STREAM, or the close.
6. The grace is a deadline, and it has to outlast the work
The double GOAWAY has one tunable: the wait between “no new streams” and the real cutoff. It is usually written as a fixed grace – five hundred milliseconds, a few seconds – copied from a framework default. What it has to be is the time the work in flight needs. This probe cuts on the instant section 4 used for its second run, so all twelve streams are admitted and the slowest remaining handler finishes 241.2 ms after the cut.
| Grace | Answered | Ambiguous | Drain time | What the client is left with |
|---|---|---|---|---|
| 0.00 s | 4 | 8 | 20.8 ms | half the batch unanswered and unknowable |
| 0.02 s | 5 | 7 | 40.9 ms | one more answer, 0.03 s of work later |
| 0.05 s | 6 | 6 | 70.8 ms | halfway |
| 0.10 s | 8 | 4 | 121.1 ms | two thirds, four streams still ambiguous |
| 0.20 s | 11 | 1 | 220.8 ms | one stream short of complete |
| 0.30 s | 12 | 0 | 320.9 ms | complete, with the whole batch answered |
| 0.50 s | 12 | 0 | 521.1 ms | no further gain, the longest hold |
| no deadline | 12 | 0 | 241.5 ms | complete, closed as soon as the last answer went |
Note: the grace is printed in seconds because that is how the setting is written, the drain in milliseconds because that is how the loss accumulates. The 0.20 s row closes 20.7 ms before the last answer would have gone out, and the stream it loses is ambiguous rather than unprocessed: the first frame promised nothing would be refused. Past 0.30 s nothing improves – 12 answered either way – and the 0.50 s row holds the socket 521.1 ms against 320.9 ms to deliver the same twelve answers: a grace longer than the work is deploy time paid for nothing.
from __future__ import annotations
import time
import common
from h2kit import Cut, H2Server
from rawkit import RawClient
def run(grace: float) -> dict:
server = H2Server(cut=Cut(at=4, trigger="completed", mode="deadline",
grace_s=grace, close_after_s=0.02, stagger=STAGGER_S),
handler_delay=HANDLER_S)
client = RawClient(server.port, linger_s=0.4)
keys = [f"d{index}" for index in range(STREAMS)]
try:
outcomes = client.batch(keys, idempotency_key=True)
session = server.sessions[0]
common.wait_for(lambda: session.closed_at > 0, 1.0)
closed = session.closed_at or time.perf_counter()
return {
"answered": sum(1 for record in outcomes if record["result"] == "response"),
"ambiguous": sum(1 for record in outcomes if record["result"] == "closed_unanswered"),
"unprocessed": sum(1 for record in outcomes if record["result"] == "goaway_unprocessed"),
"server_completed": len(session.completed),
"drain_ms": round((closed - session.cut_at) * 1000, 1),
"goaways": [item["last_stream_id"] for item in session.goaways],
}
finally:
server.stop()
The grace buys one more thing Table 7 cannot see: not more answers for work already started, but a stream the client created while the first frame travelled. A probe writes twelve requests, cuts on the fourth arrival, then, 0.02 s later – before it has read a single frame – opens a thirteenth on the same connection. On the server’s own clock that stream arrives 20.1 ms after the first GOAWAY was written, which is the window RFC 9113 section 6.8 exists for.
| Shutdown | Late stream | Its verdict | Retried | Executed | Duplicated | Drain |
|---|---|---|---|---|---|---|
| one GOAWAY, true cutoff | refused: it is above the cutoff | RETRY_SAFE | 9 | 13 | 0 | 112.2 ms |
| hold, then one GOAWAY | refused while the drain held its answers | RETRY_SAFE | 9 | 13 | 0 | 110.7 ms |
| two GOAWAYs, grace 0.50 s | admitted, answered 291 ms later | ANSWERED, cutoff 25 | 0 | 13 | 0 | 520.9 ms |
The handshake is the only row that answers it in place, and the only row with nothing to retry: 0 retries against 9, with the second frame naming its stream (25) instead of a number written before the stream existed. Both single-frame shapes refuse it, and a refusal is a safe retry rather than a lost request – 13 executions for 13 requests, nothing run twice. So the trade is round trips against drain time: 408.7 ms of extra drain buys back 9 attempts on a second connection.
Pick the grace from the work: A longer grace is worth its deploy time only against a reader that stays for it; for hyper-h2 it changes nothing, because the first frame already ended that connection (section 5). A wait and a deadline longer than the work end in the same place – they differ when a handler hangs. The deadline bounds the deploy, the wait bounds the loss. Set it from your slowest endpoint’s p99, not from a framework default; if the two disagree, a container runtime will enforce its own.
7. One outage, five retry policies, and the burst each produces
The second half of a GOAWAY is what happens after it: every client that read the frame, and every client that read nothing because the socket closed, decides when to try again. The probe takes 120 clients failing at the same instant against a server that refuses every connection for 1.00 s and then answers, and records when each accepted connection arrived. Only the retry policy varies: base 0.05 s, cap 1.00 s, at most 9 attempts.
| Retry policy | Connections | During the outage | Peak in one 50 ms | All served | Arrivals in the first 100 ms |
|---|---|---|---|---|---|
| fixed 200 ms, no backoff | 720 | 600 | 87 | 80.9 ms | 120 |
| exponential, no jitter | 720 | 600 | 77 | 628.8 ms | 0 |
| exponential, full jitter | 847 | 728 | 20 | 994.4 ms | 29 |
| exponential, equal jitter | 730 | 610 | 18 | 931.9 ms | 24 |
| decorrelated jitter | 739 | 622 | 15 | 999.3 ms | 27 |
The fixed loop wins the race and loses the argument. A metronome is always about to tick, so everything is served 80.9 ms after recovery – and that is the load a service coming back up cannot absorb: 87 connections in 50 ms, five times a second, for the length of the outage. The exponential curve without jitter is worse on both counts: 77 in one window and 628.8 ms to serve them, because the whole fleet computes the same doubling sequence from the same base.
Full jitter flattens it – 77 to 20, a factor of 3.9, with 29 connections in the first 100 ms instead of 0 – and charges for it during the outage: 728 refused against 600, because a draw from the whole interval is often short. It also clears slower: 994.4 ms against 628.8 ms, because a spread-out fleet has a longer tail than a synchronised one. That trade is Table 10.
| Policy | 10 ms buckets used | Clients in the fullest bucket | Peak share | Clients per peak arrival | Third retry, median |
|---|---|---|---|---|---|
| exponential, no jitter | 1 | 10,000 | 100.0 % | 1.00 | 350 ms |
| exponential, full jitter | 35 | 545 | 5.5 % | 18.35 | 173.7 ms |
| exponential, equal jitter | 18 | 1,039 | 10.4 % | 9.62 | 261.9 ms |
| decorrelated jitter | 144 | 216 | 2.2 % | 46.30 | 483.9 ms |
Equal jitter keeps half the interval fixed and randomises the rest: 1,039 in the fullest bucket instead of 545, at the cost of a later median. Decorrelated draws from [base, previous x 3] rather than an attempt counter and spreads widest – 216 in the fullest bucket, 46.30 clients per arrival – and pays with the longest tail: 483.9 ms against 173.7 ms for full jitter.
from __future__ import annotations
import random
def exponential(attempt: int, base_s: float = DEFAULT_BASE_S,
cap_s: float = DEFAULT_CAP_S) -> float:
"""The undecorated delay for ``attempt`` (1 is the first retry), capped."""
if attempt < 1:
raise ValueError("attempt starts at 1")
if base_s <= 0:
raise ValueError("base_s must be positive")
if cap_s < base_s:
raise ValueError("cap_s is below base_s")
return min(cap_s, base_s * (2.0 ** (attempt - 1)))
def full_jitter(attempt: int, base_s: float = DEFAULT_BASE_S, cap_s: float = DEFAULT_CAP_S,
rng: random.Random | None = None) -> float:
"""A delay drawn uniformly from the whole exponential interval."""
random_source = rng or random
return random_source.uniform(0.0, exponential(attempt, base_s, cap_s))
def decorrelated_jitter(previous_s: float, base_s: float = DEFAULT_BASE_S,
cap_s: float = DEFAULT_CAP_S,
rng: random.Random | None = None) -> float:
"""A delay drawn from ``[base, previous * 3]``, capped; no attempt counter needed."""
if previous_s < base_s:
raise ValueError("previous_s is below base_s")
random_source = rng or random
return min(cap_s, random_source.uniform(base_s, previous_s * 3.0))
from __future__ import annotations
import random
from dataclasses import dataclass, field
@dataclass
class Backoff:
"""The delay policy of one client, with every random draw from its own generator."""
base_s: float = DEFAULT_BASE_S
cap_s: float = DEFAULT_CAP_S
jitter: str = "full"
max_server_wait_s: float | None = DEFAULT_MAX_SERVER_WAIT_S
rng: random.Random = field(default_factory=random.Random)
def __post_init__(self) -> None:
if self.jitter not in {"full", "equal", "exp", "decorrelated"}:
raise ValueError(f"unknown jitter policy {self.jitter!r}")
if self.max_server_wait_s is not None and self.max_server_wait_s < 0:
raise ValueError("max_server_wait_s must be >= 0 or None")
exponential(1, self.base_s, self.cap_s)
def delay(self, attempt: int, retry_after: float | None = None,
previous_s: float | None = None) -> float:
"""The wait before attempt ``attempt + 1``.
A server that named a wait outranks the client's own policy and its ``cap_s``:
honouring it is the difference between backing off and being rate limited
further. Only ``max_server_wait_s`` may override it, and it does so by refusing
the wait - :class:`ServerWaitTooLong` - rather than by shortening it, because a
client that sleeps for its own ceiling instead of the server's number is back
on a service that asked it to stay away.
"""
if retry_after is not None:
wait = max(0.0, retry_after)
if self.max_server_wait_s is not None and wait > self.max_server_wait_s:
raise ServerWaitTooLong(wait, self.max_server_wait_s)
return wait
if self.jitter == "exp":
return exponential(attempt, self.base_s, self.cap_s)
if self.jitter == "equal":
return equal_jitter(attempt, self.base_s, self.cap_s, self.rng)
if self.jitter == "decorrelated":
previous = max(self.base_s, previous_s if previous_s is not None else self.base_s)
return decorrelated_jitter(previous, self.base_s, self.cap_s, self.rng)
return full_jitter(attempt, self.base_s, self.cap_s, self.rng)
The lines that get copied wrong are in Backoff.delay. A Retry-After is the server choosing the delay, so it outranks the client’s curve and its cap_s: clipping a 30-second wait to a five-second cap turns a rate limit into a retry every five seconds. What bounds it is a separate ceiling, max_server_wait_s, and a wait past it is refused, not shortened – a client that sleeps for its own ceiling comes back to a service that asked it to stay away, and an hour-long wait belongs in a queue rather than in a thread. The refusal is an exception the decision turns into a stop, so the caller is told which wait it would not sit out instead of being handed a shorter one.
8. The retry budget: what it saves in an outage and what it costs before one
Jitter decides when a client retries; a budget decides whether it may. The rule here is the one Finagle and Envoy ship: retry while retries stay a small share of the traffic already being sent, with a floor so a quiet client can still retry the call that matters. Finagle counts that share over a window, a percentage of requests with a minimum per second; Envoy computes its allowance from the requests in flight. Either way it scales with real traffic, so an outage cannot multiply it, and a sliding window keeps the state in three numbers: requests, retries, and an allowance of max(min_retries, ratio x requests).
This is not gRPC’s retry throttling, which is a different instrument with the same name. gRPC keeps a token bucket per channel: tokenRatio tokens added per successful RPC up to maxTokens, one removed per failed RPC, and a retry refused while the bucket sits below half its maximum. That watches the failure rate of a channel and gates individual calls; the window budget watches the volume a client generates and is shared by all of its requests. Both stop a storm; a service that copies one while believing it has the other sizes it wrongly.
| Upstream | Client | Requests on the wire | Amplification | Succeeded | Retries denied |
|---|---|---|---|---|---|
| half the requests return 503 | three attempts, no budget | 690 | 1.73x | 89.2 % | 0 |
| half the requests return 503 | three attempts, 10 % budget | 440 | 1.10x | 56.5 % | 172 |
| every request returns 503 | three attempts, no budget | 1,200 | 3.00x | 0 % | 0 |
| every request returns 503 | three attempts, 10 % budget | 440 | 1.10x | 0 % | 395 |
Against a total outage the budget is free money: the same zero successes, 63 % fewer requests on a service that cannot answer any, and the failure surfaces at the caller instead of being retried into a queue. Against a half-failing upstream it costs 33 points of success, because most refused retries would have worked. A ratio tuned for an outage is the wrong ratio for a partial failure, and a service with both needs it sized for the second.
"""How many retries a client fleet may spend.
A retry budget is the one control that survives a total outage. Per-request limits
do not: when every request fails, three attempts per request means three times the
load on a service that was already falling over.
The rule measured in this article is the ratio budget that Finagle and Envoy ship: a
client may retry while its retries stay a small share of the requests it has made -
bounded by a floor, so a quiet client can still retry the one call that matters.
Finagle states it as "retries are allowed up to ``percent`` of requests within a
tumbling window, never fewer than ``minRetries``"; Envoy's retry budget computes an
allowance from the requests in flight and the expected retry rate. Both are the same
idea: the retry allowance scales with real traffic, so an outage cannot multiply it.
This is that idea as a sliding window: retries allowed = ``max(min_retries, ratio *
requests)`` over the last ``window_s`` seconds. Counting in a window rather than storing
tokens makes the budget self-healing - a burst that exhausts it is gone from the count
one window later - and makes the state trivial to log.
It is worth separating this from gRPC's retry throttling, which is a token bucket with
different accounting: the bucket gains ``tokenRatio`` tokens per successful RPC (up to
``maxTokens``) and loses one token per failed RPC, and a retry is refused while the
bucket sits below half its maximum. That mechanism watches the failure *rate* of a
channel; the window budget here watches the *volume* of traffic and is shared by the
client. Both stop a storm; they observe different things about it.
"""
from __future__ import annotations
import threading
import time
from collections import deque
from dataclasses import dataclass, field
from typing import Callable
@dataclass
class RetryBudget:
"""A sliding-window retry budget shared by every request of one client.
``ratio`` is the fraction of calls that may be retried; ``min_retries`` is the
floor that lets a low-traffic client retry at all; ``window_s`` is how long a
request keeps counting. All three are measured from the same clock, which the
tests replace with a fake one.
"""
ratio: float = 0.1
min_retries: float = 10.0
window_s: float = 10.0
clock: Callable[[], float] = time.monotonic
requests: deque[float] = field(default_factory=deque, repr=False)
retries: deque[float] = field(default_factory=deque, repr=False)
denied: int = 0
lock: threading.Lock = field(default_factory=threading.Lock, repr=False)
def __post_init__(self) -> None:
if not 0.0 <= self.ratio <= 1.0:
raise ValueError("ratio must be between 0 and 1")
if self.min_retries < 0 or self.window_s <= 0:
raise ValueError("min_retries must be >= 0 and window_s > 0")
def _expire(self, now: float) -> None:
horizon = now - self.window_s
while self.requests and self.requests[0] < horizon:
self.requests.popleft()
while self.retries and self.retries[0] < horizon:
self.retries.popleft()
def record_request(self) -> None:
"""Count one caller request. Every request, retried or not, is one call."""
with self.lock:
now = self.clock()
self._expire(now)
self.requests.append(now)
def allow(self) -> bool:
"""Spend one retry if the window allows it, and say whether it did."""
with self.lock:
now = self.clock()
self._expire(now)
allowance = max(self.min_retries, self.ratio * len(self.requests))
if len(self.retries) < allowance:
self.retries.append(now)
return True
self.denied += 1
return False
def snapshot(self) -> dict:
"""The state a dashboard needs: what was spent, and what is left."""
with self.lock:
now = self.clock()
self._expire(now)
allowance = max(self.min_retries, self.ratio * len(self.requests))
return {"requests": len(self.requests), "retries": len(self.retries),
"allowance": round(allowance, 3),
"remaining": round(max(0.0, allowance - len(self.retries)), 3),
"denied": self.denied}
Two details make it usable. Counting in a window rather than storing tokens keeps the state to three numbers in a log line and heals a burst one window later without an operator. And the floor matters more than the ratio on a quiet client: a service making one request every ten seconds would otherwise never retry the call that matters.
9. The whole path: the same retries, eighty duplicated effects or none
One program puts the pieces together: 20 batches of 10 requests – 200 logical requests – with every connection cut silently once 6 of its streams are answered, so each batch loses its tail the way a rolling deploy loses one. Three clients face it: a hand-written loop that retries every unanswered stream after a fixed wait with no idempotency key, and the guard with a budget of 10 % and of 50 %.
| Client | Attempts on the wire | Retried | Refused by budget | Executions | Duplicated effects | Unanswered | Batch p50 |
|---|---|---|---|---|---|---|---|
| fixed wait, no key | 280 | 80 | 0 | 280 | 80 | 0 | 188.8 ms |
| guard, 10 % budget | 220 | 20 | 60 | 220 | 0 | 60 | 74.4 ms |
| guard, 50 % budget | 280 | 80 | 0 | 280 | 0 | 0 | 108.4 ms |
Every row faced the same 80 unanswered requests; only the cost differs. The naive loop retried all of them and executed 280 requests for 200 units of work – 40 % of the workload ran twice – because a request whose answer was lost looks exactly like one that never arrived. The 50 % guard retried the same number for the same 280 executions, and the server recognised the key every time: 80 repeats counted, 0 duplicated effects. At 10 % it retried 20 and reported the other 60 as unanswered – visibly, rather than by quietly doubling the load.
from __future__ import annotations
import time
from typing import Callable
from .policy import Outcome, RetryPolicy
def call_with_retry(send: Callable[[int, str | None], Outcome], policy: RetryPolicy,
method: str = "GET", idempotency_key: str | None = None,
sleep: Callable[[float], None] | None = None,
on_retry: Callable[[Attempt, float], None] | None = None,
record_request: bool = True) -> CallResult:
"""Call ``send`` until it answers, the attempts run out, or the budget says stop.
``send`` receives the attempt number and the idempotency key, and returns an
:class:`Outcome` rather than raising: the difference between "the server said no"
and "no answer came back" is the difference between a retryable request and a
duplicated side effect, and an exception thrown across this function erases it.
The wait happens after the decision, never before the first attempt, and a wait
the policy refused is not taken - a budget that only logs refusals while the
client keeps sleeping is a budget that changes nothing.
``record_request`` is for a caller that has already counted the request itself -
a batched client counts the batch, then retries the unanswered members through
this loop, and counting each of those again would let the budget refill itself
with the very retries it is meant to ration.
"""
if sleep is None:
sleep = time.sleep
if policy.budget is not None and record_request:
policy.budget.record_request()
result = CallResult(ok=False)
previous_delay: float | None = None
for attempt_number in range(1, max(policy.max_attempts, policy.max_attempts_unsafe) + 1):
outcome = send(attempt_number, idempotency_key)
attempt = Attempt(number=attempt_number, outcome=outcome)
if outcome.ok:
result.attempts.append(attempt)
result.ok = True
result.value = outcome
result.reason = "answered"
return result
decision = policy.decide(method, attempt_number, outcome,
idempotency_key=idempotency_key,
previous_delay=previous_delay)
attempt.reason = decision.reason
attempt.server_wait_refused = decision.server_wait_refused
if not decision.retry:
result.attempts.append(attempt)
result.reason = decision.reason
return result
attempt.waited_s = decision.delay_s
result.attempts.append(attempt)
if on_retry is not None:
on_retry(attempt, decision.delay_s)
if decision.delay_s > 0:
sleep(decision.delay_s)
previous_delay = decision.delay_s
result.reason = "attempt limit"
return result
from __future__ import annotations
from dataclasses import dataclass, field
from .backoff import Backoff, ServerWaitTooLong
from .budget import RetryBudget
@dataclass
class RetryPolicy:
"""The retry rules of one client.
``max_attempts`` counts the first attempt, so 3 means one call and two retries.
``max_attempts_unsafe`` is separate and defaults to 1: a POST without an
idempotency key is never repeated, however tempting the error looks - unless the
peer's own cutoff says the stream was never processed and ``trust_cutoff`` is on.
"""
max_attempts: int = 3
max_attempts_unsafe: int = 1
backoff: Backoff = field(default_factory=Backoff)
budget: RetryBudget | None = None
trust_cutoff: bool = True
def __post_init__(self) -> None:
if self.max_attempts < 1 or self.max_attempts_unsafe < 1:
raise ValueError("attempt counts start at 1")
@staticmethod
def repeatable(method: str, idempotency_key: str | None) -> bool:
"""Whether repeating this request is safe: the method, or the key, says so."""
return idempotency_key is not None or method.upper() in IDEMPOTENT_METHODS
def decide(self, method: str, attempt: int, outcome: Outcome,
idempotency_key: str | None = None,
previous_delay: float | None = None) -> Decision:
if outcome.ok:
return Decision(False, reason="answered")
safe = self.repeatable(method, idempotency_key)
cutoff_retry = outcome.kind == GOAWAY_UNPROCESSED and self.trust_cutoff
basis = safe or cutoff_retry
limit = self.max_attempts if basis else self.max_attempts_unsafe
if not basis:
return Decision(False, reason=f"not repeatable after {outcome.kind}")
if attempt >= limit:
return Decision(False, reason="attempt limit")
if outcome.kind == STATUS and outcome.status not in RETRYABLE_STATUS:
return Decision(False, reason=f"status {outcome.status}")
try:
delay = self.backoff.delay(attempt, outcome.retry_after, previous_delay)
except ServerWaitTooLong as refused:
# The retry is abandoned rather than shortened. It is decided before the
# budget is asked, so a retry that will not happen spends no allowance.
return Decision(False, server_wait_refused=True,
reason=(f"server asked for {refused.wait_s:g} s, "
f"over the {refused.ceiling_s:g} s ceiling"))
if self.budget is not None and not self.budget.allow():
return Decision(False, reason="budget exhausted")
return Decision(True, delay_s=delay, reason=f"retry after {outcome.kind}")
The loop is dull on purpose: send, decide, wait, send again, with the same key on every attempt so the server can tell a repeat from a new request. The decision takes five inputs, and the two a framework usually hides are the ones that matter – whether the request may be repeated at all, and whether the budget still allows an attempt.
The key is the load-bearing part: A retry without an idempotency key is not a retry, it is a second request. The measured difference in Table 12 is 80 duplicated effects against 0, with the same retry count and the same wire volume in two of the three rows. If a service cannot accept a key – a third-party API, a legacy endpoint – the only safe policy for its writes is the middle row: no retry below the cutoff.
10. The package, and what each file decides
The code is one small package, streamguard: 6 modules, 802 lines, and 129 tests in 6 files. Each module answers one question the page asked, and none imports a framework: the loop takes a callable, the budget takes a clock, the verdicts take two integers.
| Module | Owns | Public surface | Tested by |
|---|---|---|---|
goaway.py | the verdict table, and the drain that names what it admitted | GoAway.verdict, Drain | 37 tests |
backoff.py | the delay curves, jitter, Retry-After | Backoff, full_jitter, retry_after_seconds | 34 tests |
budget.py | the sliding-window retry budget | RetryBudget.allow, snapshot | 11 tests |
policy.py | one decision over method, attempt, outcome and budget | RetryPolicy.decide, Outcome | 29 tests |
client.py | the loop that applies it, with every wait accounted for | call_with_retry, CallResult | 14 tests |
pytest -q reports as one run. The remaining 4 are in test_integration.py, which starts the scripted server and holds the end-to-end checks below.Three tests encode the page rather than the code: one drains a real connection mid-batch and asserts that an honest drain answers everything it admitted and retries nothing; one cuts every connection at its first request and asserts that the fleet spends exactly its budget; one asserts that a Retry-After past the client’s ceiling stops the call instead of being shortened to the ceiling. The first two start the scripted server the probes use, so a change that makes the guard pass while the protocol stops behaving fails the suite.
Ship the cutoff, then the key, then the budget: Deploy order beats the ratio. Ship the server first: its cutoff is what makes the client’s verdicts true, and which shape that cutoff takes is already settled – RFC 9113’s two-frame handshake where the clients read both frames, and where they cannot (hyper-h2 ends the connection on the first) one frame held back while the server keeps admitting, with a deadline on that hold and the frame written after the answers. Then the key, on every write that can be repeated. Then the budget, once the first two are in place – a budget in front of a server that duplicates work and a client that guesses only fails faster.
Frequently asked questions
Is a GOAWAY frame an error or a shutdown?
It is an instruction, and the error code says which kind. NO_ERROR means the sender will not accept new streams on this connection and the client should finish or move them; any other code says why it stopped. Either way the frame is final for new streams: after it, a stream can only be created on another connection.
What exactly does last_stream_id promise?
That the sender has not acted, and will not act, on any stream above that number. It says nothing about the streams at or below it – they may have completed, may still be running, and their answers may be lost. That asymmetry is why the field decides retries but cannot decide idempotency – and why a server that sets it to its last finished stream, with handlers still running, has said something untrue.
Can I retry a POST that was above the cutoff?
At the protocol level, yes: the server promised it never started it. The promise is only worth the server’s discipline. Where the server sent a false cutoff while its handlers kept running, retrying those streams executed 4 requests a second time. Retry writes above the cutoff only when the cutoff comes from a server that stops starting work before it announces, and keep an idempotency key for the ones below it.
Why did a rolling deploy duplicate some orders?
Because the client saw 12 of 12 streams close without an answer and retried all of them. A silent close leaves every unanswered stream ambiguous, so a write that ran before the socket died runs again when a client retries it anyway: 4 duplicated effects and 16 executions for 12 requests in the measurement.
Does hyper-h2 read responses after a GOAWAY?
No. In 4.4.1 it moves the connection to CLOSED when it reads the frame and raises ProtocolError on the next one, so a drain that sent its GOAWAY first delivered 0 of 4 answers to that client, while one that held the frame until its work was answered delivered 4 of 4. Finish writing answers before the frame if the drain has to deliver them.
Full jitter or decorrelated jitter?
Full jitter is the safer default: no state beyond the attempt number, and the delay is bounded by the exponential interval. In the measurement of 10,000 clients failing together, full jitter put 545 clients in the fullest 10 ms bucket and decorrelated put 216, at a median third retry of 173.7 ms against 483.9 ms. Choose decorrelated when the peak matters more than the tail; full jitter when you have no latency budget to trade.
What ratio should the retry budget use?
One you can defend as load. At 10 % a total outage cost 63 % fewer requests with no change in successes, and a half-failing upstream lost 33 points of success against an unbudgeted client. Raise the ratio toward the failure share you are prepared to retry; lower it when the upstream is shared with traffic that cannot retry.
Is the two-frame handshake worth doing?
It is the shape RFC 9113 defines, and the right one for Go, nghttp2 and gRPC clients that keep reading after the first frame. What it buys is the work a single frame has to refuse: a stream the client creates while that frame travels. Here the 8 requests already on the wire were admitted and answered instead of handed back, and a thirteenth stream written the same way was answered in place – 0 retries against 9. What it costs is the grace – 378.7 ms of drain at that instant – and, against hyper-h2, every answer, because that client ends the connection on the first frame. The one-frame variant section 5 measures is not free either: it holds its frame while it keeps admitting, so it needs a deadline, and the frame has to wait for the answers it promised. RFC 9113’s two-frame handshake stays the standard shape for the clients that read it; the hold is what a server does for the ones that cannot.
How long should the grace between the two GOAWAY frames be?
At least the time the work already in flight needs – the grace is a deadline, not a delay. Here the slowest remaining handler answered 241.2 ms after the drain opened, so a grace of 0.10 s, whose socket closed 121.1 ms after the cut, lost 4 streams, while 0.30 s (closed 320.9 ms after the cut) lost 0. Take the p99 of the slowest endpoint that can be in flight, not a framework default – and note that against a hyper-h2 client no grace helps, because the first frame already ended the connection.
Reproducing this
The appendix prints every file the measurements run. 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.
- Four constants set every drain experiment:
STREAMS(12),HANDLER_S(0.05 s),STAGGER_S(0.03 s) andGRACE_S(0.50 s) between the two GOAWAY frames; the in-flight probe of section 6 spreads its handlers by 0.02 s and opens its late stream 0.02 s into the batch. - The storm probe adds
CLIENTS(120), an outage of 1.00 s, base 0.05 s, cap 1.00 s, at most 9 attempts and a fixed delay of 200 ms; the jitter probe draws 10,000 clients per policy from a seededrandom.Randomand buckets arrivals into 10 ms windows; the hold probe of section 5 opens one stream every 10 ms for 1.0 s against a drain that keeps admitting, with and without its 0.20 s deadline. - The appendix holds the six package modules and the three harness modules –
common.py(records, percentiles, the loopback listener),h2kit.py(the scripted server, itsCut, the GOAWAY writer) andrawkit.py(the frame reader) – printed in full, not excerpted. - Absent from this page: the eleven probe scripts. They add no logic to what the appendix prints and only wire a harness to a table; each writes one JSON record, and the rest of its output is progress on a terminal.
00_host.pyfeeds Table 1,01_drain.pyTables 2, 4 and 5,02_h2client.pyTable 6,05_grace.pyTable 7,09_inflight.pyTable 8,03_storm.pyTable 9,04_jitter.pyTable 10,06_budget.pyTable 11,07_endtoend.pyTable 12,08_tests.pyTable 13 and10_hold.pysection 5. Every number on the page is read from those records, so a figure that was never measured cannot be printed. - Every block on this page prints definitions, not behaviour: running the file that contains them is what writes the record. The suite runs with
PYTHONPATH=module:sandbox python3 -m pytest -q module/streamguard/tests, starts the same scripted server the probes use, and fails if the protocol stops behaving underneath the guard.
Appendix: the streamguard source, and the harness it runs on
The verdict table and the true cutoff: goaway.py
"""What a GOAWAY lets a caller conclude, and the drain a server should run instead.
RFC 9113 section 6.8 gives a GOAWAY frame one number that matters: ``last_stream_id``,
"the highest-numbered stream that the sender might have taken some action on". Every
stream above it was not processed, so a client may retry it on another connection
without asking anyone. Every stream at or below it is unknown: it may be done and its
answer lost, and whether retrying it is safe depends on the request, not the frame.
The second half of the module is the server's side of the same rule (``Drain``): stop
admitting at the cutoff, announce the highest stream actually taken on, and keep
answering what was admitted. One frame sets its cutoff at the instant it is written, so
a stream the client sent while that frame was in flight is above the cutoff and has to be
refused - correct, and a retry the client pays for. RFC 9113 section 6.8 adds a first
frame - last-stream-id 2^31-1, a grace, then the real cutoff - so that a stream arriving
while the first frame travelled is admitted and named by the second one. That handshake
buys exactly that in-flight tail, at the price of the grace it holds the connection open.
It is also the shape a hyper-h2 client cannot use, because it ends the connection on the
first frame, so a server that faces such clients holds one frame back while it keeps
admitting (``Drain.hold``) - and puts a deadline on that hold, because while no frame is
out a well-behaved client has no reason to stop creating streams. The deadline closes
admission, not the connection: ``Drain.stop_admitting`` refuses further streams and the
frame still waits for the handlers that were admitted, because a hyper-h2 client throws
away every answer that follows the frame. What no shape may do is name finished streams
while handlers keep running: that frame is false about the future, and the retries it
invites can repeat work the server has already done.
"""
from __future__ import annotations
import time
from dataclasses import dataclass, field
from typing import Callable
MAX_STREAM_ID = 2 ** 31 - 1
NO_ERROR = 0
PROTOCOL_ERROR = 1
INTERNAL_ERROR = 2
REFUSED_STREAM = 7
ENHANCE_YOUR_CALM = 11
ANSWERED = "answered"
RETRY_SAFE = "retry_safe"
RETRY_IDEMPOTENT = "retry_idempotent"
UNRETRYABLE = "unretryable"
# A connection whose GOAWAY carried one of these is worth reconnecting to. A
# protocol or flow-control error is not: the peer believes this client broke the
# connection, and asking again on a new one repeats what broke it.
RECONNECTABLE = frozenset({NO_ERROR, INTERNAL_ERROR, REFUSED_STREAM, ENHANCE_YOUR_CALM})
@dataclass(frozen=True)
class GoAway:
"""The two fields of a GOAWAY frame a retry decision needs."""
last_stream_id: int
error_code: int = NO_ERROR
def __post_init__(self) -> None:
if not 0 <= self.last_stream_id <= MAX_STREAM_ID:
raise ValueError("last_stream_id is out of range")
@property
def reconnects(self) -> bool:
return self.error_code in RECONNECTABLE
@property
def accepts_everything(self) -> bool:
"""True for the first frame of a graceful drain: no new streams, nothing refused."""
return self.last_stream_id == MAX_STREAM_ID
def verdict(self, stream_id: int, answered: bool, idempotent: bool) -> str:
"""What the client may do with one stream once this frame has arrived.
``idempotent`` means "safe to repeat": either the method is idempotent or the
request carries an idempotency key the server deduplicates on. A stream at or
below the cutoff without a response is exactly the case where guessing costs
a duplicated side effect.
"""
if stream_id <= 0:
raise ValueError("stream ids start at 1")
if answered:
return ANSWERED
if stream_id > self.last_stream_id:
return RETRY_SAFE
return RETRY_IDEMPOTENT if idempotent else UNRETRYABLE
@dataclass
class Drain:
"""The server half: stop admitting at the cutoff, and keep answering what was admitted.
Four phases - ``accepting``, ``grace``, ``draining`` and ``closed`` - and the two frames
of RFC 9113 section 6.8 fall between the first three. ``accepting`` is normal service. ``begin()`` writes the first frame - last-stream-id
2^31-1, which refuses nothing - and opens ``grace``: a stream that arrives now was
created before the client could read that frame, so it is admitted, answered, and
covered by the cutoff that follows. ``stop_admitting()`` (or the deadline passing)
moves to ``draining``: nothing new starts, the answers keep going out, and the frame
is still unwritten. ``finish()`` writes that cutoff and moves to ``closed``; a stream
that arrives after it is above the number and is not started.
``should_start`` is the whole discipline in one line: it refuses only once the cutoff
has been announced, so the number in the second frame is true - every stream the
server started is at or below it, and every stream above it was never started.
Two frames or one. ``begin()`` then ``finish()`` is the handshake of RFC 9113 section
6.8, and it is what admits the client's in-flight tail. ``finish()`` alone - it opens
the drain itself - announces the same true cutoff without a grace, and that cutoff is
taken at that instant: a stream the client created while that one frame was in flight
is above it and gets refused. So the handshake buys the tail and costs the grace; the
single frame costs the retries and saves the grace. Neither is safe for a hyper-h2
client to read first, because it ends that client's connection on the first GOAWAY -
hold the frame until the answers are out for it.
The hold, and the deadline it needs. ``hold()`` opens the drain and writes nothing:
keep serving, then write one true cutoff when the work is done. It is the only shape a
server can use when the client is hyper-h2, and it has a weakness the two-frame
handshake does not have - during the hold no frame has gone out, so nothing has told
a well-behaved client (Go, nghttp2, gRPC) to stop creating streams. Under steady load
the arrivals do not end, and a hold with no deadline therefore does not end either.
``deadline_s`` is what bounds it: once it has passed, ``should_start`` refuses, the
cutoff written next names the highest stream that did start, and a stream refused here
is above that number - still the truth the field promises. The deadline bounds the
deploy; the work that was in flight when it passed is answered as usual.
Closing admission and writing the frame are two steps, not one. ``stop_admitting()``
closes the door at the deadline and leaves the frame unwritten until
``finish()``: the answers for the streams already admitted go out first, and the frame
that ends the connection comes after them. For a frame reader the two orders look the
same, but hyper-h2 moves to CLOSED on the frame and raises on the next one, so a frame
written at the deadline throws away the tail it was about to deliver - the streams
that started just before it and are still being answered. Refusing at the deadline and
naming them in the frame ten milliseconds later costs those ten milliseconds and keeps
every answer.
"""
grace_s: float = 0.05
deadline_s: float = 0.0
clock: Callable[[], float] = time.monotonic
phase: str = "accepting"
highest_started: int = 0
highest_finished: int = 0
opened_at: float = 0.0
began_at: float = 0.0
overdue: bool = False
started: set[int] = field(default_factory=set, repr=False)
def should_start(self, stream_id: int) -> bool:
"""Admit a stream unless admission is closed or the deadline has passed.
During ``grace`` this returns True on purpose: the first frame promised the
client that nothing was refused, and a stream that arrives now is one it created
before it could read that frame. Refusing it here would make the first frame a
lie and the second cutoff lower than the work actually done.
The deadline is the other side of that: a hold with no frame out has told the
client nothing, so under load the arrivals never stop. Once ``deadline_s`` has
passed the drain refuses, and the cutoff it writes next covers every stream that
did start - the refused one is above it, which is what the field promises.
``stop_admitting()`` closes admission the same way without waiting for the clock.
"""
if self.phase in ("draining", "closed"):
return False
if self.expired:
self.overdue = True
return False
self.note_started(stream_id)
return True
def note_started(self, stream_id: int) -> None:
if stream_id > self.highest_started:
self.highest_started = stream_id
self.started.add(stream_id)
def note_finished(self, stream_id: int) -> None:
if stream_id > self.highest_finished:
self.highest_finished = stream_id
def hold(self) -> None:
"""Open the drain without writing a frame: keep admitting while the clock runs.
This is the single-frame shape a hyper-h2 fleet needs - say nothing, serve, then
announce one true cutoff - and the clock it starts is the one ``deadline_s`` is
measured against.
"""
if self.phase == "closed":
raise RuntimeError("drain already finished")
if self.phase == "grace":
return
self.phase = "grace"
self.began_at = self.clock()
def stop_admitting(self) -> None:
"""Close admission without writing a frame: answer what was admitted, then finish.
This is the half of the deadline that is not the frame. Called when the deadline
passes (or when a drain decides to stop early), it makes ``should_start`` refuse
while the answers for the streams already admitted are still going out; the frame
that names them is written by ``finish()`` afterwards. A stream refused here is
above the cutoff that frame will carry, so the client may retry it - and a client
that only learns it at the frame still learns it before the connection closes.
"""
if self.phase == "closed":
raise RuntimeError("drain already finished")
if self.phase == "accepting":
self.hold()
self.phase = "draining"
def begin(self) -> int:
"""Open the drain and return the first GOAWAY's last-stream-id.
Only a drain that is still admitting can make the first frame's promise, which is
that nothing was refused. Once ``stop_admitting()`` or the deadline has closed
the door the frame to write is the cutoff, and a 2^31-1 here would tell the client
that no stream was turned away while every stream that arrives is turned away -
so a closed door raises instead of returning a frame that would be false, and
``finish()`` is the call that fits it. Calling it again during the grace is
harmless: the first frame is already out and is named the same way.
"""
if self.phase == "closed":
raise RuntimeError("drain already finished")
if self.phase == "draining":
raise RuntimeError(
"admission is already closed: the frame to write is finish()'s cutoff, "
"not a first frame that would refuse nothing")
if self.phase == "grace":
return MAX_STREAM_ID
self.hold()
return MAX_STREAM_ID
@property
def admitting(self) -> bool:
"""True while a stream that arrives may still be started."""
return self.phase in ("accepting", "grace") and not self.expired
@property
def admission_closed(self) -> bool:
"""True once no further stream may start, whether or not the frame is out."""
return self.phase in ("draining", "closed") or self.expired
@property
def expired(self) -> bool:
"""True once the hold's deadline has passed; nothing may start after it."""
return self.deadline_s > 0 and bool(self.began_at) and self.elapsed_s() >= self.deadline_s
def elapsed_s(self) -> float:
return 0.0 if not self.began_at else self.clock() - self.began_at
def finish(self) -> int:
"""Announce the cutoff and close the drain; returns its last-stream-id.
The number is the highest stream started, including the ones admitted during the
grace or before the deadline passed. After this call a stream that arrives is
above the cutoff and is refused.
"""
if self.phase == "closed":
raise RuntimeError("drain already finished")
if self.phase == "accepting":
self.hold()
self.phase = "closed"
return self.highest_started
def drain_complete(self) -> bool:
"""True when every stream that was started has been answered."""
return self.phase == "closed" and self.highest_finished >= self.highest_started
The delay curves and Retry-After: backoff.py
"""Delay between attempts.
Two things decide how a retry storm ends: the shape of the delay (exponential, so a
long outage is not hammered) and the jitter on top of it (so a fleet that failed at
the same instant does not come back at the same instant). Both are here, plus the
parser for the one delay the server gets to choose.
``Retry-After`` outranks both. ``cap_s`` bounds the delay the client *invents*, and
clipping the server's own number with it would turn a 429 carrying ``Retry-After: 30``
into a retry every five seconds - the client insisting on a rate the server already
refused. A separate ceiling, ``max_server_wait_s``, bounds what the client is willing to
sit out at all, and a wait above it is **refused, not shortened**: an hour-long
``Retry-After`` belongs in a queue, not in a sleeping thread and not in a retry that
comes back after sixty seconds because that was the client's ceiling rather than the
server's instruction. The refusal is an exception, ``ServerWaitTooLong``, so a caller
sees a wait it will not sit out instead of a shorter one it did not choose.
The policies are the four named in the literature rather than invented ones:
* ``exp`` - no jitter: ``base * 2 ** (attempt - 1)``. Deterministic, and the reason
a hundred clients that failed together retry together.
* ``full`` - ``uniform(0, exponential)``: the whole interval, so some clients retry
almost at once and the mean wait stays the same.
* ``equal`` - half the interval fixed, half random.
* ``decorrelated`` - ``uniform(base, previous * 3)``, which does not need an attempt
counter, only the delay that came before it.
"""
from __future__ import annotations
import email.utils
import random
import time
from dataclasses import dataclass, field
DEFAULT_BASE_S = 0.1
DEFAULT_CAP_S = 10.0
# A cap on what the client will sit out when the *server* named the wait. Deliberately
# separate from ``cap_s``: one bounds a curve the client chose, the other bounds a
# deadline the server chose, and conflating them silently retries against a rate limit.
DEFAULT_MAX_SERVER_WAIT_S = 60.0
class ServerWaitTooLong(Exception):
"""The server asked for a wait beyond what this client will sit out.
Carries both numbers so a caller can log the instruction it is refusing instead of
only the ceiling it applied.
"""
def __init__(self, wait_s: float, ceiling_s: float) -> None:
super().__init__(f"server asked for {wait_s:g} s, ceiling is {ceiling_s:g} s")
self.wait_s = wait_s
self.ceiling_s = ceiling_s
def exponential(attempt: int, base_s: float = DEFAULT_BASE_S,
cap_s: float = DEFAULT_CAP_S) -> float:
"""The undecorated delay for ``attempt`` (1 is the first retry), capped."""
if attempt < 1:
raise ValueError("attempt starts at 1")
if base_s <= 0:
raise ValueError("base_s must be positive")
if cap_s < base_s:
raise ValueError("cap_s is below base_s")
return min(cap_s, base_s * (2.0 ** (attempt - 1)))
def full_jitter(attempt: int, base_s: float = DEFAULT_BASE_S, cap_s: float = DEFAULT_CAP_S,
rng: random.Random | None = None) -> float:
"""A delay drawn uniformly from the whole exponential interval."""
random_source = rng or random
return random_source.uniform(0.0, exponential(attempt, base_s, cap_s))
def equal_jitter(attempt: int, base_s: float = DEFAULT_BASE_S, cap_s: float = DEFAULT_CAP_S,
rng: random.Random | None = None) -> float:
"""Half the exponential interval plus a uniform draw from the other half."""
random_source = rng or random
half = exponential(attempt, base_s, cap_s) / 2.0
return half + random_source.uniform(0.0, half)
def decorrelated_jitter(previous_s: float, base_s: float = DEFAULT_BASE_S,
cap_s: float = DEFAULT_CAP_S,
rng: random.Random | None = None) -> float:
"""A delay drawn from ``[base, previous * 3]``, capped; no attempt counter needed."""
if previous_s < base_s:
raise ValueError("previous_s is below base_s")
random_source = rng or random
return min(cap_s, random_source.uniform(base_s, previous_s * 3.0))
def retry_after_seconds(value: str | int | float | None,
now: float | None = None) -> float | None:
"""Read a ``Retry-After`` value: delta-seconds or an HTTP-date, never negative.
Returns ``None`` when the header is absent or unparseable, so a caller can tell
"the server asked for a specific wait" from "no opinion" and use its own backoff
in the second case.
"""
if value is None:
return None
if isinstance(value, (int, float)):
if isinstance(value, bool):
raise TypeError("bool is not a Retry-After value")
return max(0.0, float(value))
text = str(value).strip()
if not text:
return None
try:
return max(0.0, float(text))
except ValueError:
pass
try:
parsed = email.utils.parsedate_to_datetime(text)
except (TypeError, ValueError):
return None
if parsed is None:
return None
reference = time.time() if now is None else now
return max(0.0, parsed.timestamp() - reference)
@dataclass
class Backoff:
"""The delay policy of one client, with every random draw from its own generator."""
base_s: float = DEFAULT_BASE_S
cap_s: float = DEFAULT_CAP_S
jitter: str = "full"
max_server_wait_s: float | None = DEFAULT_MAX_SERVER_WAIT_S
rng: random.Random = field(default_factory=random.Random)
def __post_init__(self) -> None:
if self.jitter not in {"full", "equal", "exp", "decorrelated"}:
raise ValueError(f"unknown jitter policy {self.jitter!r}")
if self.max_server_wait_s is not None and self.max_server_wait_s < 0:
raise ValueError("max_server_wait_s must be >= 0 or None")
exponential(1, self.base_s, self.cap_s)
def delay(self, attempt: int, retry_after: float | None = None,
previous_s: float | None = None) -> float:
"""The wait before attempt ``attempt + 1``.
A server that named a wait outranks the client's own policy and its ``cap_s``:
honouring it is the difference between backing off and being rate limited
further. Only ``max_server_wait_s`` may override it, and it does so by refusing
the wait - :class:`ServerWaitTooLong` - rather than by shortening it, because a
client that sleeps for its own ceiling instead of the server's number is back
on a service that asked it to stay away.
"""
if retry_after is not None:
wait = max(0.0, retry_after)
if self.max_server_wait_s is not None and wait > self.max_server_wait_s:
raise ServerWaitTooLong(wait, self.max_server_wait_s)
return wait
if self.jitter == "exp":
return exponential(attempt, self.base_s, self.cap_s)
if self.jitter == "equal":
return equal_jitter(attempt, self.base_s, self.cap_s, self.rng)
if self.jitter == "decorrelated":
previous = max(self.base_s, previous_s if previous_s is not None else self.base_s)
return decorrelated_jitter(previous, self.base_s, self.cap_s, self.rng)
return full_jitter(attempt, self.base_s, self.cap_s, self.rng)
The sliding-window retry budget: budget.py
"""How many retries a client fleet may spend.
A retry budget is the one control that survives a total outage. Per-request limits
do not: when every request fails, three attempts per request means three times the
load on a service that was already falling over.
The rule measured in this article is the ratio budget that Finagle and Envoy ship: a
client may retry while its retries stay a small share of the requests it has made -
bounded by a floor, so a quiet client can still retry the one call that matters.
Finagle states it as "retries are allowed up to ``percent`` of requests within a
tumbling window, never fewer than ``minRetries``"; Envoy's retry budget computes an
allowance from the requests in flight and the expected retry rate. Both are the same
idea: the retry allowance scales with real traffic, so an outage cannot multiply it.
This is that idea as a sliding window: retries allowed = ``max(min_retries, ratio *
requests)`` over the last ``window_s`` seconds. Counting in a window rather than storing
tokens makes the budget self-healing - a burst that exhausts it is gone from the count
one window later - and makes the state trivial to log.
It is worth separating this from gRPC's retry throttling, which is a token bucket with
different accounting: the bucket gains ``tokenRatio`` tokens per successful RPC (up to
``maxTokens``) and loses one token per failed RPC, and a retry is refused while the
bucket sits below half its maximum. That mechanism watches the failure *rate* of a
channel; the window budget here watches the *volume* of traffic and is shared by the
client. Both stop a storm; they observe different things about it.
"""
from __future__ import annotations
import threading
import time
from collections import deque
from dataclasses import dataclass, field
from typing import Callable
@dataclass
class RetryBudget:
"""A sliding-window retry budget shared by every request of one client.
``ratio`` is the fraction of calls that may be retried; ``min_retries`` is the
floor that lets a low-traffic client retry at all; ``window_s`` is how long a
request keeps counting. All three are measured from the same clock, which the
tests replace with a fake one.
"""
ratio: float = 0.1
min_retries: float = 10.0
window_s: float = 10.0
clock: Callable[[], float] = time.monotonic
requests: deque[float] = field(default_factory=deque, repr=False)
retries: deque[float] = field(default_factory=deque, repr=False)
denied: int = 0
lock: threading.Lock = field(default_factory=threading.Lock, repr=False)
def __post_init__(self) -> None:
if not 0.0 <= self.ratio <= 1.0:
raise ValueError("ratio must be between 0 and 1")
if self.min_retries < 0 or self.window_s <= 0:
raise ValueError("min_retries must be >= 0 and window_s > 0")
def _expire(self, now: float) -> None:
horizon = now - self.window_s
while self.requests and self.requests[0] < horizon:
self.requests.popleft()
while self.retries and self.retries[0] < horizon:
self.retries.popleft()
def record_request(self) -> None:
"""Count one caller request. Every request, retried or not, is one call."""
with self.lock:
now = self.clock()
self._expire(now)
self.requests.append(now)
def allow(self) -> bool:
"""Spend one retry if the window allows it, and say whether it did."""
with self.lock:
now = self.clock()
self._expire(now)
allowance = max(self.min_retries, self.ratio * len(self.requests))
if len(self.retries) < allowance:
self.retries.append(now)
return True
self.denied += 1
return False
def snapshot(self) -> dict:
"""The state a dashboard needs: what was spent, and what is left."""
with self.lock:
now = self.clock()
self._expire(now)
allowance = max(self.min_retries, self.ratio * len(self.requests))
return {"requests": len(self.requests), "retries": len(self.retries),
"allowance": round(allowance, 3),
"remaining": round(max(0.0, allowance - len(self.retries)), 3),
"denied": self.denied}
One decision over method, attempt, outcome and budget: policy.py
"""One decision function: given the method, the attempt and what happened, retry or not.
The inputs are deliberately boring, because the arguments that decide a retry are few:
* whether the request can be repeated - an idempotent method, or an idempotency key
the server deduplicates on;
* how many times it has already been tried;
* what came back: a retryable status, a connection that never answered, or a GOAWAY
that says the stream was never processed;
* whether the client's retry budget still allows another attempt.
``trust_cutoff`` is the one judgement the caller has to make. A stream above a
GOAWAY's last-stream-id was never processed, so RFC 9113 says a client may retry it
even when the request is not idempotent. That is only true of a server that stops
starting work before it announces the cutoff; against a server that announces
finished streams while handlers keep running, the same retry is a duplicated
purchase. Leave it on for a peer you control, turn it off for one you do not.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from .backoff import Backoff, ServerWaitTooLong
from .budget import RetryBudget
IDEMPOTENT_METHODS = frozenset({"GET", "HEAD", "PUT", "DELETE", "OPTIONS", "TRACE"})
# Statuses a second attempt can plausibly fix. 501 is not here: the method is not
# implemented and asking again will not implement it. 429 is, because the server is
# telling the client to slow down rather than that the request was wrong.
RETRYABLE_STATUS = frozenset({408, 425, 429, 500, 502, 503, 504})
OK = "ok"
STATUS = "status"
GOAWAY_UNPROCESSED = "goaway_unprocessed"
GOAWAY_AMBIGUOUS = "goaway_ambiguous"
CONNECTION = "connection"
TIMEOUT = "timeout"
KNOWN = frozenset({OK, STATUS, GOAWAY_UNPROCESSED, GOAWAY_AMBIGUOUS, CONNECTION, TIMEOUT})
@dataclass(frozen=True)
class Outcome:
"""What one attempt produced. ``kind`` is the only field the decision reads first."""
kind: str = OK
status: int = 0
retry_after: float | None = None
detail: str = ""
def __post_init__(self) -> None:
if self.kind not in KNOWN:
raise ValueError(f"unknown outcome kind {self.kind!r}")
@property
def ok(self) -> bool:
return self.kind == OK
@property
def ambiguous(self) -> bool:
"""True when the request may have been executed but its answer was lost."""
return self.kind in {GOAWAY_AMBIGUOUS, TIMEOUT, CONNECTION}
@dataclass(frozen=True)
class Decision:
"""What to do after one attempt, and why.
``server_wait_refused`` is set when the attempt *would* have been retried but the
server asked for a wait past the client's ceiling: the caller gets a decision it can
test instead of parsing the reason, and the operation ends rather than being retried
at a rate the server did not ask for.
"""
retry: bool
delay_s: float = 0.0
reason: str = ""
server_wait_refused: bool = False
@dataclass
class RetryPolicy:
"""The retry rules of one client.
``max_attempts`` counts the first attempt, so 3 means one call and two retries.
``max_attempts_unsafe`` is separate and defaults to 1: a POST without an
idempotency key is never repeated, however tempting the error looks - unless the
peer's own cutoff says the stream was never processed and ``trust_cutoff`` is on.
"""
max_attempts: int = 3
max_attempts_unsafe: int = 1
backoff: Backoff = field(default_factory=Backoff)
budget: RetryBudget | None = None
trust_cutoff: bool = True
def __post_init__(self) -> None:
if self.max_attempts < 1 or self.max_attempts_unsafe < 1:
raise ValueError("attempt counts start at 1")
@staticmethod
def repeatable(method: str, idempotency_key: str | None) -> bool:
"""Whether repeating this request is safe: the method, or the key, says so."""
return idempotency_key is not None or method.upper() in IDEMPOTENT_METHODS
def decide(self, method: str, attempt: int, outcome: Outcome,
idempotency_key: str | None = None,
previous_delay: float | None = None) -> Decision:
if outcome.ok:
return Decision(False, reason="answered")
safe = self.repeatable(method, idempotency_key)
cutoff_retry = outcome.kind == GOAWAY_UNPROCESSED and self.trust_cutoff
basis = safe or cutoff_retry
limit = self.max_attempts if basis else self.max_attempts_unsafe
if not basis:
return Decision(False, reason=f"not repeatable after {outcome.kind}")
if attempt >= limit:
return Decision(False, reason="attempt limit")
if outcome.kind == STATUS and outcome.status not in RETRYABLE_STATUS:
return Decision(False, reason=f"status {outcome.status}")
try:
delay = self.backoff.delay(attempt, outcome.retry_after, previous_delay)
except ServerWaitTooLong as refused:
# The retry is abandoned rather than shortened. It is decided before the
# budget is asked, so a retry that will not happen spends no allowance.
return Decision(False, server_wait_refused=True,
reason=(f"server asked for {refused.wait_s:g} s, "
f"over the {refused.ceiling_s:g} s ceiling"))
if self.budget is not None and not self.budget.allow():
return Decision(False, reason="budget exhausted")
return Decision(True, delay_s=delay, reason=f"retry after {outcome.kind}")
The retry loop: client.py
"""The loop that turns a policy into behaviour, with every wait accounted for."""
from __future__ import annotations
import time
from dataclasses import dataclass, field
from typing import Callable
from .policy import Outcome, RetryPolicy
@dataclass
class Attempt:
"""One try: what it returned, how long the client waited before it, and why it stopped."""
number: int
outcome: Outcome
waited_s: float = 0.0
reason: str = ""
server_wait_refused: bool = False
@dataclass
class CallResult:
"""The whole call: every attempt, the value of the last one, and why it stopped."""
ok: bool
attempts: list[Attempt] = field(default_factory=list)
value: object = None
reason: str = ""
@property
def waited_s(self) -> float:
return sum(attempt.waited_s for attempt in self.attempts)
@property
def retries(self) -> int:
return max(0, len(self.attempts) - 1)
@property
def server_wait_refused(self) -> bool:
"""True when the call stopped because the server asked for a wait past the ceiling.
The distinction matters to a caller that has a queue: this is not a failed
request to be picked up again, it is one the server told us to hold.
"""
return bool(self.attempts) and self.attempts[-1].server_wait_refused
def call_with_retry(send: Callable[[int, str | None], Outcome], policy: RetryPolicy,
method: str = "GET", idempotency_key: str | None = None,
sleep: Callable[[float], None] | None = None,
on_retry: Callable[[Attempt, float], None] | None = None,
record_request: bool = True) -> CallResult:
"""Call ``send`` until it answers, the attempts run out, or the budget says stop.
``send`` receives the attempt number and the idempotency key, and returns an
:class:`Outcome` rather than raising: the difference between "the server said no"
and "no answer came back" is the difference between a retryable request and a
duplicated side effect, and an exception thrown across this function erases it.
The wait happens after the decision, never before the first attempt, and a wait
the policy refused is not taken - a budget that only logs refusals while the
client keeps sleeping is a budget that changes nothing.
``record_request`` is for a caller that has already counted the request itself -
a batched client counts the batch, then retries the unanswered members through
this loop, and counting each of those again would let the budget refill itself
with the very retries it is meant to ration.
"""
if sleep is None:
sleep = time.sleep
if policy.budget is not None and record_request:
policy.budget.record_request()
result = CallResult(ok=False)
previous_delay: float | None = None
for attempt_number in range(1, max(policy.max_attempts, policy.max_attempts_unsafe) + 1):
outcome = send(attempt_number, idempotency_key)
attempt = Attempt(number=attempt_number, outcome=outcome)
if outcome.ok:
result.attempts.append(attempt)
result.ok = True
result.value = outcome
result.reason = "answered"
return result
decision = policy.decide(method, attempt_number, outcome,
idempotency_key=idempotency_key,
previous_delay=previous_delay)
attempt.reason = decision.reason
attempt.server_wait_refused = decision.server_wait_refused
if not decision.retry:
result.attempts.append(attempt)
result.reason = decision.reason
return result
attempt.waited_s = decision.delay_s
result.attempts.append(attempt)
if on_retry is not None:
on_retry(attempt, decision.delay_s)
if decision.delay_s > 0:
sleep(decision.delay_s)
previous_delay = decision.delay_s
result.reason = "attempt limit"
return result
The package’s exported names: __init__.py
"""streamguard - the retry decisions an HTTP/2 client and a draining server must share.
Four small pieces, each solving one half of the same failure:
``backoff`` how long to wait between attempts, and what ``Retry-After`` overrides.
``budget`` how many retries the whole client fleet may spend, so a failing
upstream is not asked the same question three times per request.
``goaway`` what a GOAWAY's last-stream-id lets a client conclude about each
stream, and the true cutoff a draining server should announce.
``policy`` one decision function over all of it, plus the retry loop that uses it.
"""
from __future__ import annotations
from .backoff import Backoff, ServerWaitTooLong, decorrelated_jitter, equal_jitter, \
exponential, full_jitter, retry_after_seconds
from .budget import RetryBudget
from .client import CallResult, call_with_retry
from .goaway import ANSWERED, RETRY_IDEMPOTENT, RETRY_SAFE, UNRETRYABLE, Drain, GoAway
from .policy import IDEMPOTENT_METHODS, RETRYABLE_STATUS, Decision, Outcome, RetryPolicy
__all__ = [
"ANSWERED",
"Backoff",
"CallResult",
"Decision",
"Drain",
"GoAway",
"IDEMPOTENT_METHODS",
"Outcome",
"RETRYABLE_STATUS",
"RETRY_IDEMPOTENT",
"RETRY_SAFE",
"RetryBudget",
"RetryPolicy",
"ServerWaitTooLong",
"UNRETRYABLE",
"call_with_retry",
"decorrelated_jitter",
"equal_jitter",
"exponential",
"full_jitter",
"retry_after_seconds",
]
The harness helpers every probe imports: common.py
"""Helpers shared by the article 20 probes: measurement records and loopback plumbing.
Every number the article prints is written through :func:`save` into ``results/``,
one JSON file per probe, and the builder reads only those files. The helpers here
are the timing statistics, the loopback listener and connect, the sysctl reader
and the result loader the probes call.
"""
from __future__ import annotations
import json
import pathlib
import socket
import time
HERE = pathlib.Path(__file__).resolve().parent
ROOT = HERE.parent
RESULTS = ROOT / "results"
SCRATCH = ROOT / "scratch"
HOST = "127.0.0.1"
def save(name: str, payload: dict) -> None:
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.name}")
def load(name: str) -> dict:
return json.loads((RESULTS / f"{name}.json").read_text(encoding="utf-8"))
def percentile(values: list[float], q: float) -> float:
ordered = sorted(values)
if not ordered:
raise ValueError("percentile of an empty sample")
if len(ordered) == 1:
return float(ordered[0])
rank = (len(ordered) - 1) * q / 100.0
low = int(rank)
high = min(low + 1, len(ordered) - 1)
return float(ordered[low] + (ordered[high] - ordered[low]) * (rank - low))
def describe(values: list[float], scale: float = 1.0) -> dict:
"""A sample's shape, with one scale factor so a table can print milliseconds."""
ordered = sorted(values)
return {
"n": len(ordered),
"min": round(ordered[0] * scale, 6),
"p50": round(percentile(ordered, 50) * scale, 6),
"p90": round(percentile(ordered, 90) * scale, 6),
"p99": round(percentile(ordered, 99) * scale, 6),
"max": round(ordered[-1] * scale, 6),
"mean": round(sum(ordered) / len(ordered) * scale, 6),
}
def now() -> float:
return time.perf_counter()
def sysctl(name: str) -> str:
path = pathlib.Path("/proc/sys") / name.replace(".", "/")
return path.read_text().strip()
def listen(backlog: int = 128) -> tuple[socket.socket, int]:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((HOST, 0))
sock.listen(backlog)
return sock, sock.getsockname()[1]
def connect(port: int, timeout: float = 5.0) -> socket.socket:
sock = socket.create_connection((HOST, port), timeout=timeout)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
return sock
def wait_for(predicate, timeout: float = 5.0, interval: float = 0.002) -> bool:
deadline = now() + timeout
while now() < deadline:
if predicate():
return True
time.sleep(interval)
return predicate()
def drain(sock: socket.socket, seconds: float) -> bytes:
"""Read whatever arrives for ``seconds``; used by probes that only need timing."""
sock.settimeout(seconds)
chunks = []
try:
while True:
chunk = sock.recv(65536)
if not chunk:
break
chunks.append(chunk)
except (socket.timeout, TimeoutError):
pass
return b"".join(chunks)
The scripted server and its five shutdowns: h2kit.py
"""A scripted HTTP/2 server and client that a probe can stop at an exact moment.
The server is a real h2 endpoint on loopback: it reads the client preface, accepts
HEADERS frames, runs one handler thread per stream and writes the response back
through the same connection object under one lock. What makes it a probe rather
than a server is :class:`Cut`, which stops a chosen connection in one of five ways:
``silent`` close the socket with no GOAWAY.
``strict`` stop starting work at the cut, send one GOAWAY naming the last stream
started, answer what already started, then close.
``wait`` stop starting work at the cut, answer what already started, and only
then send one GOAWAY naming the last stream started, then close. With
``keep_admitting`` the door stays open while it waits - a stream that
arrives is served and named by the frame at the end - and
``hold_deadline_s`` bounds that wait, because nothing tells a client to
stop creating streams until the frame is written. The deadline closes
admission, not the connection: the frame that names what was admitted is
written only after those answers are out, because a hyper-h2 client ends
the connection on the frame and would discard everything behind it.
``deadline_frame_first`` writes the frame at the deadline instead, which
is the order this discipline replaced; it exists to measure what the tail
costs a library client.
``graceful`` the double GOAWAY of RFC 9113 section 6.8: first with last-stream-id
2^31-1 (no new streams, nothing refused), then, after a grace period,
the real one. Streams that arrive during the grace are admitted and
answered, because the first frame promised the client they would not be
refused; the second frame names them.
``immediate`` send one GOAWAY naming the streams already answered, then close on a
deadline while the handlers it hid are still running - it does not finish
them. This is the frame the specification forbids - the field is
documented as the highest stream the sender *might* act on, and this
server then acts on streams above it - so its row exists to measure the
cost of the number, not as an option to copy.
Every shape reacts to the same two events, ``trigger``: a request arriving or a handler
finishing, and ``at`` of them. Three of them then stop starting new work and finish what
they admitted - the strict frame, the held frame, and the handshake, which keeps
admitting through its grace and refuses only once its second frame is written. The
fourth closes the socket. The fifth writes a false number and then closes on a deadline,
so the only thing that separates its row from the strict one is the number it wrote -
which is why the probe can attribute the difference to that number alone.
The client records for every stream which of four things happened to it, because
those four are the whole retry decision: a response, a GOAWAY or RST_STREAM that
names the stream as unprocessed, a connection closed after the GOAWAY said the
stream was accepted (ambiguous), or a connection closed with no GOAWAY at all
(also ambiguous, and indistinguishable from a response that never came).
"""
from __future__ import annotations
import socket
import threading
import time
from dataclasses import dataclass, field
import h2.config
import h2.connection
import h2.errors
import h2.events
import h2.exceptions
from hyperframe.frame import GoAwayFrame
SERVER_CONFIG = h2.config.H2Configuration(client_side=False, header_encoding="utf-8")
CLIENT_CONFIG = h2.config.H2Configuration(client_side=True, header_encoding="utf-8")
MAX_STREAM_ID = 2 ** 31 - 1
NO_ERROR = 0
REFUSED_STREAM = 7
ENHANCE_YOUR_CALM = 11
RESPONSE = "response"
UNPROCESSED = "goaway_unprocessed"
AMBIGUOUS = "closed_unanswered"
RESET = "stream_reset"
def goaway_frame(last_stream_id: int, error_code: int = NO_ERROR) -> bytes:
"""Serialize one GOAWAY frame without touching the h2 connection's state machine.
``H2Connection.close_connection`` moves that state machine to CLOSED, and a closed
connection refuses every response on a stream the frame said it had accepted -
exactly the frames a drain exists to send. The frame is built here instead, so the
connection stays open until the socket is closed.
"""
frame = GoAwayFrame(stream_id=0)
frame.error_code = error_code
frame.last_stream_id = last_stream_id
return frame.serialize()
@dataclass
class Cut:
"""When to stop a connection, and how.
``trigger`` decides what ``at`` counts: requests whose headers arrived, or
streams whose handler finished. ``stagger`` spreads the handler delays so a
cut in the middle of a batch lands between streams rather than after all of
them; ``cut_connections`` limits the cut to the first N connections, so a
retry can reach the same server and be served.
"""
at: int = 4
trigger: str = "completed"
mode: str = "strict"
grace_s: float = 0.1
error_code: int = NO_ERROR
close_after_s: float = 0.02
stagger: float = 0.0
cut_connections: int = 1
keep_admitting: bool = False
hold_deadline_s: float = 0.0
deadline_frame_first: bool = False
@dataclass
class Session:
"""One accepted connection and everything the server observed on it."""
cid: int
conn: h2.connection.H2Connection
sock: socket.socket
lock: threading.Lock = field(default_factory=threading.Lock)
received: dict[int, float] = field(default_factory=dict)
started: dict[int, float] = field(default_factory=dict)
completed: dict[int, float] = field(default_factory=dict)
refused: list[int] = field(default_factory=list)
goaways: list[dict] = field(default_factory=list)
closed_at: float = 0.0
draining: bool = False
refusing: bool = False
dead: bool = False
cut_at: float = 0.0
admission_closed_at: float = 0.0
def max_started(self) -> int:
return max(self.started) if self.started else 0
class H2Server:
"""An accept loop that runs one :class:`Session` per client connection.
``handler_delay`` is the time a handler holds a stream between doing its work
and answering it: that window is what makes a stream in-flight at the moment
of the cut. ``stagger`` adds ``stagger * (ordinal - 1)`` to that delay so the
completions happen in order instead of together.
"""
def __init__(self, cut: Cut | None = None, handler_delay: float = 0.0,
body: bytes = b'{"ok":true}', status: int = 200,
fail_rate: float = 0.0, fail_seed: int = 1) -> None:
self.cut = cut
self.handler_delay = handler_delay
self.body = body
self.status = status
self.fail_rate = fail_rate
self.fail_random = __import__("random").Random(fail_seed)
self.executions = 0
self.sessions: list[Session] = []
self.effects: dict[str, float] = {}
self.duplicates = 0
self.started_total = 0
self.completed_total = 0
self.lock = threading.Lock()
self.cut_lock = threading.Lock()
self.sock, self.port = self._bind()
self.sock.settimeout(0.1)
self.stopping = threading.Event()
self.thread = threading.Thread(target=self._accept_loop, daemon=True)
self.thread.start()
def _bind(self) -> tuple[socket.socket, int]:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("127.0.0.1", 0))
sock.listen(256)
return sock, sock.getsockname()[1]
# -- connection lifecycle -------------------------------------------------
def _accept_loop(self) -> None:
while not self.stopping.is_set():
try:
client, _ = self.sock.accept()
except (socket.timeout, TimeoutError):
continue
except OSError:
break
client.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
with self.lock:
session = Session(cid=len(self.sessions) + 1,
conn=h2.connection.H2Connection(config=SERVER_CONFIG),
sock=client)
self.sessions.append(session)
threading.Thread(target=self._serve, args=(session,), daemon=True).start()
def _serve(self, session: Session) -> None:
session.conn.initiate_connection()
self._flush(session)
session.sock.settimeout(0.05)
while not session.dead:
try:
data = session.sock.recv(65536)
except (socket.timeout, TimeoutError):
continue
except OSError:
break
if not data:
break
try:
events = session.conn.receive_data(data)
except Exception: # noqa: BLE001 - a cut is the point
break
for event in events:
if isinstance(event, h2.events.RequestReceived):
self._on_request(session, event.stream_id, event.headers)
elif isinstance(event, h2.events.DataReceived):
with session.lock:
session.conn.acknowledge_received_data(
event.flow_controlled_length, event.stream_id)
self._flush(session)
session.closed_at = time.perf_counter()
try:
session.sock.close()
except OSError:
pass
def _on_request(self, session: Session, stream_id: int,
headers: list[tuple[str, str]]) -> None:
if session.dead:
# A close that already happened is a process that is gone: the HEADERS
# frames behind it in the same buffer never reach a handler.
return
session.received[stream_id] = time.perf_counter()
ordinal = len(session.received)
if session.refusing:
self._refuse(session, stream_id)
return
threading.Thread(target=self._handle, args=(session, stream_id, dict(headers), ordinal),
daemon=True).start()
cut = self.cut
if cut is not None and cut.trigger == "received" and not session.draining:
if session.cid <= cut.cut_connections and len(session.received) >= cut.at:
self._await_admitted(session)
self._begin_cut(session)
def _await_admitted(self, session: Session, timeout: float = 0.05) -> None:
"""Wait for the handlers of the streams just received to register themselves.
A handler runs on its own thread and registers a moment after the request
thread starts it. Reading ``started`` before that would let a cut announce a
cutoff below the streams it admitted, and would make the drain close before
they were answered - a race that would show up as a different row on every run.
Bounded, so a stuck thread cannot hold the drain open.
"""
deadline = time.perf_counter() + timeout
while len(session.started) < len(session.received) and time.perf_counter() < deadline:
time.sleep(0)
def _handle(self, session: Session, stream_id: int, headers: dict[str, str],
ordinal: int) -> None:
session.started[stream_id] = time.perf_counter()
with self.lock:
self.started_total += 1
self.executions += 1
fails = self.fail_rate > 0 and self.fail_random.random() < self.fail_rate
status = 503 if fails else self.status
key = headers.get("x-request-id") or f"{session.cid}:{stream_id}"
with self.lock:
if self.effects.get(key):
self.duplicates += 1
else:
self.effects[key] = time.perf_counter()
delay = self.handler_delay + (self.cut.stagger * (ordinal - 1) if self.cut else 0.0)
if delay:
time.sleep(delay)
if session.dead:
return
try:
with session.lock:
session.conn.send_headers(
stream_id,
[(":status", str(status)), ("content-type", "application/json"),
("content-length", str(len(self.body)))],
end_stream=False)
session.conn.send_data(stream_id, self.body, end_stream=True)
self._flush(session)
except Exception: # noqa: BLE001 - a cut is the point
return
session.completed[stream_id] = time.perf_counter()
with self.lock:
self.completed_total += 1
cut = self.cut
if (cut is not None and cut.trigger == "completed" and not session.draining
and session.cid <= cut.cut_connections
and len(session.completed) >= cut.at):
self._begin_cut(session)
# -- the cut --------------------------------------------------------------
def _begin_cut(self, session: Session) -> None:
with self.cut_lock:
if session.draining:
return
session.draining = True
session.cut_at = time.perf_counter()
cut = self.cut
if cut.mode in {"graceful", "deadline"}:
# The first frame says no further stream will be created; one that arrives
# anyway was created before the client could read it, so it is admitted and
# the second frame's cutoff covers it. Refusing it here would make the first
# frame a lie. ``_second_goaway`` starts refusing at the cutoff.
session.refusing = False
self._goaway(session, MAX_STREAM_ID, cut.error_code)
timer = threading.Timer(cut.grace_s, self._second_goaway, args=(session, cut))
timer.daemon = True
timer.start()
return
if cut.mode == "strict":
session.refusing = True
self._goaway(session, session.max_started(), cut.error_code)
timer = threading.Timer(cut.close_after_s, self._close_when_idle,
args=(session, len(session.started)))
timer.daemon = True
timer.start()
return
if cut.mode == "wait":
# No frame until the work is done: the answers go out first, so a client
# that stops reading frames at the GOAWAY still receives them. ``keep_admitting``
# leaves the door open while it waits - a stream that arrives is started and
# answered, and the one frame written at the end names it.
session.refusing = not cut.keep_admitting
timer = threading.Timer(0.0, self._wait_then_announce,
args=(session, cut, len(session.started)))
timer.daemon = True
timer.start()
return
if cut.mode == "immediate":
# The same admissions as ``strict`` and one difference: the frame reports what
# has been *answered* instead of what has been *started*, and the connection
# then closes on a deadline while the handlers it hid are still running - it
# does not finish them.
session.refusing = True
self._goaway(session, max(session.completed) if session.completed else 0,
cut.error_code)
timer = threading.Timer(cut.close_after_s, self._kill, args=(session,))
timer.daemon = True
timer.start()
return
self._kill(session)
def _wait_then_announce(self, session: Session, cut: Cut, target: int) -> None:
"""Answer what was already started, then name it in one GOAWAY, then close.
``target`` is the number of streams started when the cut opened, counted the
way :meth:`_close_when_idle` counts it, so a handler thread that registers late
cannot make the wait end early. With ``keep_admitting`` the target is every stream
that has arrived, and the wait also holds one handler interval after the cut so a
stream still in the client's buffer is read and served instead of lost -
``hold_deadline_s`` ends that hold at a fixed time instead, and whatever arrived
after the number was written is refused.
"""
if cut.keep_admitting and cut.hold_deadline_s > 0:
self._bounded_hold(session, cut)
return
deadline = time.perf_counter() + 2.0
if cut.keep_admitting:
while time.perf_counter() < deadline and not session.dead:
settled = time.perf_counter() - session.cut_at >= self.handler_delay
if settled and len(session.completed) >= len(session.received):
break
time.sleep(0.002)
else:
while time.perf_counter() < deadline and not session.dead:
if len(session.completed) >= target:
break
time.sleep(0.002)
if session.dead:
return
# From the frame on, a stream that arrives is above the number it is writing and
# is refused. Set first, so nothing starts between the count and the frame.
session.refusing = True
self._goaway(session, session.max_started(), cut.error_code)
if cut.close_after_s > 0:
time.sleep(cut.close_after_s)
self._kill(session)
def _bounded_hold(self, session: Session, cut: Cut) -> None:
"""Stop admitting at the deadline, answer what was admitted, then write one frame.
The deadline refuses new streams; it does not end the connection. A hyper-h2
client moves to CLOSED when it reads a GOAWAY and raises on the next frame, so a
frame written at the deadline would throw away every answer still behind it -
the streams that started just before the deadline and finish just after it. The
frame therefore waits for those handlers, names every stream that was admitted,
and closes the connection behind itself. Nothing is left above the cutoff except
the streams the deadline refused, and those may be retried anywhere.
"""
deadline = session.cut_at + cut.hold_deadline_s
while time.perf_counter() < deadline and not session.dead:
time.sleep(0.002)
session.refusing = True
session.admission_closed_at = time.perf_counter()
if cut.deadline_frame_first:
# The order this replaced: the frame goes out at the deadline and the answers
# it hides follow it, which is the tail a library client discards.
self._goaway(session, session.max_started(), cut.error_code)
timer = threading.Timer(0.0, self._close_when_idle, args=(session, len(session.started)))
timer.daemon = True
timer.start()
return
# Every stream that arrived before the door closed is either started or refused;
# wait for the handler threads to register before the count is taken.
settle = time.perf_counter() + 0.05
while (len(session.started) + len(session.refused) < len(session.received)
and time.perf_counter() < settle and not session.dead):
time.sleep(0)
target = len(session.started)
deadline = time.perf_counter() + 2.0
while time.perf_counter() < deadline and not session.dead:
if len(session.completed) >= target:
break
time.sleep(0.002)
if session.dead:
return
self._goaway(session, session.max_started(), cut.error_code)
time.sleep(0.002)
self._kill(session)
def _second_goaway(self, session: Session, cut: Cut) -> None:
if session.dead:
return
# From this frame on, a stream that arrives is above the cutoff: the drain has
# named the last stream it will start, so nothing else may start.
session.refusing = True
self._goaway(session, session.max_started(), cut.error_code)
if cut.mode == "deadline":
# A termination deadline, the way a container runtime imposes one: the
# second GOAWAY goes out and the connection closes whether or not the
# handlers have answered.
timer = threading.Timer(cut.close_after_s, self._kill, args=(session,))
else:
timer = threading.Timer(cut.close_after_s, self._close_when_idle,
args=(session, len(session.started)))
timer.daemon = True
timer.start()
def _close_when_idle(self, session: Session, target: int) -> None:
"""Close once ``target`` streams - those started when the drain began - are answered.
The count is taken at the drain, not read here: a timer can fire before a
handler thread has registered itself, and ``completed >= started`` would then
be true with nothing completed at all.
"""
deadline = time.perf_counter() + 2.0
while time.perf_counter() < deadline and not session.dead:
if len(session.completed) >= target:
break
time.sleep(0.002)
self._kill(session)
def _goaway(self, session: Session, last_stream_id: int, error_code: int) -> None:
"""Write one GOAWAY frame and keep the connection usable for the streams it names.
``H2Connection.close_connection`` would move the h2 state machine to CLOSED,
which then refuses every response on a stream the GOAWAY said it had accepted -
exactly the frames a drain exists to send. The frame is built and written
directly instead, so the connection stays open until :meth:`_kill`.
"""
if session.dead:
return
try:
self._flush(session)
with session.lock:
session.sock.sendall(goaway_frame(last_stream_id, error_code))
except OSError:
session.dead = True
return
session.goaways.append({"at": time.perf_counter(),
"last_stream_id": last_stream_id,
"error_code": error_code})
def _refuse(self, session: Session, stream_id: int) -> None:
"""Record a stream the drain will not start, and send nothing for it.
The GOAWAY already names it as unprocessed, and a real HTTP/2 client moves to
CLOSED when it reads that GOAWAY: an RST_STREAM sent afterwards is a protocol
error to hyper-h2, so a server that "helpfully" resets refused streams makes
the client discard the connection instead of the streams.
"""
session.refused.append(stream_id)
def _kill(self, session: Session) -> None:
session.dead = True
try:
session.sock.shutdown(socket.SHUT_RDWR)
except OSError:
pass
def _flush(self, session: Session) -> None:
try:
with session.lock:
data = session.conn.data_to_send()
if data:
session.sock.sendall(data)
except OSError:
session.dead = True
def stop(self) -> None:
self.stopping.set()
try:
self.sock.close()
except OSError:
pass
for session in self.sessions:
self._kill(session)
class H2Client:
"""Sends requests on one connection and labels each stream the way a retry policy must."""
def __init__(self, port: int, timeout: float = 5.0) -> None:
self.port = port
self.timeout = timeout
self.goaways: list[dict] = []
self.error = ""
self.frames_after_goaway = 0
def batch(self, keys: list[str], idempotency_key: bool = False) -> list[dict]:
"""Open one connection, start every request at once, and read until it closes.
``keys`` name the work, not the stream: the same key on a later connection is
the same logical request, which is what lets the server count a duplicate
instead of a second effect.
"""
sock = socket.create_connection(("127.0.0.1", self.port), timeout=self.timeout)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
conn = h2.connection.H2Connection(config=CLIENT_CONFIG)
conn.initiate_connection()
sock.sendall(conn.data_to_send())
streams: dict[int, dict] = {}
for key in keys:
stream_id = conn.get_next_available_stream_id()
headers = [(":method", "POST"), (":path", "/work/" + key),
(":scheme", "https"), (":authority", "loopback"),
("content-length", "0")]
if idempotency_key:
headers.append(("x-request-id", key))
streams[stream_id] = {"key": key, "status": 0, "done": False,
"result": "", "reset_code": 0,
"started": time.perf_counter()}
conn.send_headers(stream_id, headers, end_stream=True)
sock.sendall(conn.data_to_send())
goaway_last: int | None = None
self.goaways = []
self.error = ""
self.frames_after_goaway = 0
sock.settimeout(self.timeout)
eof = False
while not eof and not self._all(streams):
try:
data = sock.recv(65536)
except (socket.timeout, TimeoutError):
break
if not data:
eof = True
break
try:
events = conn.receive_data(data)
except h2.exceptions.ProtocolError as exc:
self.error = type(exc).__name__
break
for event in events:
if self.goaways:
self.frames_after_goaway += 1
if isinstance(event, h2.events.ResponseReceived):
streams[event.stream_id]["status"] = int(dict(event.headers)[":status"])
elif isinstance(event, h2.events.StreamEnded):
streams[event.stream_id]["done"] = True
streams[event.stream_id]["result"] = RESPONSE
elif isinstance(event, h2.events.StreamReset):
streams[event.stream_id]["reset_code"] = event.error_code
streams[event.stream_id]["result"] = RESET
streams[event.stream_id]["done"] = True
elif isinstance(event, h2.events.ConnectionTerminated):
goaway_last = event.last_stream_id
self.goaways.append({"last_stream_id": event.last_stream_id,
"error_code": event.error_code})
try:
sock.sendall(conn.data_to_send())
except OSError:
eof = True
break
try:
sock.close()
except OSError:
pass
ended = time.perf_counter()
for stream_id, record in streams.items():
if record["result"] == RESPONSE:
record["elapsed"] = ended - record["started"]
continue
if record["result"] == RESET and record["reset_code"] == REFUSED_STREAM:
record["result"] = UNPROCESSED
elif record["result"] == RESET:
record["result"] = (AMBIGUOUS if goaway_last is None or stream_id <= goaway_last
else UNPROCESSED)
elif goaway_last is not None and stream_id > goaway_last:
record["result"] = UNPROCESSED
else:
record["result"] = AMBIGUOUS
record["done"] = True
record["elapsed"] = ended - record["started"]
return [{"stream_id": stream_id, **record} for stream_id, record in streams.items()]
@staticmethod
def _all(streams: dict[int, dict]) -> bool:
return all(record["done"] for record in streams.values())
The frame-level client the protocol was measured with: rawkit.py
"""A frame-level HTTP/2 client: enough of RFC 9113 to measure a drain without a library.
The point of this client is what it does *not* do. hyper-h2 moves its state machine to
CLOSED the moment it reads a GOAWAY and then refuses every later frame, so it cannot
answer the question a drain raises: did the responses the server still had in flight
reach the client? This client reads frames, keeps reading after the GOAWAY, and counts
what arrives - HEADERS and DATA on streams the GOAWAY said were accepted, streams it
said were not, and the order the two arrived in.
It sends the client preface, an empty SETTINGS frame, one HEADERS frame per request
(HPACK-encoded with the hpack package h2 itself uses) and acknowledges the server's
SETTINGS. Nothing else is on the wire.
"""
from __future__ import annotations
import socket
import struct
import time
from hpack import Decoder, Encoder
PREFACE = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
DATA = 0x0
HEADERS = 0x1
RST_STREAM = 0x3
SETTINGS = 0x4
PING = 0x6
GOAWAY = 0x7
WINDOW_UPDATE = 0x8
CONTINUATION = 0x9
END_STREAM = 0x1
END_HEADERS = 0x4
PADDED = 0x8
ACK = 0x1
RESPONSE = "response"
UNPROCESSED = "goaway_unprocessed"
AMBIGUOUS = "closed_unanswered"
RESET = "stream_reset"
def frame(kind: int, flags: int, stream_id: int, payload: bytes = b"") -> bytes:
return struct.pack(">I", len(payload))[1:] + bytes([kind, flags]) + \
struct.pack(">I", stream_id & 0x7FFFFFFF) + payload
def parse_frame(header: bytes) -> tuple[int, int, int, int]:
length = int.from_bytes(header[0:3], "big")
return length, header[3], header[4], int.from_bytes(header[5:9], "big") & 0x7FFFFFFF
class RawClient:
"""One connection, every request started at once, every frame time-stamped."""
def __init__(self, port: int, timeout: float = 5.0, linger_s: float = 0.0) -> None:
self.port = port
self.timeout = timeout
# A pooled client does not hang up when its last answer arrives: it keeps the
# connection for the next request, which is exactly why it sees the second
# GOAWAY of a drain. The linger is how long this one keeps reading after its
# own streams are done.
self.linger_s = linger_s
self.frames: list[dict] = []
self.goaways: list[dict] = []
self.late_sent_at = 0.0
def batch(self, keys: list[str], idempotency_key: bool = False,
late_keys: tuple[str, ...] = (), late_after_s: float = 0.02) -> list[dict]:
"""Send ``keys`` at once; ``late_keys`` open after a short delay, unread frames.
A late request is the client's in-flight tail: a stream created while a frame was
already on its way. The client here writes the whole batch, waits ``late_after_s``
without reading a single frame, and only then opens the late streams and starts
reading - so from its side the late stream was created in ignorance of anything
the server had sent, which is the race. From the server's side the stream arrives
after the first GOAWAY was written, which is the window the handshake exists for.
"""
sock = socket.create_connection(("127.0.0.1", self.port), timeout=self.timeout)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
sock.settimeout(self.timeout)
encoder = Encoder()
decoder = Decoder()
self.frames = []
self.goaways = []
self.broken = False
self.late_sent_at = 0.0
sock.sendall(PREFACE + frame(SETTINGS, 0, 0))
streams: dict[int, dict] = {}
buffer = b""
stream_id = 1
def open_stream(key: str, late: bool = False) -> bool:
"""Write one HEADERS frame and start tracking its stream."""
nonlocal stream_id
headers = [(b":method", b"POST"), (b":path", b"/work/" + key.encode()),
(b":scheme", b"https"), (b":authority", b"loopback"),
(b"content-length", b"0")]
if idempotency_key:
headers.append((b"x-request-id", key.encode()))
if not self._send(sock, frame(HEADERS, END_HEADERS | END_STREAM, stream_id,
encoder.encode(headers))):
return False
streams[stream_id] = {"key": key, "status": 0, "done": False, "result": "",
"reset_code": 0, "started": time.perf_counter(),
"answered_at": 0.0, "after_goaway": False, "late": late}
stream_id += 2
return True
for key in keys:
if not open_stream(key):
break
if late_keys:
time.sleep(late_after_s)
self.late_sent_at = time.perf_counter()
for key in late_keys:
open_stream(key, late=True)
goaway_last: int | None = None
eof = False
while not eof:
try:
chunk = sock.recv(65536)
except (socket.timeout, TimeoutError):
break
if not chunk:
eof = True
break
buffer += chunk
while len(buffer) >= 9:
length, kind, flags, sid = parse_frame(buffer[:9])
if len(buffer) < 9 + length:
break
payload = buffer[9:9 + length]
buffer = buffer[9 + length:]
now = time.perf_counter()
self.frames.append({"kind": kind, "flags": flags, "stream": sid,
"length": length, "at": now})
if kind == SETTINGS and not flags & ACK:
self._send(sock, frame(SETTINGS, ACK, 0))
elif kind == HEADERS:
block = payload[1:] if flags & PADDED else payload
if flags & PADDED:
block = block[:len(block) - block[0]]
try:
headers = dict(decoder.decode(block, raw=True))
status = int(headers.get(b":status", b"0"))
except Exception: # noqa: BLE001 - a cut is the point
status = 0
record = streams.get(sid)
if record is not None:
record["status"] = status
if flags & END_STREAM and record is not None:
self._answered(record, now, goaway_last)
elif kind == DATA:
record = streams.get(sid)
if flags & END_STREAM and record is not None:
self._answered(record, now, goaway_last)
elif kind == RST_STREAM:
record = streams.get(sid)
if record is not None:
record["reset_code"] = int.from_bytes(payload[0:4], "big")
record["result"] = RESET
record["done"] = True
record["answered_at"] = now
elif kind == GOAWAY:
goaway_last = int.from_bytes(payload[0:4], "big") & 0x7FFFFFFF
self.goaways.append({"last_stream_id": goaway_last,
"error_code": int.from_bytes(payload[4:8], "big"),
"at": now})
elif kind == PING and not flags & ACK:
self._send(sock, frame(PING, ACK, 0, payload))
if all(record["done"] for record in streams.values()):
if self.linger_s <= 0:
eof = True
break
sock.settimeout(self.linger_s)
try:
while True:
more = sock.recv(65536)
if not more:
eof = True
break
buffer += more
while len(buffer) >= 9:
length, kind, flags, sid = parse_frame(buffer[:9])
if len(buffer) < 9 + length:
break
payload = buffer[9:9 + length]
buffer = buffer[9 + length:]
self.frames.append({"kind": kind, "flags": flags, "stream": sid,
"length": length, "at": time.perf_counter()})
if kind == SETTINGS and not flags & ACK:
self._send(sock, frame(SETTINGS, ACK, 0))
elif kind == GOAWAY:
goaway_last = int.from_bytes(payload[0:4], "big") & 0x7FFFFFFF
self.goaways.append(
{"last_stream_id": goaway_last,
"error_code": int.from_bytes(payload[4:8], "big"),
"at": time.perf_counter()})
if eof:
break
except (socket.timeout, TimeoutError, OSError):
pass
eof = True
break
ended = time.perf_counter()
try:
sock.close()
except OSError:
pass
for stream, record in streams.items():
if record["result"] == RESPONSE:
continue
if record["result"] == RESET and record["reset_code"] == 7:
record["result"] = UNPROCESSED
elif record["result"] == RESET:
record["result"] = (AMBIGUOUS if goaway_last is None or stream <= goaway_last
else UNPROCESSED)
elif goaway_last is not None and stream > goaway_last:
record["result"] = UNPROCESSED
else:
record["result"] = AMBIGUOUS
record["done"] = True
record["elapsed"] = ended - record["started"]
return [{"stream_id": stream, **record} for stream, record in streams.items()]
def _send(self, sock: socket.socket, data: bytes) -> bool:
"""Write to a connection the peer may already have closed.
A shutdown that is measured is a shutdown the peer performs while this client is
still writing: the write then fails with EPIPE or ECONNRESET. That is the event
under test, not an error, so it is reported back and the reader keeps whatever
the server wrote before it closed.
"""
try:
sock.sendall(data)
return True
except OSError:
self.broken = True
return False
@staticmethod
def _answered(record: dict, now: float, goaway_last: int | None) -> None:
if record["done"]:
return
record["result"] = RESPONSE
record["done"] = True
record["answered_at"] = now
record["elapsed"] = now - record["started"]
record["after_goaway"] = goaway_last is not None
def counts(self) -> dict:
"""Frame kinds on the wire, and how many arrived after the first GOAWAY."""
first = self.goaways[0]["at"] if self.goaways else None
kinds: dict[str, int] = {}
after = 0
for item in self.frames:
name = {DATA: "DATA", HEADERS: "HEADERS", RST_STREAM: "RST_STREAM",
SETTINGS: "SETTINGS", PING: "PING", GOAWAY: "GOAWAY",
WINDOW_UPDATE: "WINDOW_UPDATE", CONTINUATION: "CONTINUATION"}.get(
item["kind"], str(item["kind"]))
kinds[name] = kinds.get(name, 0) + 1
if first is not None and item["kind"] != GOAWAY and item["at"] > first:
after += 1
return {"kinds": kinds, "frames_after_first_goaway": after}
