Skip to content

A lean, scalable and low-cost raster look-up service built with COGs

Last month, I had the privilege to speak at FOSS4G NA 2024 in St. Louis about a raster look-up service built on Cloud Optimized GeoTIFFs (COGs), a piece of infrastructure that I helped build and that quietly answers a deceptively simple question: what is the flood depth, wind speed or ground shaking at this exact latitude and longitude? In my talk, I walked through how we answered that question for millions of locations, drawn from terabytes of climate hazard data, while spending roughly what one might spend on a modest compute tier. In this post, I walk you through the journey, the experiments that shaped it and the lessons we learned along the way.

The needle in a haystack problem

I want to begin with the observation that reframed the entire project for us, which is that big data and big questions are not the same thing. Our haystack was enormous, covering entire contiguous US, yet every question we asked of it was a single needle: give me the hazard values at this very specific point. Not, give me the hazard values for the whole county or a zip code. When the access pattern is that narrow, the engineering challenge is less about computing over everything and more about how you structure and store your data for fast retrieval.

Big data, but small questions. The craft is in reading just what you need.

What the data looks like

The product in this story estimates how natural hazards such as floods, windstorms and earthquakes threaten buildings and infrastructure. For every asset, it needs to consult the hazard layers. A single hazard layer is multiplied by a handful of climate scenarios, a few projection years (a baseline, then a decade or three into the future) and a ladder of return periods, where a 1-in-100-year event carries a 1% chance of occurring in any given year and a 1-in-500-year event carries 0.2% and so on. Multiply all of that by the roughly 950 spatial partitions that cover the continental United States, and you arrive at the following:

Dataset Approximate size
Built assets: buildings, bridges, roads, airports, ports and utility networks ~870 million records
Wind hazard grids ~1.2 billion values
Seismic hazard grids ~5.7 billion values
Flood hazard grids ~8.6 trillion values

On top of this, the source data arrived in every format one could imagine, including CSV, NetCDF, GRIB and GeoTIFF, at varying resolutions and coverages. Storing trillions of values in a database is technically possible, but I would argue that it is rarely wise, particularly when the questions asked of it are so narrow.

Spatial partitioning with OLC

Commonly, in geospatial modeling, the risk at a given location depends not just on that point, but also on its surroundings. For instance, the flood risk around a building depends on the nearby terrain, slopes, watershed and so on. Luckily for us, that spatial dependence was already modeled upstream.

Since the data already modeled spatial dependence, our map algebra reduced to focal operations rather than zonal or global. This meant, we could safely partition the data and process each chunk independently.

Whenever a computation is local in this way, a spatial partitioning scheme hands you parallelism almost for free, because each partition can be processed in isolation. We settled on Open Location Codes (OLC), the open specification that sits behind the Plus Codes you may have seen in your favorite map application. The world is divided into a grid of 20 by 20 degree cells, each cell is divided into 20 by 20 smaller cells, and the process repeats, with every child inheriting its parent's code as a prefix. A four character code therefore names a cell of one degree by one degree, which is roughly 110 km on a side, and about 950 of them blanket the continental United States.

Open Location Codes over the world and the continental United States

This hierarchy has a charming property, which is that you can climb to a parent simply by chopping characters off the end of the code. Better still, once the encoding is vectorized, hashing millions of coordinates into their codes is astonishingly fast. A query for a building and its surrounding hazard data can therefore discard most of the world with a cheap string comparison, rather than computing a distance to every candidate point in a table.

Data structures for fast location look-up

Our hazard data initially lived as points in a data warehouse. To obtain the hazard value for a building or a bridge, the pipeline would extract hazard data for the 4 digit open-location code where the asset was located, then would build a KD-tree spatial index over those hazard points, then found the nearest neighbors of the asset in the hazard dataset and interpolated between them using inverse distance weighting. This is a respectable and well-understood recipe, but when we profiled our slowest pipelines, they were spending a startling share of their lifetime inside exactly this interpolation. This approach would work well only when you process all the assets within the same partition. If you ever attempted to do a random look-up, it would be excruciatingly slow.

We then ran a simple experiment: grid the same hazard data, store it as GeoTIFFs, do the look-up against these rasters and compare. With a raster, the question what is the value at this coordinate? needs no search at all. Since geospatial rasters store extent, and spatial reference, you can deterministically find the exact cell in the raster where a coordinate falls and simply read the value at that cell directly.

When we store gridded data as rasters, location-based queries become simple look-ups rather than search operations. This phenomenally speeds up both batch and random access.

Vector look-up with KD-tree and interpolation versus direct raster look-up

The table below compares the time and resource consumption of the two approaches.

Vector (KD-tree + interpolation) Raster (direct look-up)
Time for one partition 4.45 hours 1.5 mins
Memory footprint ~14.5 GB ~3.5 GB
Core operation Build an index, search neighbors, interpolate Convert coordinate to continuous rasters, read the cell containing a given coordinate

Rearchitecting hazard pipelines

The move from vector based storage for hazard data (in data warehouses) to rasters was a big engineering shift. Not only was it new to the team, it also required careful thinking and rearchitecting several established pipelines. This was my single biggest contribution to the engineering team at that company. I had to convince the science and engineering teams to move away from the comfort of managed data warehouse to an arbitrary file-based storage system where the tooling had to be built entirely in-house. Although science and engineering teams march toward a common goal, their concerns were very different. The science team was concerned about fidelity of the risk scores, while the engineering team focused on performance, scalability and maintainability of this rather new approach.

