cancel
Showing results for 
Search instead for 
Did you mean: 
Community Articles
Dive into a collaborative space where members like YOU can exchange knowledge, tips, and best practices. Join the conversation today and unlock a wealth of collective wisdom to enhance your experience and drive success.
cancel
Showing results for 
Search instead for 
Did you mean: 

Insurers Don’t Need Faster APIs. They Need Fewer Calls: Geospatial Scoring with H3 and Spatial SQL

Phani_sannala
Contributor
Insurance · Reinsurance · Banking · Telecom · Retail · Agriculture — Per-Object API Calls to Per-Cell Scoring with H3 and Native Spatial SQL

By @Phani_sannala, in collaboration with @sridharplv

Your lakehouse already holds the geometry. Why are you shipping it, one object at a time, to someone else's server?

Every data platform I've built has the same embarrassing bottleneck, and it is never the lakehouse.

The ingestion is solved. The Delta tables are clustered. The gold layer refreshes on time. Then somewhere in the middle of the pipeline sits a loop that takes each record, serialises it to JSON, posts it to an external API, waits a quarter of a second, parses the answer, and moves on to the next record. That loop is where the hours go. It is where the 2 AM pages come from. And in most cases, it is doing work your cluster could do faster without leaving the building.

This article is about deleting that loop — or, where you genuinely can't, shrinking it by orders of magnitude. I'll use geospatial hazard scoring as the worked example, because that's where I hit it hardest, but the pattern applies anywhere a pipeline calls an external service once per record.

The problem: one object in, hundreds of rows out

Strip away the industry and the pattern looks like this. You hold a large set of objects with a location — a point, or a polygon. For each one, you call an external service that knows something about that location and returns a block of enriched records. You land those records and aggregate them back to the object.

It shows up everywhere:

• Insurance and reinsurance — scoring buildings, factories, schools and public assets for flood, wildfire, windstorm and earthquake exposure under several climate scenarios.
• Banking — physical climate-risk disclosure on lending portfolios and secured assets.
• Telecom — coverage and signal-propagation scoring for every planned tower site.
• Retail and property — catchment demographics, visitor traffic and competitor density per store or parcel.
• Agriculture — soil, yield and drought indices per field boundary.
• Logistics — risk and ETA enrichment per route segment or depot.

The worked example

I'll use the case I know best: climate and catastrophe hazard scoring for an insurance portfolio. Each risk object is a building, a plant, a school, a hospital — anything that can be insured. It arrives as either a point (an address) or a polygon (a site footprint).

The hazard API takes a coordinate and returns a full hazard cube for it: every peril (flood, coastal surge, wildfire, windstorm, earthquake, heat, drought, hail…) crossed with every climate scenario (the SSP pathways — SSP1-2.6, SSP2-4.5, SSP5-8.5 and friends) crossed with every forecast horizon. In our case that was roughly 400 records per coordinate.

Points are manageable. Polygons are where it detonates. The service doesn't score a polygon as one thing; it resolves the footprint into the coordinates inside it — often 1,000 to 3,000 of them for a large site — and returns 400 records for each.

Do the multiplication

InputCoordinates sentRecords returned
1,000 point objects1,0004,00,000
1,000 polygon objects × 2,000 coords20,00,00080,00,00,000

One thousand polygons — a modest commercial book — produces two million scoring requests and eight hundred million rows. Scale the portfolio to six figures and the job stops being a pipeline and starts being a weekend.

Why the per-object API pattern breaks

The API isn't the villain. The shape of the integration is. Six things go wrong at once:

1. Latency is multiplied, not added. A 250 ms round trip is nothing once. Two million times, behind a vendor concurrency cap of 16 in-flight calls, it is hours of pure waiting — and your cluster is billing DBUs the whole time while its cores sit idle.
2. Rate limits and batch caps set your throughput, not your hardware. You can scale to 64 workers; the vendor will still answer 16 calls at a time. Adding compute makes the bill bigger, not the job faster.
3. Failures are a statistical certainty. At two million calls, a 1% rate of 429s and 503s is 20,000 retries. Without idempotent, resumable bookkeeping, a job that dies at 70% restarts from zero.
4. There is no deduplication. The caller has no idea that two warehouses 200 m apart sit in the same hazard-model grid cell and will receive identical scores. So it asks twice. Then it asks again next quarter.
5. The geometry work is hidden and duplicated. Point-in-polygon, tessellation, centroid choice — the vendor does it behind the endpoint, opaquely, and you often pre-explode polygons client-side just to satisfy a points-only contract. That's two copies of the same spatial logic, neither of which you control.
6. Data leaves the platform. Every call ships your exposure locations outside your governance boundary and brings results back un-lineaged. Unity Catalog can't tell you which model version produced which score.

