Mrs. Rini's order board is up on the shop's TV, and it uses hx-trigger="every 30s". Mrs. Rini changes #12 to Ironing, but the TV only follows 26 seconds later. The customer waiting in front of it has already gone to ask the cashier.
Polling asks again and again, "anything new?". SSE (Server-Sent Events) turns that around: the browser opens one connection that stays open, and the server pushes news through it the moment something changes. WebSocket is one open connection too, but two-way: the browser and the server can both send at any time. Mrs. Rini's Laundry customers come in the same three kinds. Polling is the customer who phones every 30 minutes, "is my laundry done?". SSE is the customer subscribed to Mrs. Rini's messages, which arrive right when the status changes. WebSocket is a phone call left connected, where both sides can talk.
An SSE stream: one connection, many messages
The browser asks for GET /board/stream and the server replies with Content-Type: text/event-stream without closing the connection. Every time something changes, the server writes one message:
id: 1
event: order-12
data: <li id="order-12" sse-swap="order-12" hx-swap="outerHTML">#12 Mr. Darto, 3 kg: <span>Ironing</span></li>
id: 2
event: newOrder
data: <li id="order-15" sse-swap="order-15" hx-swap="outerHTML">#15 Mrs. Tini, 4 kg: <span>Queued</span></li>
event:the message's name. A message with noevent:line is namedmessage.data:its content, HTML here. Write the HTML on one line.- A blank line ends a message.
id:the message's number, used when reconnecting.
The sse extension: sse-connect and sse-swap
<script src="https://unpkg.com/[email protected]"></script>
<div hx-ext="sse" sse-connect="/board/stream">
<ul id="order-board" sse-swap="newOrder" hx-swap="beforeend">
<li id="order-12" sse-swap="order-12" hx-swap="outerHTML">#12 Mr. Darto, 3 kg: <span>Washing</span></li>
<li id="order-13" sse-swap="order-13" hx-swap="outerHTML">#13 Ms. Wulan, 2 kg: <span>Ironing</span></li>
</ul>
<span hx-get="/count" hx-trigger="sse:newOrder">3 orders today</span>
</div>
hx-ext="sse"andsse-connect="/board/stream"on the wrapper: one connection for everything inside it.sse-swap="order-12": when a message namedorder-12arrives, itsdatais swapped into this element. The default isinnerHTML. Herehx-swap="outerHTML", so the whole row is replaced by the server's new row. Several names can be separated by commas.sse-swap="newOrder"withhx-swap="beforeend"on the<ul>adds a new row at the end of the board. That row #15 carries its ownsse-swap="order-15", and htmx registers it straight away.hx-swapis inherited. Without anhx-swap="outerHTML"of their own, the rows inside the<ul>usebeforeendtoo, and a new status gets stuck after the old one: "WashingIroning".hx-trigger="sse:newOrder": that message triggers a normal htmx request, hereGET /count.sse-close="close"on the wrapper closes the connection when the server sends aclosemessage. If htmx replaces or removes the wrapper, its connection is closed too.
In Laravel 13, response()->eventStream() writes that format for you:
use Illuminate\Http\StreamedEvent;
use Illuminate\Support\Str;
Route::get('/board/stream', function () {
return response()->eventStream(function () {
$since = now();
$until = now()->addMinutes(5);
$round = 0;
while (now()->isBefore($until)) {
$checked = now();
foreach (Order::where('updated_at', '>', $since)->get() as $order) {
$row = view('board._row', ['order' => $order])->render();
yield new StreamedEvent(event: "order-{$order->id}", data: Str::squish($row));
}
$since = $checked;
if (++$round % 15 === 0) {
yield new StreamedEvent(event: 'ping', data: 'ping'); // no element catches it
}
sleep(1);
}
});
});
Str::squish() flattens the HTML onto one line. A value yielded without StreamedEvent is named update, not message.
The two additions to the loop protect the PHP worker. PHP only notices a closed tab when it writes to the connection, and eventStream() checks connection_aborted() only when a message is yielded. Without a ping every 15 seconds, a board with no new orders keeps its worker for good, even after the TV is switched off. After 5 minutes the loop ends, and EventSource reconnects by itself a few seconds later.
Polling or SSE: when the news arrives
every 30s |
SSE | |
|---|---|---|
| #12 changes at 08:00:04, shows on the board | 08:00:30, 26 seconds late | 08:00:04, at once |
| Requests per hour, one tab | 120, mostly with the same content | 1 connection that stays open |
The board was opened at 08:00:00, so polling asks at 08:00:30, 08:01:00 and so on. The change to #12 at 08:00:04 only shows at 08:00:30, on its next turn to ask. SSE shows it right then.
When the connection drops
- A short network drop. The browser's own
EventSourcereconnects by itself a few seconds later (the server can set that with aretry: 3000line). If the messages carryid:, the browser sends aLast-Event-ID: 2header when reconnecting, and the server can resend the messages after number 2 that were missed. - The browser gives up, for example when the server replies with an error or the wrong
Content-Type. The sse extension then tries again itself with a delay that keeps doubling: 0.5 seconds, 1, 2, 4 and so on, up to 64 seconds at most. Once connected, the delay starts over. - Messages from while it was down that aren't resent are lost. Laravel's
eventStream()only writesevent:anddata:, noid:. The safest way: on every new connection, the server sends the full board as the first message.
WebSocket: two-way
<script src="https://unpkg.com/[email protected]"></script>
<div hx-ext="ws" ws-connect="/board/ws">
<ul id="messages"></ul>
<form ws-send>
<input name="message" placeholder="Message to the courier">
<button>Send</button>
</form>
</div>
ws-connectopens a WebSocket (ws://orwss://). An address starting with/is adjusted by itself.- Every message from the server is HTML. Elements with an
idin it replace the element with the same id, like an OOB swap:<ul id="messages" hx-swap-oob="beforeend"><li>Courier: on the way</li></ul>. ws-sendon a form sends its content as JSON over that connection:{"message":"...","HEADERS":{...}}.- After an abnormal close, the ws extension reconnects with a random delay that keeps growing, up to 64 seconds. Messages sent while it's down wait and go out once it's connected.
When polling is enough
- Polling fits when being a few seconds to half a minute late is fine. It runs on any hosting, with no connection left hanging.
- SSE for one-way news that must show right away, such as a board on the shop's TV or notifications.
- WebSocket when the browser sends often too, such as a chat between the cashier and the courier.
- Count the cost. In Laravel on plain PHP-FPM, every open SSE connection holds one PHP worker for as long as it's open: 10 workers, 10 board tabs, and the 11th visitor waits. On HTTP/1.1, a browser also opens only 6 connections to one domain, SSE connections in other tabs included. HTTP/2 doesn't have that limit.
⚠️ Connections that never open, and messages nobody catches
- Forgetting
hx-ext="sse"or its script.sse-connectis then just an attribute, no connection. In the exercise, the wrapper needshx-ext="sse"andsse-connect="/events", and the<div>inside it needssse-swap="message". - Names that don't match.
sse-swap="message"doesn't catch the messages namedupdatefrom Laravel'seventStream(). Make the names match. - An inherited
hx-swap="beforeend". Rows inside the<ul>append too, instead of replacing. Give every row anhx-swap="outerHTML"of its own. - Multi-line HTML in
data:. The second line doesn't start withdata:, so the message is cut. Send one line.
TL;DR: SSE (Server-Sent Events) is one one-way connection, from the server to the browser, with event:, data: and id: messages separated by blank lines. WebSocket is two-way. With the sse extension: hx-ext="sse" and sse-connect="/board/stream" on the wrapper, sse-swap="order-12" (or message for unnamed messages) on the receiving element, hx-trigger="sse:newOrder" to trigger a request, and sse-close to close. A short drop: the browser reconnects and sends Last-Event-ID. The browser gives up: the extension tries again with delays of 0.5, 1, 2, 4 seconds up to 64 seconds. With the ws extension: ws-connect, HTML messages swapped by id, and ws-send sending a form as JSON. every 30s can be up to 30 seconds late, SSE is immediate. Polling is enough when lateness doesn't matter, and remember SSE holds one PHP worker per tab.
⚡ Polling or SSE
Guess first: the board uses every 30s and was opened at 08:00:00. Order #12's status changes at 08:00:04. When does the change show?
At 08:00:30, 26 seconds late, on its next turn to ask. With SSE, the change shows right away, at 08:00:04.
Meaning: SSE is one one-way connection that stays open: the server pushes news through it the moment something changes. WebSocket is one open connection too, but two-way.
⚡ sse-connect and sse-swap
Write:
<script src="https://unpkg.com/[email protected]"></script>
<div hx-ext="sse" sse-connect="/board/stream">
<ul id="order-board" sse-swap="newOrder" hx-swap="beforeend">
<li id="order-12" sse-swap="order-12" hx-swap="outerHTML">#12 Mr. Darto, 3 kg: <span>Washing</span></li>
<li id="order-13" sse-swap="order-13" hx-swap="outerHTML">#13 Ms. Wulan, 2 kg: <span>Ironing</span></li>
</ul>
<span hx-get="/count" hx-trigger="sse:newOrder">3 orders today</span>
</div>
Meaning: sse-connect on the wrapper opens one connection for everything inside it. sse-swap="order-12" swaps the content of a message named order-12 into that element. A message with no event: line is named message.
⚡ Sometimes polling is enough
Meaning: Polling fits when being a few seconds late is fine, and it runs on any hosting. Count the cost too: in Laravel on PHP-FPM, every open SSE connection holds one PHP worker.