An Edge Script can answer a request with a stream of Server-Sent Events. The script returns a Response that holds a ReadableStream, and the edge delivers each event as the script writes it.
The CDN page describes how the network treats an event stream, including the heartbeat and the caching rules. This page describes what a script must do.
Quickstart
This example sends one event immediately, and one more every 15 seconds. The interval also acts as the heartbeat that keeps the connection open.
Return the response before you wait
Return the Response at once, and let the stream fill in afterwards. A script that waits before it returns is treated as a slow origin: the edge allows 60 seconds for a response to start, and answers with 504 Gateway Timeout when nothing arrives. This applies to any await before the return, and a subrequest is the common case.
Write the first event as soon as the stream opens, and do not wait for the
first real update. The client receives no part of the response until your
script writes the first byte, and this includes the response headers.
Keep the isolate alive
The isolate that answers a request can be evicted once the handler returns. An event stream lives longer than the handler, so pass a promise to waitUntil that resolves only when the stream ends. Without it, the script can stop in the middle of a stream.
Always resolve that promise when the stream closes. A promise that never settles holds the isolate open after the client has gone.
Caching
A stream that a script returns is not cached, and it needs no Cache-Control header. The edge serves every request to a standalone script from the script itself.
Set Cache-Control: no-cache anyway if the same code also runs behind a pull zone as middleware, where the normal caching rules apply.
Limits
The Edge Scripting limits apply, with one point to note: the 30-second CPU time limit measures processor time, and not the time a connection stays open. A stream that waits between events uses almost no CPU time. Pricing follows the same rule.
Keep the work inside the stream small. A script that builds each event with a subrequest reaches the subrequest limit quickly.
References