The usual response is to tune the loop: async clients, bigger batches, smarter back-off. All useful. None of them change the fact that the unit of work is wrong.

The reframe: the cell is the unit, not the object

Split what the API does into its two real jobs:

• Geometry resolution — turning a point or polygon into the set of locations that need scoring, with weights. This is deterministic, well-understood computational geometry.
• Scoring — evaluating the hazard (or demographic, or signal) model at a location. This is the part that may genuinely be someone else's intellectual property.

The first job has no business being behind an HTTP endpoint. It belongs next to the data, in Databricks, at cluster speed.

Once geometry is resolved in the lakehouse, a second insight falls out: almost every scoring model is gridded. Hazard models, catchment models, propagation models — they all evaluate on a raster or grid of finite resolution. If two objects fall in the same grid cell, they get the same answer. So you index every location to a discrete global grid — H3 — and ask the scoring service once per distinct cell, not once per object or coordinate.

Three things then compound:

1. Deduplication. Real portfolios cluster — buildings are in cities, stores are on high streets. Millions of coordinates collapse to a far smaller set of cells.
2. Caching. A cell's score depends on geography and model version, not on who owns the building. Cache it in Delta, keyed on (h3_cell, model_version), and the next portfolio — or next quarter's re-run — pays only for cells it hasn't seen.
3. Elimination. If the scoring model can be brought in-house as data (a published grid) or as code (logic you own), the remaining calls go to zero.

The call count stops being a function of portfolio size and becomes a function of geographic footprint × cache freshness.

api_tax_pipeline_diagram.png

 

The top row scales with coordinates; the bottom row scales with distinct, uncached cells.

The tooling in late 2026: you probably don't need a library anymore

If your mental model of geospatial on Databricks is "install Mosaic" or "attach the Sedona JARs", it's out of date. The platform now does the core work natively.

