How Async Generators Tamed Omni's Query Stream

Starting with the good parts

I’ve been writing JavaScript for over 20 years, and I got into it almost as a contrarian act. Internet Explorer 6 was the dominant browser. Debugging JavaScript was close to impossible. Any serious engineer back then would have told you it was a terrible language.

My insight was simple: all the work I was doing powered web applications, and every browser ran JavaScript. It was becoming the lingua franca of the web, and that seemed important.

So I invested in it. I remember reading Douglas Crockford’s JavaScript: The Good Parts on cold bus rides across the Bay Bridge. Crockford, who also gave us JSON, wrote an opinionated guide on which parts of the language to use and which to avoid. That habit of asking “which parts are actually good?” stuck with me.

This post is about one of the parts I wrote off, and was wrong about: generators. At Omni, they turned a messy, multiplexed stream of query results into a plain for loop and a switch statement, and nearly four years later, that’s still how Omni’s browser app consumes every query it runs.

The wire format

Omni streams query results to the browser over a long-lived HTTP response. Why not one big blocking response, or a WebSocket? Because plain HTTP streams are the lowest common denominator you always end up supporting, and because we need to send multiple query results at once. HTTP/2 also made long-lived streams cheap, since many of them can share one connection.

Streaming HTTP has no standard way to split a stream into messages, so we use NDJSON, one message per line (NDJSON stands for “newline-delimited JSON”). Our results are Apache Arrow, which streams natively. But every connection also carries metadata, so JSON is the envelope and the Arrow bytes ride inside it as a base64 string:

{"job_id": "…", "client_result_id": "…", "status": "COMPLETE", "result": "QVJST1cxAAD/////…"}

In the browser, reading it is simple: pull bytes off response.body with a stream reader, decode them, and parse each complete line.

One pipe, many queries

With a connection and a parser in hand, the obvious next step is to emit an event for each message. That’s easy in the browser. But in the React codebases that were the norm four or five years ago, it felt unergonomic to me. I wanted consumers of this interface to loop over the data, and not have to worry about registering event listeners, and especially to not have to remember to clean up after them.

The catch is that you don’t know when each message will arrive. A loop that blocks until all the data is in defeats the purpose. At that point you might as well use a non-streaming endpoint that sends everything at once.

And we had a harder requirement: multiplexing. A dashboard might have 15 queries. We didn’t want to run them one at a time, or open 15 connections. We wanted one pipe: send as many queries as we like down it, and keep one persistent stream that hands back each result as it finishes. In practice the stream opens with a header line, every result line carries its own job_id, and a footer line closes the batch.

So we had many queries on one connection, results arriving in any order, and UI code that had to make sense of it all.

A solution looking for a problem

A quick detour into my own coding taste. I seek the simplest solution, sometimes to a fault. For a long time I eyed the generator spec with skepticism.

Generators looked like a neat solution in search of a problem, at least in the browser. Apart from fetch and XMLHttpRequest before it, most web apps didn’t need to do much asynchronous work, even four or five years ago. When they did, Promise was a great solution. Native streams often felt opaque and short on use cases too.

That’s not to say they were useless. I’d built streaming query pipelines at earlier jobs. They just weren’t common enough to reach for by default. This was Crockford’s lesson at work. The Good Parts had taught me to ask whether a feature earned its place before I used it, and generators hadn’t earned theirs yet. So, out of what I’d call healthy skepticism, I kept an eye on them, but didn’t reach for them.

The light bulb

My first version, shipped in January 2023, was event-driven. The server side was an event emitter, and the browser listened with server-sent events (EventSource). A dashboard wired up one callback per kind of message:

const streamer = new QueryRunJobEventSourceClient(collectionId, searchParams)
streamer.onResult((result) => setResults(/* … */))
streamer.onError((error) => setErrors(/* … */))
streamer.onStreamFailed((failure) => {
  /* mark every query we haven't heard from as failed */
})
streamer.onClose(() => setIsRunning(false))
streamer.connect()

It worked fine. But EventSource only does GET. Starting a query run creates something, and in REST terms that’s a POST, not a GET. Using GET went against REST, and every run option had to squeeze into the URL. The response types kept multiplying: failures, queries that needed more information, requests for just a query plan. Each new type meant another callback, and the flow of a single run was spread across all of them.

What I wanted was for callers to write the code they already know: a loop, and a switch over the kinds of result. That’s when the light bulb went on. Streams, generators and async generators, the tools I’d never had a use for, fit this problem exactly, and they chain together:

  1. A stream reader pulls raw bytes off a plain fetch response.
  2. An async generator turns those bytes into parsed messages.
  3. A second async generator upgrades each message into something the UI can use directly, such as decoded Arrow data.

