This article is about how I built an extremely memory constrained, distributed query engine that achieves Athena/Trino/BigQuery level performance while running purely serverless across different data centers on Cloudflare's Durable Objects.
The first time I used Athena felt magical. I could join tables with billions of rows, and get useful results back all within about 5 seconds.
Years later I discovered DuckDB, again magical. Just throw multi-gb parquet (or even CSV!) and it would give results back in no time.
I wanted to understand how these things work, and so I initially set myself this challenge:
- Build a file format similar to Parquet, but simpler, with a basic query engine that can run the ClickBench queries in less than 100kb of WASM.
ClickBench (https://github.com/ClickHouse/ClickBench) is a great open benchmark with about 43 realistic queries and a dataset with 100 million rows.
I achieved this (well slightly over 100kb) and managed to beat DuckDB on a few queries! Write up here. However while this was a fun experiment it's mainly a toy project without many practical use cases.
Recently I've been obsessed with efficiency and where possible full scale to zero. I like Cloudflare's Durable Object primitive as it gives me the low latency start-up/scale to 0 of a worker, BUT can store state and is individually addressable. I decided to build on my 100kb wasm experiment with the following goal:
- Can we achieve Athena (Trino) and BigQuery performance with purely serverless memory constrained Durable Objects
The result - it is possible to get comparable performance with Athena using memory constrained Durable Objects across data centers, at a similar or lower cost, and its infinitely* scaleable! (infinite = unlimited budget and cloudflare having unlimited capacity).
I don't have unlimited cloud budget so the actual hosted version is not publically accessible but you can watch recorded runs replay in the console at wcol-coordinator.rust-wasm.workers.dev, and the code is at github.com/davidgtonge/wcol.
The rest of this post goes into how this works and what I learned along the way.
The Curse of Rust Dependencies
Now as someone who has done a load of JS, I can hardly complain about Rust crates vs NPM packages, but I'm going to anyway. The beauty of Rust is the strict compiler with proper type checking (not the false sense of security that you get from TS). BUT, it is very easy for a relatively simple Rust project to end up taking minutes to compile by the time you add a few dependencies. Something like Arrow is particularly bad. (HT to https://ninja.kunobi.com/kache which I've found better than https://github.com/mozilla/sccache for speeding up paralell (i.e. agentic) rust compilation). In addition a lot of Rust crates are not really made for WASM or a memory constrained environment. So given we are in the world of agents I feel I have full permission to ignore any shame in NIH and just build (prompt) everything from scratch.
This meant:
- A zero-allocation Thrift parser (now on crates.io as compact-parquet-thrift). The usual route deserialises the whole Parquet footer into a tree of objects; this one walks the footer's bytes in place and keeps only what the query needs.
- A streaming Parquet page reader. Pages are decoded as the bytes arrive from R2 range requests, in a fixed amount of memory, so a scan never holds a whole column chunk.
- A JS-Wasm stream pool. Memory bounded (and efficient) handling of 100+ streams between JS and WASM with back pressure.
- A SQL parser. I managed to get DataFusion down to a reasonable size, but got sick of the slow iteration and so opted to use my 1000 LOC custom parser for experiments, with the ability to swap in DataFusion later.
- WCS, a small wire format for raw and aggregated data that moves between Durable Objects with a fixed frame size of 64kb.
Claude created some good interactive walk throughs of these here (and one for the Thrift and Parquet layer here).
But let me walk you through the high level architecture first and then data flow with trade offs.
Architecture
The system is built around a few core principles:
- Instead of distributing work to threads or networked nodes, a Durable Object is the compute primitive used. We separate Scans, Reducers, Finalizers, Coordinators all into different Durable Objects.
- Communication happens via RPC streams - Cloudflare provides the ability for us to open up low latency TCP streams between these DOs (this is one of the main benefits of DOs vs standard Workers - I only want a single instance of a given "reducer", I don't want 10 scanners speaking to 10 instances of the same reducer)
- Tight memory accounting - each DO can get up to 128 MB, BUT may end up sharing an isolate with another DO and so in practice 64 MB is the ceiling we aim for.
- Where memory growth is inevitable (reducer hash tables), the query planner aims to keep memory needed to < 32 MB per DO, BUT where this is missed (i.e. skewed distributions) we spill to R2 (initially I wanted to spill to the DO's sqlite, but its insanely expensive!). When the planner estimates more group state than the Durable Object reducers can hold between them (128 reducers × 16 MB), it runs the reducers in Cloudflare Containers instead, which have more memory and a local disk to spill to.
- To stay on top of memory budgets communication between DOs is via 64kb frames in a new WCS format that supports raw data as well as aggregates.
So how does it work
A query is submitted to the co-ordinator which parses, creates a logical plan, reads the parquet footer(s) and creates a physical plan. The physical plan is a graph of Scan, Reduce and Finalise nodes. Durable objects are initialised with the graph and their particular job. Because durable objects are addressable a scan node can create connections to reducer nodes, and reducer nodes can create connections to finaliser node (normally the same node as the coordinator).
Each Scan node receives R2 ranges to read (we do some clever coalescing to optimise the number of ranges to read), and it performs filtering and projection and then sends frames to up to 100 reducers. Each reducer receives streams from up to 100 scanners, processes and builds up its hash table - this is the same mechanism for global sort, join, group by, top K, etc. If the hash table breaches the memory limit it is sorted and streamed to R2. This can happen multiple times, so for a really bad skew we could need up to 10 x 32mb sorted hash table partials on R2. Once all Scan streams have been received the Reducer then reads the 10 parallel sorted hash table partials in parallel, joins and emits to the finaliser. For TopK queries - Reducers only need to emit their local TopK, which reduces the data sent significantly.
There isn't much more than that, the hardest parts are managing memory and reliable streaming. However when it works its beautiful and a lot more visible than a standard multi-core threaded query engine.
Scaling? To keep reliability I limited input and output streams to maximum 100. This means that if we need 1000 reducers to speed up a really big query we will need to put 100 routers between the reducers and the scanners. The routers take hash % 100 each and then route to their assigned reducers hash % 10.
A few unexpected gotchas I found while developing:
- Big difference between hibernated DO startup and new DO startup (obvious in retrospect, but I assumed it would be 10-20ms difference, whereas in reality hibernated DOs can start in about 120ms, whereas fresh DOs were more like 300ms.
- CPU allocation per DO is not uniform - this could be expected, but I thought it would be random, whereas in reality I had some DO's that consistently had demonstrably slower CPU performance than the rest or which always ended up sharing V8 Isolates.
Containers
While spilling to R2 is fairly cheap, it is slow and while working on getting some queries faster I decided to make Cloudflare Containers optional for some worklads. This doesn't change the architecture at all (each Container instance is backed by a Durable Object), and the advantage of writing the logic in Rust means that I can compile a lightweight (1.02 MB!) Rust docker image pretty easily.
I experimented with different instance sizes (Cloudflare supports from 1/16 to 4 vCPU) and settled on the Basic size with 1/4 vCPU and 1 GB of memory. The reason is that the system is designed to be singled threaded and so we get speed through having lots of reducers - so its better to run 32 x 1/4 vCPU containers than 8 x 1 vCPU containers.
Cost and Performance
You can see some example query replays here: https://wcol-coordinator.rust-wasm.workers.dev/
We managed to get 28 of the 33 queries running under 10s. On average we were 2.7x slower than Athena, although we were faster on a few queries. So not quite the result I was looking for, but pretty decent considering that queries are run across data centers on memory constrained compute primitives not designed for this at all!
Cost wise we were competetive, with most queries cheaper and few sightly more expensive. The beauty with Cloudflare's Durable Objects is you only pay while they are active, and we don't pay any data transfer costs. So our costs are:
- Durable Obejct processing duration
- Durable Object requests
- R2 Gets
- R2 Puts
- Container processing duration (if used)
Once a scanner durable object has finsihed scanning and has sent all its data to a reducer, we stop paying for that durable object.
Hash Exchange and Spill
While we can write memory efficient code with streaming and strict rules around allocation, some queries or analysis problems just require a lot of data in memory. For example grouping, sorting, joining. There are 2 approaches implemented in WCOL, both are standard approaches used in many engines, but how they work with Durable Objects is slightly different.
The first is a hash exchange. Because we have separate scanner reading the data, we can get those scanners to speak to multiple reducers, and we send to a reducer by hashing the group keys (or sort range, or join keys). So if we are grouping 1 billion events by 1 million users, we need to have a million users in memory as we stream the billion events through the system. The approach here is to hash the million users such that we can divide the million users up among X reducers. e.g. with 100 reducers each reducer only needs to deal with 10,000 users. Essentially we end up with a partitioned hash map of transactions by user, but partitioning allows it to be split across hundreds of durable objects.
Now, if data is evenly distributed our planner can ensure that each reducer can execute a full query within its limited memory budget. However real data is seldom evenly distributed and therefore we are likely to get some reducers that end up with more data than they can fit in memory. While our planner tries to avoid this happening we need to deal with it when it happens. The approach here is to "spill to disk". This is standard practice for query engines, however Durable Objects don't have a disk. I experimented with using the SQlite attached to each Durable Object, this worked but was super expensive - and the aim of this work is to be cheap! So I ended up spilling to R2.
How does this work. I tried a few approaches, but the simplest one was:
- Have a fixed size hash
- Once it reaches its max size, stop processing incoming streams
- Sort the hash and stream to R2
- Start a new hash and start processing incoming streams again
This may repeat multiple times so for a given query we could end up with several partial sorted hashmaps written to R2. Once incoming streams are finished and all the data has been received, we then stream all the partial hashmaps back from R2, because they are sorted we can join matching hash keys and output to the finalizer without needing to have the full hashmap in memory.
This slows the system down and so we try and avoid it where possible (and use Containers where we anticipate the memory needs), but it makes the system robust (and able to operate on these memory constrained compute instances).
WCS: the wire format
Every stream between Durable Objects (scan to reducer, reducer to finaliser, and to the container reducers) is a sequence of WCS frames: a 32-byte header and at most 64kb of data. There are four kinds of frame:
- A batch of rows, in the engine's own columnar layout, so nothing is converted on the way in or out.
- A partial aggregate, so a scan sends its running counts, sums or distinct sets for a slice of the groups rather than its rows.
- A dictionary, sent once per column before the batches that use it, so strings cross the network as small integer ids, just as they sat in the Parquet file.
- An end marker, so a connection that drops never looks like a stream that finished.
Again the question would be - why not use Arrow? But I needed the strict 64kb limit for memory accounting. A Reducer can have 100 incoming streams if they all send 1 MB chunks then we'll be out of memory. Also Arrow as mentioned earlier is ridiculously slow to compile. The benefit of using our own wire format is that we can send raw data as well as aggregates through the same format.
So What
This was an interesting experiment, but is it useful? Maybe not as a general purpose Trino replacement, but I think there is value in being able to run large analytics workloads on V8 isolates with constrained memory. This archteciture allows much more efficient use of CPU (in the sense that the greater the number of paralell workloads that can be supported, the lower the chance of unused idle capacity).
I personally think a lot of microservice based architectures would run well on V8 isolates and I've been looking at CellD at Moneyhub. Even NodeJS is getting in on the action with this green threads proposal