A subscription flushed its state file through a package variable, which the ntfy tests replaced with a no-op in their TestMain. Tests in other packages could not reach it, so the daemon's own tests still flushed for real. Options.Sync now takes the flush; nil means (*os.File).Sync, as before. The ntfy tests pass a no-op through their options and to saveState. Behaviour is unchanged. docs/plans/ntfy.md names the option, and its line references follow the code. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
49 KiB
Plan: ntfy over WebSockets
Status: planned; nothing is built. The owner accepted every proposed default on 2026-12-01 (Decisions), and design.md's Planned next item 6 records them. Each stage runs in its own session, briefed from its section: stage 1 follows decisions 1-6, stage 2 decisions 7-13, and stage 3 decisions 14-18. The stages run in order. No stage changes what a card looks like. A check against the owner's own ntfy server, and every receipt on the live printer, needs his OK; the server's address, its topics and the printer's ntfy token stay in the session's scratchpad, never in the repository, a commit, a log, a note or a command line. Whichever stage finishes last deletes this plan, its findings with it, and design.md's Planned next item 6.
Decisions (owner, 2026-11-30)
- The subscriber uses ntfy's WebSocket endpoint (
/<topics>/ws) first and falls back to the JSON stream. The transport can also be chosen per subscription in the config. Decision 14 sets out what the WebSocket costs behind Caddy. - It handles ntfy's replay limits:
X-Messages-Truncated: 1on a replay cut at 10 MB, and429with error code42905when the daily bandwidth budget is spent. ntfy 2.38.3 sends neither to a stream, only to a poll; decision 4 says what the subscriber does. - Resuming by
since=<message ID>is checked in ntfy's source first, including what ntfy does once that ID has expired from its cache. Findings, SINCE, and decision 1. - docs/ntfy.md advises, for ntfy behind Caddy,
behind-proxy: truein ntfy and astream_close_delayin Caddy, so that Caddy's reloads do not drop streams at once. Decision 18. - There is no ntfy-compatible publish endpoint (owner, 2026-12-01).
Überbringer takes no ntfy publish requests; ntfy messages reach it
through subscriptions and the
ntfymodule route.
The owner accepted the details below on 2026-12-01. They are numbered, so the rest of the plan can refer to them.
For stage 1:
- The cursor stays a server time. Findings, SINCE. The subscriber goes on asking
since=<unix time>and never sends a message ID.- A known ID resumes right after it. That suits an ntfy cluster, whose nodes can store a message late.
- An unknown ID, one that has expired or is not yet stored on the node asked, replays the topic's whole history. The only exception is an ID that node delivered in the last two minutes (server_tail.go:70-85). The subscriber keeps seen IDs only back to two minutes before its cursor, and checks no message against its floor, so such a replay would print again what printed within
max_backlog. - A time never replays from before the floor.
- Trade-off: in an ntfy cluster, a message that a node cut off from its database stores more than two minutes late is missed. The owner's ntfy is one node.
- The cursor while a replay is under way. Today each message dealt with moves the cursor to its own time (subscriber.go:568-588). But messages do not always come in time order. ntfy subscribes a connection before it sends
openand the replay, so a message published meanwhile can come between two replayed ones. ntfy's tail and slow attachment uploads also deliver older messages late (Findings, NTFY'S STREAMS). If such a message moves the cursor and the connection then drops, or the daemon restarts, the next request starts after it. The rest of the replay is never asked for again, and is lost. On the JSON stream this needs a drop or a restart in mid-replay. On a WebSocket a full print queue is enough: the subscription stops reading, answers no ping, and ntfy closes the connection about a minute later (decision 11). So, on a connection that asked for a replay (since), no message moves the cursor until the firstkeepalive, which moves it to its own time, as today. ntfy sends keepalives only after the replay (server.go:1786-1811), so the first one marks its end. A replay cut short is then asked for again from the old cursor, and the seen IDs drop what printed. A connection withoutsincereplays nothing and moves the cursor as today. Stage 1 makes this fix on its own.- On a WebSocket, which has no keepalives, the cursor then stays put for the whole connection. The next connection replays it again, within
max_backlog(decision 12), and the seen IDs drop the repeats. - A cap at the time of
openis not enough: a replay that reaches back more than two minutes beforeopenwould still lose its rest. Nor can WebSocket pings stand in for keepalives: ntfy starts pinging before the replay (server.go:1878, 1949), a ping can come between replayed messages, and it carries no time. - Trade-off: longer replays after a reconnect, and on a WebSocket larger state writes (decision 12). Nothing more prints.
- On a WebSocket, which has no keepalives, the cursor then stays put for the whole connection. The next connection replays it again, within
- An error written into a stream. Once ntfy has begun a
200answer, a later failure is written as one more line of the body:{"code":…,"http":…,"error":…}(server.go:715-766). On a stream in 2.38.3 it followsopen, from a failed cache read; in the middle of a body it comes only on polls. Today the line decodes as a message without an event, which counts as a message (message.go:83-89), so each reconnect would print an empty card. So, on a subscription's connection, an object withouteventthat has a numerichttpfield is ntfy's error. It ends the connection as an answer with that status would, except that it has noRetry-After, since the answer's headers are gone, so a429there backs off.last_errorreads likeHTTP 500 (ntfy 50001). Nothing prints, and ntfy'serrortext stays out of logs andlast_error. Thentfymodule route is unchanged. A fix of its own, in stage 1.- Trade-off: none; only ntfy writes the stream, and its messages always have an event.
- What the replay limits mean for a stream. ntfy 2.38.3 applies both limits to
poll=1requests only (Findings, REPLAY LIMITS). So a stream never gets42905for its replay. A stream's replay over 10 MiB of one topic is cut, oldest first, withoutX-Messages-Truncated. The stream keeps its replay, and the subscriber handles the limits wherever they can appear: a429with code42905(decision 5),X-Messages-Truncated: 1on the JSON stream's answer, should a later ntfy send it beforeopen(decision 6), and an error line (decision 3). docs/ntfy.md says that a cut stream replay cannot be seen.- Trade-off: against ntfy 2.38.3, a cut replay goes unnoticed. It takes more than 10 MiB of one topic's messages within
max_backlog: some 2,500 full-size messages.
- Trade-off: against ntfy 2.38.3, a cut replay goes unnoticed. It takes more than 10 MiB of one topic's messages within
- A
429with code42905. It is a429like any other. On the JSON stream's refused answer, the reader takes ntfy's error object from the 4 KiB of body it already reads, and the subscription waits for itsRetry-After, capped at an hour (subscriber.go:42-43, 846-860), on the same transport.last_errorreadsHTTP 429: the server's daily bandwidth limit is spent (ntfy 42905), and any other ntfy code is named as(ntfy <code>). An error line backs off (decision 3). On a refused upgrade ntfy writes no body (server.go:731-745), so there only the status andRetry-Afterare known. The WARN line is today'sntfy connection lost, never with the URL. Against ntfy 2.38.3 a subscription never gets42905(decision 4); the handling is for a later ntfy.- The same code refuses an attachment download once the budget is spent (server.go:1049). The worker fetches a card's image, and an attached image is optional, so it prints as any failed optional image does. docs/ntfy.md says so.
- Trade-off: a
Retry-Afterover an hour is cut to an hour, so a spent budget can cost up to 24 refused connections a day, each a WARN line.
- A replay the server says it cut. When the JSON stream's answer carries
X-Messages-Truncated: 1, one WARN line says that the server cut the replay and older messages were lost, without the topic. Nothing prints, and/healthzdoes not change: what ntfy kept is the replay's newest part.- Trade-off: against ntfy 2.38.3 the line never appears (decision 4), and only the log would show it.
For stage 2:
- The WebSocket library. The
Dialerofgithub.com/fasthttp/websocket(v1.5.12, the latest), which docs/plans/remote-printers.md decision 5 chose for its agent. One WebSocket implementation then serves the agent and the subscriber. It is pure Go and builds withCGO_ENABLED=0. It follows no redirect, and on a refused upgrade it returns the answer's status and headers (Findings, THE WEBSOCKET LIBRARY). Its handshake watches the context only while it dials, so the dial function the subscriber gives it closes the connection once the connection's context ends, from the dial on: a stop never waits for a slow handshake. If remote-printers stage 2 has not brought the library, stage 2 here adds it at its latest release, with the licence notices regenerated.- Trade-off: no release since 2025-01-01, as remote-printers.md notes, and a fault there reaches both ends. Its
Conntakes no context, so a blocked read ends only when the connection is closed.
- Trade-off: no release since 2025-01-01, as remote-printers.md notes, and a fault there reaches both ends. Its
- The WebSocket request.
wss://, orws://withallow_insecure, to<server>/<topics>/ws, with the stream's query from the same builder:sinceand, while it is sent,priority. The credentials go in theAuthorizationheader, as on the stream; never in?auth=, which ntfy also reads (server_auth.go:65-78), because tokens in query strings end up in proxy logs (design.md:262-263). The request sendsUser-Agent: uberbringer, noOrigin, no subprotocol and no compression. The dial keeps the stream's limits: 10 s to connect, 30-s TCP keepalives, the proxy from the environment, and 30 s for the whole handshake. A3xxis a failed connection with today's message (subscriber.go:773-775).- Trade-off: the library takes
httpand SOCKS5 proxies but not anhttpsone, which the stream takes (Findings, THE WEBSOCKET LIBRARY). Decision 15 counts that as a refusal, soautouses the stream.
- Trade-off: the library takes
- Pings, the clock and stalls. ntfy pings a WebSocket every keepalive interval, 45 s by default, and closes it when no pong comes within that interval plus 15 s (server.go:1856-1904).
- The reader answers each ping at once with a pong, with a 1-s write deadline as the library's own handler has, and sends no pings of its own.
- Each ping then gives the loop a
pingevent, sent as every event is, so a stop frees the reader (subscriber.go:978-986). It resets the stall timer as a keepalive does: a connection with no message and no ping for twicekeepaliveplus 15 s is opened again. A ping never moves the cursor. - No read deadline is set on the socket; the loop's stall timer closes it, as it closes a stream (subscriber.go:384-387).
- A WebSocket learns the server's clock from
openalone. ntfy's101answer has noDate, and one a proxy adds is the proxy's clock (design.md:337-339). Anopenwithout a time ends the connection as a protocol error (decision 15). keepalivekeeps its meaning, the server's keepalive interval, which ntfy also pings at.- Trade-off: a dead connection is found only after twice
keepaliveplus 15 s, 105 s by default, as on the stream.
- Message size. As on the stream, a message over 1 MiB is read to its end and skipped, with today's WARN (
ntfy line skipped,longer than 1 MiB), and the connection stays open. The reader takes each frame throughNextReaderinto at most 1 MiB and discards the rest, so a frame costs no more memory than a line. A binary frame is skipped as a line that is not JSON. ntfy's own limits keep a message far smaller: a 4,096-byte body, a 1,024-byte title and 512 bytes of tags (config.go:78, 93-94). The library'sSetReadLimitis not used: it ends the connection, the next replay would send the message again, and a subscription withtransport = "websocket"would never get past it.- Trade-off: a hostile server can still keep the subscriber reading, as on the stream.
- A full print queue on a WebSocket. While the handler cannot take a message, the loop stops reading (design.md:312-317), so the reader answers no ping. Nothing special is done. ntfy closes the connection about a minute later. The reader's last events wait until the queue has room; then the subscription reconnects after the usual backoff, and decision 2 keeps the cursor behind what it has not dealt with. The JSON stream stays open through such a pause, held by TCP backpressure, since ntfy's HTTP server has no write timeout (server.go:509).
- Trade-off: one reconnect, with its replay, after each pause longer than about a minute. docs/ntfy.md says so.
max_backlogwhile connected. With decision 2, a WebSocket's cursor stays put, and the seen IDs are kept from two minutes before the cursor (state.go:179-192). On a long connection they would grow to the 20,000 cap. So, at each save, while the connection knows the server's clock, the floor rises to the server's time now lessmax_backlog, computed ascheckBacklogcomputes it (subscriber.go:596-608). The raised floor bounds the next replay and the seen IDs, and nothing else: a message on the current connection is not checked against it, so one held in a JSON stream through a long printer outage still prints, as today. It applies to both transports; on the stream, whose keepalives move the cursor, it rarely changes anything.- Trade-off: on a WebSocket every save writes the IDs within
max_backlog, about 60 an hour at a message a minute. A busy topic with a 12-hourmax_backlogcan reach the 20,000 cap, some 700 KB written and synced within a second of each message. The stream writes about two minutes' worth.
- Trade-off: on a WebSocket every save writes the IDs within
- The config key and the Go field.
transportper subscription,"websocket"or"json", written exactly so. Its default is"json"in stage 2, so a build between stages 2 and 3 behaves as today unless a subscription asks; stage 3 adds"auto"and makes it the default (decisions 14 and 15). In Go,ntfy.Options.Transporttakes this meaning, and today's field of that name, the stream'shttp.RoundTripper, becomesRoundTripperin stage 2's first commit.- Trade-off: the default changes again in stage 3, so a build between the two stages differs from the release.
For stage 3:
-
WebSockets come first. The owner keeps the WebSocket first, and
autois the default from stage 3. Behind Caddy, the findings show the JSON stream as good or better on each count this plan examines; these are the costs he accepts:- Replays: with decision 2, a WebSocket's cursor does not move during a connection, so each reconnect replays up to
max_backlogof messages, where the stream replays about two minutes. - Pauses: a full queue for more than about a minute closes a WebSocket (decision 11); the stream stays open.
- Reloads: a Caddy reload closes every WebSocket, at once or after
stream_close_delay; it leaves the stream open under Caddy's default grace period (decision 18). - Code: a second transport, and a library without a release since 2025-01-01.
The usual reason for WebSockets, a proxy that buffers a streamed answer, does not hold for Caddy, which flushes ntfy's stream at once.
transport = "json"keeps a subscription on the stream. - Replays: with decision 2, a WebSocket's cursor does not move during a connection, so each reconnect replays up to
-
auto, and what counts as a refusal.transport = "auto"tries the WebSocket and falls back to the JSON stream when the answer shows that the server, or a proxy in front of it, does not take WebSockets:- the upgrade is answered with a status other than
101that is not a3xx,401,403,408,429or5xx. ntfy answers400with code40016when a proxy dropped theUpgradeheader (server.go:1817-1819), and an old server or a proxy without the path answers404; - the library refuses a
101answer (ErrBadHandshakewith a101, or a compression it did not offer); - an open WebSocket breaks the protocol: one of the library's
websocket:errors that is neither a*CloseError, anet.Errornor end of file; - an
openwithout a time (decision 9); - a proxy setting the library cannot use, such as an
httpsproxy (decision 8); - three connections in a row closed after the
101and beforeopen. ntfy writesopenright after the upgrade (server.go:1943-1948), so this marks a broken tunnel while the server itself is up.
Every other failure keeps the transport and backs off as today, since the stream would fail the same way: a dial or TLS error, a timeout, a
3xx,401or403, a429, a5xx, a stall, and a close. ntfy closes a WebSocket without a close frame, which reads as code 1006, and Caddy's reload sends 1001; both are closes. The fallback connects at once, without a backoff step, since the refusal said nothing about the server's health.- Trade-off: a proxy that keeps the tunnel open past
openand breaks it later shows as repeated drops, not as a refusal, soautostays on the WebSocket.transport = "json"is the cure, and docs/ntfy.md says so.
- the upgrade is answered with a status other than
-
How long a fallback lasts. A subscription that fell back uses the JSON stream for at least an hour. It tries the WebSocket again on its first reconnect after that, never by dropping a working stream. A restart tries the WebSocket first, since the fallback is not saved. One INFO line says that the subscription falls back, with the status and never the URL, and one says when the WebSocket works again.
- Trade-off: at most one refused upgrade an hour, and one per restart.
-
/healthz. Each subscription gainstransport,websocketorjson, the one its current or last connection uses. A fallback is not an error, solast_errorkeeps its meaning.- Trade-off: a field kept in the API for good.
-
Caddy and ntfy settings in docs/ntfy.md. A section, ntfy behind Caddy, advises:
- in ntfy's
server.yml,behind-proxy: true. ntfy then tells clients apart by theX-Forwarded-Forheader Caddy sets, instead of counting every client, the printer among them, as Caddy's one address in its rate limits; - in the
reverse_proxyof ntfy's site,stream_close_delay 5m. A reload otherwise closes every proxied WebSocket at once. With it, a WebSocket stays open for up to five minutes after a reload, and then closes; the delay moves the reconnect later and spreads the reconnects of many clients, but does not avoid it; - that the JSON stream is a plain answer, which a reload leaves open until it ends, unless Caddy's global
grace_periodis set; it then closes when that period ends; - no
response_bufferson ntfy's site: Caddy then refuses an answer that carriesIncremental: ?1, as ntfy's stream does, with501(Findings, CADDY). Noflush_intervalis needed, since Caddy flushes such an answer at once; - that the subscription loses nothing to a reload either way, since it resumes from its cursor;
- that a proxy that cannot pass WebSockets makes
autofall back, and thattransport = "json"avoids the refused upgrade. - Trade-off: the advice covers Caddy only. For other proxies it points to ntfy's docs.
- in ntfy's
Investigation findings
Read on 2026-12-01, offline from cloned sources: ntfy at tag v2.38.3 (commit 5dc000a5, 2026-11-27, its latest release; main at f2a23b1d changes nothing in server/, message/ or model/), Caddy at v2.11.9 (commit 0d98caea) with its documentation (caddyserver/website at fef9d0c2), and fasthttp/websocket v1.5.12 and Fiber v3.7.0 from the module cache. No ntfy server was contacted, and no config.toml was read. ntfy line numbers below are at v2.38.3; the subscriber's are at c778c3f.
NTFY'S STREAMS
- One handler serves
/json,/sseand/raw(server/server.go:1691-1814), and/wshas its own (1816-1955). Both subscribe the connection to its topics, check its access, sendopen, then the replay, then live messages. One lock orders the writes, so a message published during the replay can come between two replayed ones. The replay of several topics is sorted by time, keeping each topic's order (2071-2075). - Messages do not always come in time order. ntfy dates a message when its request arrives (1123), sends it to subscribers (1196) and only then stores it (1225), so an attachment upload delays a message dated earlier. ntfy's tail sends a connection the stored messages it has not had, which includes messages published while it was being opened (server_tail.go:21-56; topic.go:139-192, in particular 155-162).
- The JSON stream sends a
keepaliveobject every keepalive interval (45 s by default, config.go:25), and only once the replay is written (1786-1811). Its answer carriesIncremental: ?1(1765). ntfy's HTTP server has no write timeout (509). - A WebSocket gets one JSON text frame per object, written with
WriteJSON(msg)(1909-1918), sosequence_idis always there; the stream leaves it out when it equalsid(model/model.go:95-102). Neither changesSequence()(message.go:93-98). - A WebSocket gets no
keepaliveobjects. ntfy starts pinging it every keepalive interval before the replay (1878-1904, 1949). It reads with a 64-byte limit, since it expects only pongs, and a deadline of the keepalive interval plus 15 s that each pong renews (1856-1871). Every write has a 2-s deadline (195-198). A client that stops reading for about a minute is closed. ntfy closes the socket without a close frame (1847, 1894). - ntfy's
101answer has noDate: the upgrade writes it without one, and ntfy passes no headers (1843). open,message,message_delete,message_clearandpoll_requestcome the same way on both. A delete or clear is stored like a message, so a replay sends it too; a delete removes only the scheduled, unsent messages of its sequence (1270-1330).- A WebSocket request without the
Upgradeheader gets400with code40016(1817-1819; errors.go:134). A refused upgrade otherwise gets its status, and itsRetry-Afterwhere there is one, but no body (724-745). - A draining node of an ntfy cluster answers new streams
503with code50301before the upgrade, and closes its streams a few at a time; its clients are expected to resume withsince(server_drain.go). A single node never drains.
REPLAY LIMITS
- A replay holds at most 10 MiB of
Message.Size()per topic, which counts the publisher's fields (model/model.go:104-120; server/config.go:85-88). It is not a setting. The newest messages that fit are kept, at least one, and ntfy learns that older ones were left out (message/cache.go:240-257, 650-683). Release notes: docs/releases.md:386. X-Messages-Truncated: 1is set just before the replay's first message is written (server.go:2077-2081). On the JSON stream,openwent out before it, so the header is not sent. On a WebSocket the answer was hijacked, and the source says so. Only apoll=1answer, which has noopen, carries it (1758-1764).- A replay's bytes count against the visitor's daily bandwidth budget, the one attachment downloads use, on a
poll=1request only (1708-1713, 1730-1739, 1762). Each message is charged before it is written, so a budget spent at the first message gives a clean429, and one spent later ends a200answer with an error line (ERRORS IN A BODY). The code is42905,limit reached: daily bandwidth reached(errors.go:210).Retry-Aftercomes from the budget's bucket, which refills over a day (visitor.go:363-372; errors.go:21, 94; server.go:724-729). The default budget is 500 MB (config.go:117), and a budget of 0 admits nothing (visitor.go:249-252). - ntfy's docs say both limits apply to "a poll=1 request, or any request with since=" (docs/subscribe/api.md, Replay limits). At v2.38.3 the code applies them to polls only.
- An attachment download,
GET /file/…, is refused with the same code once the budget is spent (server.go:1049).
SINCE
sincetakes nothing (no replay on a stream, everything on a poll),all,latest,none, a message ID, Unix seconds, or a duration (server.go:2094-2119).- A time replays
time >= sinceamong published messages, newest first, then reversed (message/cache_sqlite.go:35-40). - An ID is looked up once, on the read replica and then the primary (message/cache.go:279-286, 323-345). If it is known, the replay holds the rows written after it, and those dated in its second or later that were written before it, for nodes that write late; some come twice, and "clients drop duplicates by id" (cache.go:288-316; cache_sqlite.go:60-69).
- An ID that is not known, because it expired or is not yet written, gives the topic's whole retained history, up to the cache duration (12 h by default, config.go:23) and the 10-MiB cap. The exception is an ID this node delivered in the last two minutes: the replay then starts two seconds before that delivery (server_tail.go:17, 70-85; topic.go:24, 87-93).
- A delete leaves published messages in the cache (server.go:1270-1330), so an ID stays known until it expires.
ERRORS IN A BODY
- ntfy's error handler sets the status and writes
{"code":…,"http":…,"error":…,"link":…}and a newline (server.go:715-766; errors.go:14-22, wherecodemay be absent andhttpnever is). Once a200answer has begun, the status cannot change, so the object becomes the body's last line. On a stream in 2.38.3 it can only followopen, since the replay is read in full before its first write (2044-2087) and streams are not charged. After an upgrade it writes nothing (738-745).
AUTHENTICATION
- ntfy reads the
Authorizationheader, or?auth=or?authorization=holding the header's value in base64url, the query winning (server_auth.go:65-78). Basic authentication with an empty user makes the password a token (88-97).
CADDY
- reverse_proxy's
stream_close_delayandstream_timeout: by default a reload closes every WebSocket, with a close message to both ends; the docs suggest5mas a delay. The close code is 1001 (streaming.go:513-526). - Both act on hijacked connections only, the WebSockets: modules/caddyhttp/reverseproxy/streaming.go:214-215 and 428-500. A plain streaming answer is an active request, which a reload's shutdown waits for until
grace_periodends, and that period is eternal by default (modules/caddyhttp/app.go:137-143, 754-768). flush_intervalis ignored, and each write is flushed at once, when an answer carriesIncremental: ?1or its length is unknown. Withresponse_buffersset, Caddy 2.11.7 and later refuse an answer that carriesIncremental: ?1with501(reverseproxy.go:1335-1339).- ntfy's docs:
behind-proxymakes ntfy read the client's address fromproxy-forwarded-header,X-Forwarded-Forby default, which Caddy'sreverse_proxysets. ntfy's own Caddy example redirects plain-HTTPGETs of topic paths (docs/config.md:1568-1583); the subscriber never follows a redirect.
THE WEBSOCKET LIBRARY
- fasthttp/websocket v1.5.12, client.go: the
DialertakesNetDialContext,NetDialTLSContext,ProxyandHandshakeTimeout(58-81; 45 s in its default dialer, 142).DialContext(159) takeswsandwssURLs only, refuses user info (175-185), and sends one request. It watches the context while it dials and does the TLS handshake (298, 333), and only as a socket deadline after that (262-276, 345-355). An answer other than a valid101returnsErrBadHandshakewith the answer and its first 1,024 bytes (377-388). - Proxies:
httpthroughCONNECT, and whatever golang.org/x/net/proxy knows, such assocks5(proxy.go:31-45). Anhttpsproxy URL fails. - conn.go:
SetReadLimit(1191) ends the connection when a message passes it;SetPingHandler(1250), whose handler runs insideNextReaderon the reading goroutine;WriteControl(442) may run beside a writer. Protocol errors are plainwebsocket: …errors; a socket closed without a close frame reads as*CloseError1006. Nothing takes a context. - Latest versions on proxy.golang.org on 2026-12-01: fasthttp/websocket v1.5.12 (2025-01-01), coder/websocket v1.8.15 (2026-06-15), gorilla/websocket v1.5.3 (2024-06-14), gofiber/contrib/v3/websocket v1.3.1 (2026-11-25).
THE SUBSCRIBER TODAY
- One goroutine reads each connection and hands the loop events (subscriber.go:870-893, 932-976, 978-986). The loop owns all state and stops reading while a message waits (342-364).
- The clock:
open's time first, then the answer'sDate, measured on the monotonic clock, afresh for each connection (461-478, 593-616, 924-928). A keepalive moves the cursor and never sets the clock (479-481). sinceis the cursor less two minutes, never before the floor and never clamped by the host's clock (619-621, 663-674).max_backlogis applied by the server's clock as messages arrive (484-487, 604-616).- The seen IDs: those a replay could send, at least the last 512, at most 20,000; the floor rises past the ones the cap forgets (state.go:14-20, 154-192; subscriber.go:565-576).
- Redirects are never followed (228-234, 781-783). Errors leave out the URL (843-852).
- Saves: within
saveEvery(1 s) for a change a restart must see, withincursorSaveEvery(10 min) for a cursor that alone moved, and at once for the first move from 0 (51-58, 393-402, 581-588). Tests skip the sync throughOptions.Sync(137-139). - Tests: the synctest fake answers through
RoundTrip(fake_test.go:21-139); replays (replay_test.go), redirects over real sockets (redirect_test.go), goroutines over real sockets (leak_test.go) and a 24-hour soak (soak_test.go).
WHERE THIS IS UNSURE
- Whether net/http's server, upgraded by fasthttp/websocket over
net.Pipeconnections, runs inside atesting/synctestbubble. Stage 2 checks it before it builds the fake on it. - Whether a later ntfy sends
X-Messages-Truncatedor charges bandwidth on streams, as its docs say. Decisions 5 and 6 cover both if it does. - How often the owner's Caddy reloads, which decides how much decision 18's delay matters.
SOURCES
- ntfy, tag v2.38.3: https://github.com/binwiederhier/ntfy/tree/v2.38.3, chiefly server/server.go, server/server_auth.go, server/server_tail.go, server/server_drain.go, server/errors.go, server/visitor.go, server/topic.go, server/config.go, message/cache.go, message/cache_sqlite.go and model/model.go.
- ntfy's docs: https://docs.ntfy.sh/subscribe/api/ (WebSockets, Replay limits) and https://docs.ntfy.sh/config/#behind-a-proxy-tls-etc.
- Caddy v2.11.9: https://github.com/caddyserver/caddy/blob/v2.11.9/modules/caddyhttp/reverseproxy/streaming.go, https://github.com/caddyserver/caddy/blob/v2.11.9/modules/caddyhttp/reverseproxy/reverseproxy.go and https://github.com/caddyserver/caddy/blob/v2.11.9/modules/caddyhttp/app.go.
- Caddy's docs: https://caddyserver.com/docs/caddyfile/directives/reverse_proxy (
stream_close_delay,flush_interval,response_buffers, Headers) and https://caddyserver.com/docs/caddyfile/options#grace-period. - fasthttp/websocket v1.5.12: https://github.com/fasthttp/websocket/blob/v1.5.12/client.go, proxy.go and conn.go.
- Module versions: https://proxy.golang.org/github.com/fasthttp/websocket/@latest, and the same for the other three.
Overview
WHAT SHIPS WHEN
- Stage 1: today's subscriber, made safe for any transport. No message moves the cursor during a replay, an error ntfy writes into a stream prints nothing, and ntfy's replay limits are named where they can appear.
- Stage 2:
transport = "websocket"reads the topics over ntfy's/ws;"json", the default for now, is today's stream. The floor followsmax_backlogwhile connected. - Stage 3:
auto, the default, tries the WebSocket and falls back to the stream./healthzshows each subscription's transport. docs/ntfy.md advises on ntfy behind Caddy.
COMPATIBILITY
- Nothing breaks. From stage 3, a subscription without
transportuses WebSockets first.transport = "json"keeps today's stream. /healthzgainstransport; no field changes meaning.- The state file keeps its version 1 and its fields; an older binary reads it. An older binary refuses
transportas an unknown key. - What prints does not change. TestRenderCompat and TestPaperReceipts keep passing.
- The subscriptions are not yet in a release (CHANGELOG.md
[Unreleased]). So each stage edits their[Unreleased]entry rather than adding Changed or Fixed entries, unless a release has shipped them by then.
INVARIANTS
- Both transports hand the loop the same events, and the loop's rules do not depend on the transport. A WebSocket adds
ping, which only resets the stall timer. - Each connection learns the server's clock afresh, measured on the monotonic clock: on the stream from
open's time, then the answer'sDate; on a WebSocket fromopenalone. sinceis the cursor less two minutes, never before the floor, never clamped by the host's clock, and never a message ID.max_backlogapplies by the server's clock.- The cursor moves past a message only once it is queued, held or deliberately left out. On a connection that asked for a replay, no message moves it before the first keepalive. A ping never moves it.
- The seen IDs hold at least the last 512 and at most 20,000, and the floor rises past the ones the cap forgets.
- Redirects are never followed, on either transport.
- A change a restart must see is saved within a second; a cursor that alone moved, within ten minutes; the first move from 0, at once. Tests skip the sync through
Options.Sync. - Credentials go only in the
Authorizationheader. No URL, topic, token or message text reaches a log,last_erroror Sentry. - ntfy never imports modules.
OTHER PLANS
- docs/plans/job-store.md phase 2b drops
priority=fromconnect(its decision 18). Both transports build their query with one function, so whichever lands second keeps that. Amessage_deletereachesdeliverthe same way on both. - docs/plans/templates.md stages 2 and 3 change
deliver, which both transports reach the same way. - docs/plans/remote-printers.md shares fasthttp/websocket (its decision 5). Its
stream_close_delayis for Überbringer's own Caddy site; this plan's is for the ntfy server's.
Architecture
TRANSPORTS (stages 1-3)
- Today's reader,
conn.read(subscriber.go:932-976), becomes one of two readers, chosen per connection: the stream's, unchanged, and the WebSocket's. Both send the loop the same events:openedwith the answer'sDate,msg,skipped, andendwith the status,Retry-Afterand ntfy's code. The WebSocket's addsping, and itsendsays whether the WebSocket was refused, forauto. - One function builds the query,
sinceandpriority, for both. The WebSocket URL swaps the scheme (httpstowss,httptows) and the last path part (/jsonto/ws). Options.Transportnames the transport (decision 13), andOptions.DialContext(name assumed) the WebSocket's dial function, which tests replace.
THE WEBSOCKET READER (stage 2)
d := websocket.Dialer{
NetDialContext: dial, // net.Dialer{Timeout: 10s, KeepAlive: 30s}; closes its conn when ctx ends
Proxy: http.ProxyFromEnvironment,
HandshakeTimeout: 30 * time.Second,
}
ws, resp, err := d.DialContext(ctx, wsURL, header) // Authorization and User-Agent only
dialdials, then ties the connection to the connection's context withcontext.AfterFunc, so a stop closes it during the handshake too. The same tie later frees a blocked read.- An answer other than
101ends the connection with its status andRetry-After. An error without an answer ends it with the error. - On
101: anopenedevent, without aDate. A ping handler writes the pong, then sendspingthroughconn.send. - Each frame is read through
NextReader: text up to 1 MiB is decoded as a message, longer text is drained and skipped, and a binary frame is skipped. The first message must beopenwith a time. A close or a read error ends the connection;describenames a close code without the URL. - Stopping sends a close frame with code 1000 under a 1-s deadline, then closes the socket.
THE CURSOR (stages 1 and 2)
- A connection keeps whether it asked for a replay and whether a keepalive has come. Before that keepalive,
dealtrecords a message in the seen IDs and the state, and leaves the cursor where it is (decision 2). saveraises the floor to the server's time lessmax_backlogwhile a connection knows the clock (decision 12), before it prunes the seen IDs.
FALLBACK (stage 3)
- The run keeps the time until which
autouses the stream, and how many WebSockets in a row closed beforeopen.connectpicks the WebSocket forwebsocket, the stream forjson, and forautothe WebSocket unless that time is still ahead. A refusal (decision 15) underautosets it an hour ahead and connects again at once. StatusgainsTransport, set when a connection starts.
"ntfy": [{"name": "home", "state": "connected", "transport": "websocket", "connected_since": "2026-12-01T20:58:01Z",
"last_message_at": "2026-12-01T21:04:05Z", "printed": 12, "digested": 2, "held": 0, "last_error": ""}]
CONFIG
[[ntfy.subscriptions]]
name = "home"
server = "https://ntfy.example.com"
topics = ["alerts"]
token_file = "/etc/uberbringer/ntfy.token"
# "auto" (the default) tries a WebSocket and falls back to the JSON stream;
# "websocket" and "json" use one only.
transport = "auto"
Phases
Every commit below that changes behaviour carries its own tests, docs, regenerated docs/swagger.json where a type changes, and CHANGELOG edit as COMPATIBILITY says. A stage's last commit marks the stage built in this plan's Status. The ntfy package's go test -race time is recorded in the body of each commit that adds subscriber tests, and stays well inside the five-minute timeout.
Stage 1: The cursor, errors and replay limits
Goal. Today's subscriber, on the JSON stream: no message moves the cursor during a replay, an error ntfy writes into a stream prints nothing, ntfy's error codes are named, and a replay the server says it cut is logged. Decisions 1-6.
Work.
internal/pkg/ntfy
- subscriber.go:
connkeeps whether a keepalive has come;dealtleaves the cursor alone on a connection withsinceuntil then (decision 2). A first start, withoutsince, is unchanged.- An object without
eventand with a numerichttpends the connection as that status would, with noRetry-After(decision 3). readtakes ntfy's error object from a refused answer's body, and notesX-Messages-Truncated: 1on an accepted one (decisions 5 and 6).eventgains ntfy's code;reconnectnames it as(ntfy <code>), and words42905, never with ntfy's text.- The loop logs a cut replay at WARN, without the topic.
- message.go: the error object's type.
Docs
- docs/ntfy.md, How a subscription behaves: a reconnect asks again for what a replay had not sent; an error from the server ends the connection and prints nothing; the replay limits, that a stream's cut replay cannot be seen against ntfy 2.38.3, and that
42905also refuses an attachment, which then prints as a failed optional image. - docs/configuration.md, Logs: the WARN line for a cut replay.
- docs/api.md, Health:
last_errorcan name ntfy's code. - design.md, the ntfy subscriptions paragraph: the cursor during a replay; errors in a stream; the replay limits.
- CHANGELOG: the
[Unreleased]subscriptions entry, where it says how a replay resumes.
Tests.
internal/pkg/ntfy, on the virtual clock
- The fake can hold a replay after a number of messages, send a live message, or an older one late as ntfy's tail does, inside it, and drop the connection there.
- A replay of ten messages dated 10 to 50 minutes before
open, with a live message after the third, dropped after the live one: the next request'ssincereaches back to the old cursor, and every message prints once. - The same with an older message delivered late instead of a live one, with two topics interleaved, and with a restart instead of a drop while a message waits on a full queue.
- The first keepalive moves the cursor to its time.
- A connection without
sinceis not held: TestFirstStartSendsNoSince and TestKeepalivesSaveTheCursorLazily pass unchanged. - An error line right after
open, and one in the middle of a replay: nothing prints,last_errorisHTTP 500 (ntfy 50001), the subscription backs off, and no log line holds ntfy's text. An error line with429backs off without waiting for aRetry-After. - A refused answer
429with code42905andRetry-After: 90:last_errorreads as decision 5 says, and the subscription waits 90 s. - An answer with
X-Messages-Truncated: 1: one WARN line without the topic, and every message of the replay printed. - The soak sends live and late messages inside replays and drops some replays half-way; every message still prints once.
Commits.
- Keep the ntfy cursor still until a replay has finished
- End an ntfy connection on an error written into its stream
- Name ntfy's error code when a subscription is refused
- Log the ntfy replays the server cut short
Done when.
- The full gate passes.
Stage 2: The WebSocket transport
Goal. transport = "websocket" reads a subscription's topics over ntfy's /ws, with today's rules; "json", the default for now, keeps the stream. The floor follows max_backlog while connected. Decisions 7-13. Needs stage 1.
Work.
internal/pkg/ntfy
- transport.go (new; name assumed): the reader seam, with the stream's reader moved there unchanged, and the query builder both use.
Options.TransportbecomesOptions.RoundTripper(decision 13). - websocket.go (new; name assumed): the dial function, the dialer and the reader (Architecture, THE WEBSOCKET READER; decisions 7-11).
- subscriber.go:
OptionsgainsTransportandDialContext;connectpicks the reader;eventtakesping, which only resets the stall timer;- on a WebSocket, the clock comes from
openalone (decision 9); saveraises the floor (decision 12);describenames a WebSocket close code.
- doc comments:
Keepaliveis also the ping interval; the package comment names both transports.
internal/pkg/config
transportper subscription:websocketorjson, defaultjson; any other value refused, naming the key.
internal/app/uberbringer
- ntfy.go: passes
transporton.
go.mod
github.com/fasthttp/websocketat its latest stable release, in commit 3, unless remote-printers has added it.go generate ./...regenerates THIRD-PARTY-LICENSES.md andlicenses_embed.mdin that commit, and govulncheck runs.
Docs
- docs/configuration.md, § ntfy subscriptions:
transport;keepaliveis also the ping interval. - configs/config.example.toml:
transport, commented. - docs/ntfy.md, How a subscription behaves: the transports; a WebSocket's pings; a full queue closes a WebSocket after about a minute, and the subscription reconnects once the queue has room.
- docs/security.md, What is never logged: the credentials go in the
Authorizationheader on both transports, never in a URL. - design.md, the ntfy subscriptions paragraph: two transports, pings, the WebSocket's clock, and the floor while connected.
- CHANGELOG: the
[Unreleased]subscriptions entry gainstransport.
Tests.
internal/pkg/ntfy, on the virtual clock
- First, a probe: net/http's server, upgraded by fasthttp/websocket over an in-memory listener of
net.Pipeconnections, runs inside a bubble. If it does not, the fake writes WebSocket frames itself. - The fake serves
/wswith the stream's logic:open, the replay sincesince, then live messages; a ping every keepalive interval, from before the replay, instead of keepalive objects; a connection closed without a close frame when no pong comes within the interval plus 15 s; refusals with a status andRetry-Afterand no body. - With
max_backlogof one minute on the stream, the saved floor follows the server's clock while connected, and a message held through an outage longer than that still prints (commit 2). - The behaviour tests of subscriber_test.go and replay_test.go run on both transports. Those about keepalives get WebSocket counterparts: pings keep a quiet connection open; no ping and no message for twice
keepaliveplus 15 s reconnects; a ping never moves the cursor. - On a WebSocket the cursor stays put during a connection, and a reconnect prints nothing twice.
- A queue full for five minutes on a WebSocket: the fake closes the connection after about a minute; once the queue has room the subscription reconnects once, and every message prints once.
- A 1.5-MiB text frame and a binary frame are skipped, and the connection stays open.
- The upgrade carries
Authorization(bearer, and Basic) andUser-Agent, noOriginand noauthparameter; its query equals the stream's. - Refused upgrades:
401and403giveunauthorized;429waits forRetry-After;5xxbacks off. - A server that takes the connection and never answers the upgrade: a stop returns within a second. A stop while the reader sits in the ping handler returns too.
- An
openwithout a time ends the connection; aDateon the101is not used. - A WebSocket open for three hours, with a message a minute and
max_backlogof an hour: the saved seen IDs never hold more than the last hour's beyond the last 512, and the nextsinceis within the hour. - The soak runs once on each transport.
- TestLogsCarryNoText runs on a WebSocket too: no topic, token or text in a log line or
last_error.
internal/pkg/ntfy, over real sockets
- TestNoGoroutineLeakOverRealConnections gains a WebSocket run: an httptest server with the upgrader that drops connections, answers
502and keeps the last one open; the goroutine count comes back. - TestRedirectsAreNotFollowed gains a WebSocket case: the upgrade is answered with a redirect to the raw listener, which gets no connection.
internal/pkg/config
transportdefaults tojson, takes both values, and refuses another.
Commits.
- Read the ntfy stream through a transport seam
- Let the ntfy floor follow max_backlog while connected
- Read ntfy topics over a WebSocket
- Choose the ntfy transport per subscription
Commit 1 changes no behaviour: the existing tests pass unchanged, and it has no docs or CHANGELOG edit. Commit 3 is the library code, the fake and the tests above but the config's; nothing reaches it from the config until commit 4, which adds the key, the wiring and the docs. If commit 3 passes about 800 changed lines, the fake and its probe go first, in a commit of their own with the stream tests moved onto it.
Done when.
- The full gate passes, govulncheck included.
- With the owner's OK, against his own ntfy server, with the config and the token file in the scratchpad: a subscription with
transport = "websocket"connects, and/healthzshows it connected. He publishes one short message from his own client, which prints once: look at the card's title, text and tags as he sent them, and the cut. A restart replays nothing twice. Wait for his report.
Stage 3: WebSockets first, with a fallback
Goal. auto tries the WebSocket and falls back to the JSON stream when the WebSocket is refused, and becomes the default. /healthz shows each subscription's transport. docs/ntfy.md advises on ntfy behind Caddy. Decisions 14-18. Needs stage 2.
Work.
internal/pkg/ntfy
- subscriber.go: the refusals that make
autofall back (decision 15); the fallback's hour and the INFO lines (decision 16);Status.Transport.
internal/pkg/config
transporttakesauto(commit 1), the default from commit 2.
server and internal/app/uberbringer
- server/handlers.go:
NtfyHealth.Transport, with its enum tag; the app maps it. docs/swagger.json regenerated.
Docs
- docs/configuration.md and configs/config.example.toml:
auto, then the default. - docs/configuration.md, Logs: the INFO lines for a fallback and for the WebSocket working again.
- docs/ntfy.md: the fallback, and when to set
json; a section, ntfy behind Caddy (decision 18). - docs/api.md, Health:
transportin the example and the table. - design.md, the ntfy subscriptions paragraph: WebSockets first, the fallback.
- CHANGELOG: the
[Unreleased]subscriptions entry says that subscriptions use WebSockets first and that/healthzshows the transport. The commit that only adds docs has no edit.
Tests.
internal/pkg/ntfy, on the virtual clock
/wsanswered400, as behind a proxy that dropsUpgrade: the stream opens at once, without a backoff wait;Status.Transportisjson; one INFO line. A reconnect within the hour stays on the stream; the first after it tries the WebSocket.404, a101the library refuses, a protocol error on an open WebSocket, anopenwithout a time, anhttpsproxy, and three connections in a row closed beforeopeneach fall back.401,403,429,503, a dial error, a stall, an ntfy-style close (1006) and a Caddy-style close (1001) do not.websocketnever falls back, andjsonnever asks for/ws; the fake counts the requests.- A restart tries the WebSocket first.
- The soak runs with the fake refusing WebSockets for a stretch of the day.
server
- TestHealthListsSubscriptions (health_ntfy_test.go:24) shows
transport; a test beside TestNtfyStateEnumListsEveryState (health_ntfy_test.go:71) holds thetransportenum to the values the app sends.
Commits.
- Fall back to the ntfy JSON stream when a WebSocket is refused
- Subscribe to ntfy over WebSockets by default
- Show each ntfy subscription's transport in /healthz
- Document ntfy behind Caddy
Commit 1 adds auto as a value, with its config docs; commit 2 makes it the default.
Done when.
- The full gate passes.
- With the owner's OK, against his own ntfy server: a subscription without
transportconnects over a WebSocket. Withstream_close_delay 5mset, after a Caddy reload done by the owner,connected_sincestays unchanged for up to five minutes; then the subscription reconnects once. Without it, it reconnects at once. Either way he publishes one short message after the reload, which prints once: look at the card as in stage 2. Wait for his report.