Keeping these as separate layers was deliberate. Nothing in the parser or the upgrade step depends on the browser, so they can run anywhere JavaScript runs: in a page, in a web worker, or on a Node server. The parser already does double duty: Omni’s Node server uses it too, for things like Blobby’s query tools.

Here’s the upgrade step as I first wrote it in March 2023, lightly trimmed:

export enum QueriesJobUpgradeStreamResultsType {
  CatastrophicError = 'CatastrophicError',
  Complete = 'Complete',
  Error = 'Error',
  Footer = 'Footer',
  Planned = 'Planned',
}

export async function* queriesJobUpgradeStreamResults(
  generator: ReturnType<typeof queriesJobStreamParser>
): AsyncGenerator<QueriesJobUpgradeStreamResults> {
  for await (const result of generator) {
    if ('status' in result) {
      if (result.status === OmniQueryRawResultStatus.COMPLETE && result.result) {
        yield {
          data: toArrowQueryResult(result, base64ToArrow(result.result)),
          type: QueriesJobUpgradeStreamResultsType.Complete,
        }
      } else if (result.status === OmniQueryRawResultStatus.PLANNED) {
        yield { data: result, type: QueriesJobUpgradeStreamResultsType.Planned }
      } // …errors
    } else if ('remaining_job_ids' in result) {
      yield { data: result, type: QueriesJobUpgradeStreamResultsType.Footer }
    } // …catastrophic failures
  }
}

And here’s what a caller writes today (omni-query/query-pipeline/use-query-manager.ts):

for await (const result of queryRun) {
  switch (result.type) {
    case QueriesJobUpgradeStreamResultsType.Complete:
      handleResult(result.data)
      break
    case QueriesJobUpgradeStreamResultsType.Planned:
      handlePlanResult(result.data)
      break
    case QueriesJobUpgradeStreamResultsType.Error:
      handleError(result.data)
      break
    case QueriesJobUpgradeStreamResultsType.CatastrophicError:
      handleCatastrophicError(result.data)
      break
    // …
  }
}

That’s the whole point. No callbacks to wire up or tear down. Results arrive whenever they arrive, and the loop reads top to bottom like ordinary synchronous code. Each result is a tagged union, so TypeScript narrows result.data to the right type in every case.

Instead of a set of callbacks to register, connect and tear down, a caller gets one object. Whoever holds it loops over it, and when the loop ends, so does their involvement. That’s the real win: it removes the callback ceremony, and it makes memory much easier to get right. A callback registered on a long-lived emitter keeps its closure, and everything that closure captures, alive until someone remembers to remove it. A loop has nothing to unregister. Its handling code lives in the function doing the looping, so once the run finishes, all of it can be garbage collected. You still have to cancel a run nobody needs anymore, but the bookkeeping of adding and removing listeners is gone.

Once I had the idea, it took a day or two to build. It worked, and it’s one of the things I’m proudest of.

Built on, and still standing

On top of this we built more abstractions. A QueryManager manages connections to our query-run endpoints, and there are separate query runs for dashboards, workbooks and apps (DashboardQueryRun, QueryRun, AppQueryRun), all sharing one base class.

The pattern absorbed new needs without changing shape. When the server can’t finish every query on a connection, the footer lists the ones it deferred. The pipeline reconnects for just those and keeps yielding into the same loop (query-pipeline/query-pipeline.ts):

case QueriesJobUpgradeStreamResultsType.Footer:
  if (result.data.remaining_job_ids.length > 0) {
    this.reconnect({ jobIds: result.data.remaining_job_ids })
    yield* this.results()
  }

The caller’s for await loop never knows a second connection happened. Rate-limited queries retry the same way, with exponential backoff and jitter. Over the years we’ve added DuckDB requeries and new result types, and none of them changed the loop.

To my surprise, the design has stood the test of time. Nearly four years later it has the same shape, and it runs every query the Omni app sends from the browser.

I think the pattern makes even more sense today. Browsers handle streams well, HTTP/2 makes long-lived connections cheap, and front-end workloads keep getting more asynchronous. So here’s the takeaway I’d hand any engineer: when data arrives as a stream, don’t make your callers react to it. Turn it into something they can consume procedurally. Parse it in one layer, upgrade it into the objects your app cares about in the next, and hand callers an async iterable. Then whoever, or whatever, writes the next feature gets a plain for loop and a switch.