# Query lifecycle

> How one request moves through a NYXDB WebSocket session — request ids, demand credit, progress, results, completion, failure and Cancel.

On a WebSocket session every request is a sequence of frames tagged with one
request id. The client chooses the id; the server echoes it on every frame it
sends for that request. Many requests run at once on one connection, and a slow
or streaming request does not block an unrelated finite read on the same
connection. Frame names are defined on the [Protocol](/docs/drivers/protocol)
page.

## A finite query

- client → server: ExecuteSql (request id R, maximum_rows, maximum_bytes, initial_demand)
- server → client: result batch (R)
- client → server: Demand (R, credits)
- server → client: result batch (R)
- server → client: Completed (R) (receipt and elapsed time)

- `maximum_rows` and `maximum_bytes` bound each page.
- Demand is credit: the server sends result pages only while the request holds
  credit. `initial_demand` is the first grant; `Demand` adds more.
- `Completed` ends the request with its receipt. `Failed` ends it with a status
  instead.
- A client that opted in with `ExecuteQuery` features also receives
  `QueryProgress` frames (stage `queued`, `executing`, `delivering`,
  `finalizing`, with delivered batches, rows and bytes). Progress never
  consumes demand.

## A continuous query

A `STREAM SELECT` is sent the same way, as `ExecuteSql`, and is answered with:

1. `ContinuousOpened`, carrying the subscription's delivery cursor;
2. `ContinuousResult` frames: first the snapshot of the current result, then
   exact deltas as committed writes reach the query.

`ContinuousDemand` acknowledges the delivered prefix (by delivery sequence) and
grants more credit.

A continuous query runs until it is cancelled, its connection closes, or a
configured stream lifetime (`max_stream_duration`) ends it.

## Cancel

Send `Cancel` with the request id of the request to stop. The server ends that
request with `Failed` for the same request id; other requests on the
connection continue.

Closing the connection cancels every request on it.

## Deadlines

A direct session's request carries no server deadline by default: it is
bounded by the work it asked for and stopped by `Cancel`, a connection close or
a node drain. A statement may ask for a deadline with the
`request_timeout` setting; see [Settings](/docs/sql/settings) and
[Limits](/docs/operations/limits).

## Over HTTP

`POST /sql` has no frames: the gateway collects the whole result and answers
once, with the `nyxdb.query-result/2` document or an error status. Use the
WebSocket session for results that should arrive page by page and for
streaming reads.

---

Source: https://nyxdb.io/docs/drivers/query-lifecycle/