OptionStatusUse it for
Native Spatial SQL (ST_*, GEOMETRY / GEOGRAPHY types)Built into DBR 17.1+ and Databricks SQL; GEOMETRY support is GA (docs (https://learn.microsoft.com/en-us/azure/databricks/sql/language-manual/sql-ref-st-geospatial-functio...))Parsing, area, intersection, containment, spatial joins — no import in SQL
Native H3 expressions (h3_*)Built in; need Photon or Databricks SQL Pro/ServerlessIndexing, polyfill, tessellation, k-rings, cell boundaries
Mosaic (Databricks Labs)Maintenance mode; pinned to DBR 13.3 LTS and retired with its end of support in August 2026 (GeoBrix intro (https://databrickslabs.github.io/geobrix/docs/intro))Nothing new. Migrate existing code to native functions
GeoBrix (Databricks Labs)Mosaic's GDAL-based successor, focused on what the product doesn't coverHeavy raster work (RasterX), grid utilities (GridX)
Apache SedonaOpen source, runs on DatabricksTeams already invested in it, or needing functions native SQL lacks

My rule of thumb: start native, reach for a library only when you hit a specific gap. Native functions run in Photon, need no cluster init scripts, survive runtime upgrades, and are governed like any other SQL. Python UDFs over Shapely or GeoPandas are the slowest option on the table — fine for prototyping, wrong for 800 million rows.

The architecture, step by step

Four stages, all on the medallion pattern you already run. Code below is trimmed for reading; the full runnable version, with a mock API and timing harness, is in the companion notebook.

Step 1 — Resolve geometry to weighted H3 cells (silver)

Points get one cell with weight 1. Polygons get tessellated: h3_tessellateaswkb returns every cell the footprint touches — including boundary cells — plus the exact "chip" of the polygon inside each one. That chip's area over the footprint's area is the cell's weight.

CREATE OR REPLACE TABLE silver_object_cell
CLUSTER BY (h3_cell) AS

-- Points: one cell, full weight
SELECT risk_object_id, portfolio_id,
       h3_longlatash3(st_x(geom), st_y(geom), 8) AS h3_cell,
       1.0D                                      AS weight,
       'point'                                   AS method
FROM   bronze_risk_object
WHERE  upper(st_geometrytype(geom)) LIKE '%POINT'

UNION ALL

-- Polygons: exact tessellation, boundary cells included, area-weighted
SELECT risk_object_id, portfolio_id,
       t.cellid AS h3_cell,
       st_area(st_geomfromwkb(t.chip)) / st_area(geom) AS weight,
       IF(t.core, 'core_cell', 'boundary_chip')        AS method
FROM   bronze_risk_object
LATERAL VIEW explode(h3_tessellateaswkb(st_asbinary(geom), 8)) x AS t
WHERE  upper(st_geometrytype(geom)) NOT LIKE '%POINT';

Two choices here matter more than they look:

• Tessellate, don't polyfill. h3_polyfillash3 keeps only cells whose centre falls inside the polygon, silently dropping the boundary. For thin or linear assets — a pipeline corridor, a riverside plant — the boundary is most of the site.
• Never score at ST_Centroid. The centroid of a C-shaped or ring-shaped site (a campus around a lake, a refinery around a tank farm) falls outside the footprint. You end up scoring land the insured doesn't own. The notebook counts how often this happens on a synthetic book; run that check on yours before trusting any centroid-based number.

Area ratios are taken in degrees, which is fine for a ratio within one site — the latitude distortion cancels. For absolute m² use a GEOGRAPHY or an equal-area projection.

Pick the resolution to match the scoring model's grid, not your gut. Res 8 cells are about 0.74 km². If the vendor's flood model runs at 90 m, res 8 is too coarse; if their climate model runs at 25 km, res 8 is wastefully fine.

Step 2 — Deduplicate and check the cache

CREATE TABLE IF NOT EXISTS silver_cell_score_cache (
  h3_cell BIGINT, peril STRING, scenario STRING, horizon_year INT,
  score DOUBLE, model_version STRING, fetched_at TIMESTAMP
) CLUSTER BY (h3_cell, peril);

CREATE OR REPLACE TABLE work_cells_to_score AS
SELECT d.h3_cell,
       st_x(st_geomfromwkt(h3_centeraswkt(d.h3_cell))) AS lon,
       st_y(st_geomfromwkt(h3_centeraswkt(d.h3_cell))) AS lat
FROM   (SELECT DISTINCT h3_cell FROM silver_object_cell) d
LEFT ANTI JOIN (
       SELECT DISTINCT h3_cell FROM silver_cell_score_cache
       WHERE  model_version = 'v1.4.0') c
  ON   c.h3_cell = d.h3_cell;

The anti-join is also your resumability. If the fetch dies at 70%, re-run the job: everything already landed is skipped. No checkpoint files, no manual bookkeeping.

Step 3 — Fetch only what's missing, in parallel and politely

For the cells still unscored, fan out across executors with mapInPandas, and within each executor with asyncio. Batch to the vendor's cap, bound concurrency, and back off on 429/503.

import asyncio, httpx, pandas as pd

API_URL, BATCH_CAP, PER_TASK_CONCURRENCY, MAX_RETRIES = "https://…/score", 1000, 8, 5

async def _score_batch(client, sem, batch):
    async with sem:
        for attempt in range(MAX_RETRIES):
            r = await client.post(API_URL, json={"locations": batch})
            if r.status_code in (429, 503):
                await asyncio.sleep(0.2 * 2 ** attempt)
                continue
            r.raise_for_status()
            return r.json()["results"]      # flatten to one row per cell × peril × scenario × horizon
        return []                           # left unscored; the next run's anti-join retries it

async def _score_all(locs):
    sem = asyncio.Semaphore(PER_TASK_CONCURRENCY)
    batches = [locs[i:i + BATCH_CAP] for i in range(0, len(locs), BATCH_CAP)]
    async with httpx.AsyncClient(timeout=30) as client:
        chunks = await asyncio.gather(*[_score_batch(client, sem, b) for b in batches])
    return [row for c in chunks for row in c]

def score_partition(pdfs):
    for pdf in pdfs:
        locs = [{"id": int(c), "lon": lo, "lat": la}
                for c, lo, la in zip(pdf.h3_cell, pdf.lon, pdf.lat)]
        rows = asyncio.run(_score_all(locs))
        if rows:
            yield pd.DataFrame(rows)

FETCH_PARTITIONS = 8   # global in-flight calls = FETCH_PARTITIONS × PER_TASK_CONCURRENCY

(spark.table("work_cells_to_score")
      .repartition(FETCH_PARTITIONS)
      .mapInPandas(score_partition,
                   "h3_cell long, peril string, scenario string, horizon_year int, score double")
      .selectExpr("*", "'v1.4.0' AS model_version", "current_timestamp() AS fetched_at")
      .write.mode("append").saveAsTable("silver_cell_score_cache"))

Note the knob: global concurrency is partitions × per-task semaphore. Set it from the vendor's contracted limit, not from cluster size. Twenty idle executors hammering a 16-call limit only earns you 429s.

Step 4 — Fan scores back out to the object (gold)

Different consumers need different aggregates, so publish all three:

CREATE OR REPLACE TABLE gold_risk_object_score
CLUSTER BY (portfolio_id, peril) AS
SELECT c.risk_object_id, c.portfolio_id,
       s.peril, s.scenario, s.horizon_year,
       MAX(s.score)                                       AS score_worst_case,     -- underwriting
       SUM(s.score * c.weight) / NULLIF(SUM(c.weight), 0) AS score_area_weighted,  -- portfolio roll-up
       PERCENTILE_APPROX(s.score, 0.95)                   AS score_p95,            -- tail view
       COUNT(*)                                           AS contributing_cells,
       s.model_version
FROM   silver_object_cell c
JOIN   silver_cell_score_cache s
  ON   s.h3_cell = c.h3_cell AND s.model_version = 'v1.4.0'
GROUP BY ALL;

Publishing only the area-weighted mean systematically understates concentration on large sites — the worst corner of a five-kilometre plant is exactly what an underwriter needs to assess.

Going to zero calls: bringing the scoring in-house

Deduplication shrinks the API. Whether you can delete it depends on what is actually behind the endpoint. There are three honest cases.

Case A — the model is really a grid of precomputed values. Very often the "calculation" behind a hazard or demographic API is a lookup into rasters the provider has already computed. If they will license the grid itself — as files, via Delta Sharing, or through Databricks Marketplace — load it once, index it to H3 at your chosen resolution, and the scoring step becomes a join:

-- Hazard grid, pre-aggregated to H3 once per model release
SELECT c.risk_object_id, g.peril, g.scenario, g.horizon_year,
       MAX(g.score)                                       AS score_worst_case,
       SUM(g.score * c.weight) / NULLIF(SUM(c.weight), 0) AS score_area_weighted
FROM   silver_object_cell c
JOIN   silver_hazard_grid_h3 g USING (h3_cell)
GROUP BY ALL;

Zero network calls, Photon-speed, and every score lineaged in Unity Catalog. Raster-to-H3 conversion is a one-off batch job per model release — GeoBrix's RasterX or a GDAL-based job handles it.

Case B — the logic is yours, wrapped in a service. The model was written in-house years ago in .NET or Java and exposed as an API for reuse. Port it. Most scoring logic is arithmetic over a handful of inputs; express it as SQL, or as a vectorised pandas UDF if it's genuinely procedural. Keep the service's test vectors and assert the ported version reproduces them to the decimal before switching over. A JVM library can also run in-cluster as a UDF on classic compute, if a port isn't practical.

Case C — the model is the vendor's IP and stays behind the API. Keep the API, but now it is called once per new distinct cell per model version — not once per object per run. That is a different commercial and operational conversation, and usually a much better one.

One caution for Case C: read the licence before you build the cache. Many data contracts prohibit persisting results beyond a session, or charge per risk object rather than per call. A cell-level cache shared across portfolios is technically elegant and may be contractually forbidden. Get that answered first.

Compute: what to run each stage on

The stages have very different profiles, so don't run them all on one cluster shape.

StageProfileRecommended compute
1. Geometry resolutionCPU-heavy, vectorised, pure SQLServerless SQL warehouse or Photon job cluster, DBR 17.3 LTS. Photon is mandatory for h3_*
2. Dedup + cache anti-joinShuffle-heavy joinSame as stage 1; liquid clustering on h3_cell keeps it efficient
3. API fetch (Case C only)I/O-bound, mostly waitingA small classic job cluster. Size to the vendor's concurrency, not your data
4. Fan-out to goldJoin + aggregateServerless SQL or the stage 1 cluster
Grid ingest (Case A)One-off raster processingClassic cluster with GeoBrix/GDAL, per model release only

 

A few settings that earn their keep:

• Liquid clustering — CLUSTER BY (h3_cell) on the object-cell and cache tables, CLUSTER BY (portfolio_id, peril) on gold. Spatially adjacent cells share parent prefixes, so clustering on the cell id gives you data skipping by geography with no extra work.
• Let AQE handle skew. City-centre cells hold thousands of objects; rural ones hold one. Keep adaptive query execution and skew-join handling on (they're the default) rather than hand-salting.
• Don't scale the fetch cluster to the data. In stage 3, eight workers at full vendor concurrency finish at the same time as eighty — and the eighty cost ten times as much. This is where I've seen the most DBUs wasted.
• Split into tasks in one Lakeflow job so each stage gets the right compute and a failed fetch retries alone, without recomputing geometry.
• Avoid Python UDFs for geometry. Shapely-in-a-UDF serialises every row across the JVM/Python boundary. Native ST_* and h3_* stay inside Photon.

Results — and what they cost in accuracy

I tested the pattern on a synthetic 500,000-object portfolio, clustered around 400 urban centres, with 30% polygons and a few multi-kilometre industrial sites. The mock API had a 1,000-object batch cap, 16 concurrent calls, 250 ms latency and a 2% error rate. The companion notebook measures call count, wall clock time, storage and accuracy at runtime, so you can reproduce the numbers on your own cluster.

A speed-up without an error bar is not a result, so the notebook also reports what the H3 approximation costs:

  • Mean, p95 and p99 absolute score error against an exact evaluation
  • Boundary flips: objects whose score changes by more than 10 points because they sit across a sharp hazard edge
  • The centroid bug: how many polygons have an ST_Centroid that falls outside their own footprint

The error tail comes almost entirely from objects sitting on a sharp boundary, such as a flood-plain edge or a coastal surge line. Raising the resolution shrinks it at the cost of cache hit rate. That trade-off is the real engineering decision, and it should be made against the scoring model’s native grid, not chosen for speed.

The caveat you must state

The deduplication ratio depends on how clustered your portfolio is. A dense urban book will see a much bigger reduction than a sparse agricultural one. Run the notebook at a few cluster densities (it’s one parameter) to see where your own portfolio fits.

And be precise about the claim. This replaces the geometry pipeline and the call volume around a scoring model. It does not replace anyone’s catastrophe model. Claim the first loudly and the second never.

The takeaway

For years the default was to keep the data in the lakehouse, keep the logic behind somebody’s API, and write a loop to shuttle between them one record at a time. That loop quietly became the slowest, flakiest and most expensive part of the pipeline.

Native Spatial SQL and H3 change the deal:

  • Resolve geometry where the data lives.
  • Make the grid cell, not the object, the unit of work.
  • Cache by cell and model version.
  • Bring the model in as data where you can, and call the API only for what is genuinely new where you can’t.

The fastest API call is the one you never make.

The companion notebook runs end to end on DBR 17.3 LTS with Photon, with no third-party libraries. It includes a synthetic portfolio, a mock API with real-world limits, a timing harness and accuracy checks. Swap the mock for your endpoint and set the limits to your contract to get your own numbers. Next up: converting vendor hazard rasters to H3 grids at scale, and serving per-object scores to underwriting apps with sub-second latency.

References

#Databricks SQL #Photon #Unity Catalog #Delta Lake #Delta Sharing #Databricks Marketplace #Lakeflow Jobs #Spatial SQL #H3 #Geospatial #Insurance #Performance #Best Practices

 

 

0 REPLIES 0