The enormous performance gains were compelling enough to convince the teams to pursue PoCs, experiment with gridding, resampling, spatial resolutions and a few other parameters to find the optimal architecture. After a number of iterations, performance tests, we settled on storing the rasters in COG (Cloud Optimized GeoTIFF) format, with 512 x 512 chunk size, multi-band storing either different variables or time periods. The files were laid out in a predictable pattern on blob store (GCS) with permissions allowing range-read requests. The pipelines were updated to process upstream hazard data into regularly spaced grids, and store them as COGs, using the said approach. Essentially, this is a one-time operation with big benefits downstream. Designing this architecture on cloud-native geo, was a satisfaction in itself.

The compute pipelines then downloaded the relevant rasters from object storage and queried them locally using Xarray. The most expensive pipeline we had, which had been taking about 96 hours, now finished in about 6.5 hours.

Building a hazard look-up service based on COGs

While performance victory was real, it had a shortcoming. Downloading whole rasters made sense for the densest partitions, where millions of buildings shared a handful of files. It made less sense for the majority of partitions, where buildings are sparse and a pipeline would haul down a large file only to read a few cells. This was not a flaw in the architecture, but just a side effect of how human population is unevenly distributed across continental US.

As the re-architecture effort progressed, the business side of the product changed from licensing pre-processed risk data, to live, on-demand queries. The SLA expectations of batch compute pipelines and that of on-demand queries are very different. The hazard service cannot afford to download whole rasters for each request. Thus, it became clear that we needed a way to query rasters without downloading them entirely.

With about 950 partitions, 15 return periods, 5 climate scenarios and 3 perils, we were looking at roughly 213,750 rasters at about 175 MB each, which comes to something on the order of 35 TB. There was no sensible way to bake that into a container image or to mount it on every pod, and shipping each file on request would have been absurd.

COGs and VRTs: performing surgical reads at scale

The enabling technology was the Cloud Optimized GeoTIFF. A COG is an ordinary GeoTIFF that has been organized with cloud storage in mind. The pixel data is written in internal tiles (we used 512 by 512 pixel chunks), a small header records where each tile lives, and pyramid overviews are included to serve visualization. Because object stores support HTTP range requests, a client can read the header, work out which tiles intersect the cells it cares about and fetch just those bytes, never touching the rest of the file.

The second ingredient is the Virtual Raster, or VRT, which is a small XML file that stitches hundreds of rasters into what appears to be a single logical dataset. With a VRT in front, the hazard look-up service does not need to know how many files exist or where a particular coordinate lives, since GDAL resolves that and reads only the necessary chunks from the necessary files. This separates the data layer from the application logic, and it is the reason that moving from a prototype built on a handful of rasters to production across hundreds of thousands was almost uneventful. A request now downloads kilobytes instead of gigabytes since we only download the VRT manifest, rather than any actual raster file on to the server.

The flow is easy to describe in a sentence.

A client calls the REST API, a pod in the cluster opens the VRT, GDAL issues range reads against the COGs sitting in object storage, and the hazard values come back in the response.

Tuning the high performance look-up engine

With the architecture settled, we turned to profiling. The first iteration of the service treated every location as an individual call, and its behavior as batches grew was sobering.

Look-up time versus number of locations in a request, unoptimized

We then ran a series of experiments along the following axes: the number of bands, the batch size, clustered versus dispersed sample locations, parallelism versus async calls, a command line tool versus calling libgdal directly through rasterio, and querying several small rasters versus a mosaic of rasters. The observations were consistent enough to state as rules:

  • Fewer, larger queries are faster than many small ones, since every request to the blob store carries a fixed latency tax.
  • Multi-band queries are faster than several single-band queries, since the bands we wanted lived together and a single read for a given location could penetrate across all the bands and get them at once.
  • Async calls are faster than parallel calls, which makes sense once you recognize that the work is dominated by waiting on the network rather than by computation.
  • Mosaicking contiguous, high-traffic tiles into one larger tile was the standout, because it meant fewer files to open and fewer headers to read.

Look-up time for 10,000 locations across optimizations

Method (10,000 locations) Look-up time
Baseline 219.6 s
Multi-band 102 s
Async 86 s
Mosaic 5.1 s

I find the last row the most instructive. Nothing about the hardware changed, and the algorithm did not become cleverer. We merely rearranged the data and saw phenomenal gains.

Conclusion

We began with data that was far too large to store in a conventional database, in traditional formats that were awkward to query for spatial workloads. By partitioning the world with Open Location Codes, converting points into rasters, storing those rasters as COGs and fronting them with VRTs, we built a service that streams only what it needs, and does so for roughly $100 a month in compute. Climate data is big data, and as models and resolutions improve, it will only grow larger, which is why I believe that rasters, with their combined strengths in storage, streaming, look-ups and visualization, will keep earning their place. More broadly, I am convinced that cloud native geospatial is where our field is headed. The trade-offs, however, are worth stating plainly:

  • Gridding is a lossy decision. The interpolation choices and the resolution are baked in at write time, so changing them means rewriting the data, although only by a few decimals.
  • Nature of queries impact how we stored the data. Our questions were mostly point look-ups. However, if your questions are zonal statistics over large polygons, or require reprojection and overlay, the calculus changes and you should test accordingly.
  • There is a lot to tune when it comes to rasters. Chunk size, compression, band order and mosaic boundaries all shape the performance, and they deserve as much thought as the code does.
  • Mosaics and VRTs make data more manageable. A single VRT can represent thousands of rasters. Thus concern of determining which raster to look-up can be safely offloaded to the GDAL stack which natively understands VRT. When data needs to update, it is easier to update an entire raster at once, then update the VRT. This meant our update cadence was simpler and more hygenic, and less error-prone.
  • Async reads for the win. After all the said optimizations are done, the bottleneck is still the I/O, and async helps hide that latency.

In our case, the combination was both faster and far cheaper than the alternatives we weighed. That judgment is specific to our workload, so if your data is modest, or your queries are broad rather than pointed, a simpler approach may serve you better.

Resources