---
slug: streaming-50k-150k-vehicles-one-jvm
title: "Streaming 50,000–150,000 Live Vehicles to 1,000 Viewports on One JVM"
date: "2026-12-05"
tags: Clojure, JVM, Performance, Caffeine, Geospatial, Real-Time
summary: "How a single JVM serves 50,000–150,000 moving vehicles to 500–1,000 concurrent map viewports within a 10 Hz budget without Redis, Kafka, or per-client spatial scans — using packed 64-bit Web Mercator slippy-tile pyramids, zoom-adaptive cadence gates, and lock-free two-tier Caffeine footprint caches."
demo_url: "https://qtga-transit.quantoga.com/"
demo_label: "Open Live Transit Radar (desktop browser recommended)"
preview_video_dark: "/img/demos/transit-dark.webm"
preview_video_light: "/img/demos/transit-light.webm"
preview_poster_dark: "/img/demos/transit-dark.webp"
preview_poster_light: "/img/demos/transit-light.webp"
preview_alt: "Live multi-modal geospatial radar showing buses, trams, metro, trains, planes, and ferries streaming into a viewport-culled MapLibre client"
preview_caption: "4.5s live capture of the viewport-culled geospatial radar (buses, trams, trains, ferries, planes). Interactive demo linked at right (desktop browser recommended)."
---

Most real-time map and fleet backends hit a wall long before the network saturates. The bottleneck is rarely the WebSocket write loop — it is **re-filtering, re-projecting, and re-diffing the world state for every connected viewer on every tick**.

If you have `50,000` moving entities and `1,000` concurrent browser viewports at `10 Hz`, a naive per-viewer bounding-box scan evaluates **500 million entity-viewport checks per second**. Teams usually respond by adding Redis Geo, Kafka fan-out tiers, and a fleet of stateless Node/Go projection workers — multiplying operational latency and cloud spend before fixing the algorithmic shape of the problem.

This teardown walks through the three data-structure and caching patterns we use in our real-time Clojure/JVM platform to keep **50,000 to 150,000 live vehicles** streaming to **500 to 1,000 independent viewports on a single JVM** inside a `100 ms` (`10 Hz`) tick budget — including a **1.65 ms average tick** when upstream feeds update outside most viewers' fields of view. Every pattern below is standalone and directly portable to any JVM codebase.

---

## 1. The Three-Tier Acceleration Architecture

Instead of scanning entities per viewer, we split projection into three orthogonal tiers that compose over one immutable server state tree:

1. **Packed 64-bit Slippy-Tile Pyramid (`z=4`, `z=8`, `z=12`)**: Vehicles are indexed once per tick into three Web Mercator zoom levels using bit-packed `long` keys — zero string allocations and `O(|FOV tiles|)` lookup.
2. **Zoom-Adaptive Cadence Gating**: Macro viewers (`z < 6`) do not need `10 Hz` pixel jitter. Gating macro views to `~1 Hz` and regional views (`6 <= z < 10.5`) to `~2.5 Hz` skips `69–75%` of ticks in `O(1)` while still waking immediately on any pan, zoom, or filter change.
3. **Lock-Free Two-Tier Caffeine Footprint Caching**: Each viewport records the exact set of slippy-tile keys intersecting its bounding box. On the next tick, if none of those specific tile references changed (`identical?` pointer check), the cache returns the **exact same immutable projection reference** — letting the downstream diff engine skip diffing and serialization in `O(1)`.

---

## 2. Pattern 1: Zero-Allocation 64-Bit Slippy-Tile Keys

String keys like `"12/2331/1184"` look harmless until you allocate millions of them per second inside viewport intersection loops and hash-map lookups. Packing `(z, tx, ty)` into a single 64-bit `long` fits cleanly inside both JVM `long` and JavaScript IEEE-754 safe integers (`<= 2^53`) for zoom levels `0..15`:

```clojure
(def ^:const deg->rad (/ Math/PI 180.0))
(def ^:const pi Math/PI)

(defn lon->tx ^long [^long z ^double lon]
  (let [n (double (bit-shift-left 1 z))
        raw (long (Math/floor (* (/ (+ lon 180.0) 360.0) n)))]
    (max 0 (min (dec (bit-shift-left 1 z)) raw))))

(defn lat->ty ^long [^long z ^double lat]
  (let [n (double (bit-shift-left 1 z))
        clat (max -85.05112878 (min 85.05112878 lat))
        rad (* clat deg->rad)
        merc (Math/log (+ (Math/tan rad) (/ 1.0 (Math/cos rad))))
        raw (long (Math/floor (* 0.5 (- 1.0 (/ merc pi)) n)))]
    (max 0 (min (dec (bit-shift-left 1 z)) raw))))

(defn tile-key ^long [^long z ^long tx ^long ty]
  (bit-or (bit-shift-left z 32)
          (bit-shift-left (bit-and tx 0xFFFF) 16)
          (bit-and ty 0xFFFF)))
```

We maintain three zoom levels in the spatial index:
- **`z=4` (~2,500 km cells)**: Pre-aggregated continental clusters (count, centroid, average speed, per-mode and per-scope sub-counts).
- **`z=8` (~156 km cells)**: Pre-aggregated regional clusters. When a viewer zooms in and total vehicles in the visible `z=8` cells drop below their uncluster threshold, the projector seamlessly drops to street-level vehicles.
- **`z=12` (~9.8 km cells)**: Individual vehicle buckets for street-level viewports (`z >= 10.5`).

Because `z=4` and `z=8` cells store pre-aggregated counts broken down by scope and transport mode, **RBAC and mode filtering at macro/regional zoom runs in `O(|scopes in tile|)` without ever touching individual vehicle maps**.

---

## 3. Pattern 2: Two-Tier Lock-Free Caffeine Footprint Cache

A naive cache keyed by `[world-state viewport-spec]` has two fatal flaws in a high-frequency JVM server:
1. Putting a large persistent map in a cache key forces expensive `.hashCode`/`.equals` walks.
2. Mutating a single vehicle in Tokyo changes the root `world-state` reference, invalidating cached projections for viewers looking at Helsinki or Oslo.

The fix is a **two-tier pointer-identity (`identical?`) footprint cache** backed by [Caffeine](https://github.com/ben-manes/caffeine), running all computation **outside** `ConcurrentHashMap` bucket locks so parallel worker threads see zero `MonitorEnter` contention:

- **Tier 1 (`O(1)`)**: Check if the root container (`tiles-map`) is `identical?` and `deps` (viewport bounds, zoom, RBAC scope set, filters) are `=` to the cached entry. If so, return the cached value immediately.
- **Tier 2 (`O(|FOV tiles|)`)**: Even if the root `tiles-map` changed (because vehicles moved somewhere else on Earth), check only the viewer's watched tile keys via `(identical? (get tiles-map k) prev-ref)`. If every watched tile still points to the exact same persistent map node, refresh the root pointer and return the **exact `identical?` cached projection**.

```clojure
(ns example.footprint-cache
  (:import [com.github.benmanes.caffeine.cache Cache Caffeine]
           [java.util.concurrent TimeUnit]))

(defn make-footprint-cache
  "Lock-free two-tier footprint cache over an immutable map of spatial tiles.
   Computes outside Caffeine bucket locks and returns the exact `identical?`
   projection whenever edits occur outside a viewer's watched tile keys."
  [{:keys [maximum-size expire-after-minutes]
    :or {maximum-size 4096 expire-after-minutes 5}}]
  (let [^Cache c (-> (Caffeine/newBuilder)
                     (.maximumSize (long maximum-size))
                     (.expireAfterAccess (long expire-after-minutes) TimeUnit/MINUTES)
                     (.build))]
    (fn [cache-key container deps compute-fn]
      (let [entry (.getIfPresent c cache-key)]
        (cond
          ;; Tier 1: root container and viewport deps unchanged -> O(1) hit
          (and entry
               (identical? container (:root entry))
               (= deps (:deps entry)))
          (:value entry)

          ;; Tier 2: root changed, verify only this viewport's watched tile refs
          (and entry
               (= deps (:deps entry))
               (every? (fn [[k prev-ref]]
                         (identical? (get container k) prev-ref))
                       (:watched entry)))
          (do
            (.put c cache-key (assoc entry :root container))
            (:value entry))

          ;; Cache miss: compute outside any lock and capture watched tile refs
          :else
          (let [{:keys [value watch-keys]} (compute-fn)
                watched (mapv (fn [k] [k (get container k)]) watch-keys)]
            (.put c cache-key {:root container
                               :deps deps
                               :watched watched
                               :value value})
            value))))))
```

Notice the downstream multiplier: because Tier 1 and Tier 2 return the **exact same JVM object reference** (`identical?`), our state-sync diff engine short-circuits in `O(1)` — **0 tree diffs, 0 CBOR/JSON serializations, and 0 WebSocket frames** for every untouched viewport.

---

## 4. Pattern 3: Zoom-Adaptive Cadence Windows

Even when vehicles inside a viewer's bounding box *do* move, a viewer zoomed out to continental scale (`z=4`) cannot perceive 100 ms sub-pixel shifts. We pair the footprint cache with a time-window cadence gate keyed by `[viewport-id deps]`:

- `z < 6` (macro): valid for `~1000 ms` (`~1 Hz`)
- `6 <= z < 10.5` (regional): valid for `~400 ms` (`~2.5 Hz`)
- `z >= 10.5` (street): valid for `~100 ms` (`~10 Hz`)

Because `deps` includes the normalized bounds, zoom, active transport modes, search text, and RBAC user scope, **any interactive pan, zoom, filter toggle, or persona switch immediately misses the cadence window and renders on the very next frame** — zero sluggishness when interacting, massive CPU savings while watching.

---

## 5. Empirical Benchmarks & Cgroup v2 Provenance

All numbers below were measured on a single modest 2019 desktop-class host running **OpenJDK 25.0.4** (`-XX:+UseCompactObjectHeaders`) with **Netty native `epoll`** on Linux (`7.3.4`, `TCP BBR`, `AMD Ryzen 9 3900X 12C/24T`, `31.3 GB RAM`). Capacity ceilings were enforced with hard Linux **cgroup v2** limits (`CPUQuota` + `MemoryMax`) matching real cloud VMs and single dedicated servers.

### A. Micro-Benchmark: 50,000 Vehicles × 100 Mixed-Zoom Viewports

| Scenario | Avg Latency | p99 Latency | `identical?` Skips | What Happened |
|---|---:|---:|---:|---|
| **Distant-feed tick** | **1.65 ms** | **2.37 ms** | **79 / 100** | Upstream feed updated tiles outside 79 viewports' FOVs; Tier-2 footprint cache skipped diffing & encoding |
| **Mixed-zoom cadence tick** | **6.68 ms** | **18.89 ms** | **72 / 100** | Macro/regional viewers held within cadence windows; street viewers projected from `z=12` |
| **Full cold refresh** | **7.48 ms** | **8.97 ms** | 0 / 100 | All 100 viewports forced to recompute simultaneously |

### B. Entry Cloud VM Envelope (`2 vCPU / 4 GB RAM`, `CPUQuota=200%`, `-Xmx2800m`)

Equivalent to a ~$28/mo DigitalOcean `s-2vcpu-4gb-amd` or ~$55/mo AWS `c5a.large`:

| Vehicles | Viewports | Cadence Tick Avg | Cadence Tick p99 | Full Refresh Avg | Resident RSS | Within 10 Hz (`100 ms`)? |
|---:|---:|---:|---:|---:|---:|:---:|
| 25,000 | 100 | 25.06 ms | 67.17 ms | 37.37 ms | 835.5 MB | Yes |
| 50,000 | 100 | 31.90 ms | 105.42 ms | 38.74 ms | 1,275.5 MB | Yes |
| 50,000 | 250 | 58.95 ms | 102.25 ms | 65.58 ms | 1,431.2 MB | Yes |
| **50,000** | **500** | **90.99 ms** | **101.41 ms** | **138.08 ms** | **1,722.5 MB** | **Yes (Peak)** |
| 100,000 | 500 | 147.86 ms | 201.81 ms | 227.17 ms | 1,445.8 MB | No (saturation cliff) |

On a $28/month 2-vCPU box, **50,000 live vehicles × 500 concurrent viewports** stays inside the 100 ms tick budget (`375 / 500` viewports short-circuited via `identical?` per tick) at **1.72 GB RSS**. Pushing to 100,000 vehicles × 500 viewports crosses the 100 ms budget cleanly — no silent OOM or GC death spiral.

### C. Dedicated Node Envelope (`8C / 16T / 16 GB RAM`)

| Vehicles | Viewports | Cadence Tick Avg | Cadence Tick p99 | Full Refresh Avg | Resident RSS | Within 10 Hz (`100 ms`)? |
|---:|---:|---:|---:|---:|---:|:---:|
| 50,000 | 100 | 5.64 ms | 6.48 ms | 8.96 ms | 1,313.4 MB | Yes |
| 50,000 | 500 | 16.34 ms | 24.50 ms | 26.11 ms | 2,548.5 MB | Yes |
| 100,000 | 500 | 25.42 ms | 48.49 ms | 36.36 ms | 3,648.2 MB | Yes |
| 100,000 | 1,000 | 47.17 ms | 63.07 ms | 71.09 ms | 4,202.2 MB | Yes |
| **150,000** | **1,000** | **65.19 ms** | **97.40 ms** | **86.68 ms** | **4,776.1 MB** | **Yes** |

On a single 8-core dedicated server, **150,000 live vehicles × 1,000 concurrent viewports** holds **65.19 ms avg** (`97.40 ms` p99, `746 / 1,000` `identical?` skips per tick, `4.78 GB` RSS, `2.11 GB` heap) with headroom to spare.

---

## 6. Practical Takeaways & Trade-Offs

- **Optimize data identity before adding distributed queues**: Returning `identical?` references from a localized footprint cache eliminates diffing, serialization, and socket traffic simultaneously.
- **Avoid `ConcurrentHashMap.compute` around heavy projections**: Computing inside bucket locks serializes virtual or ForkJoin threads across unrelated hash collisions. Read-then-put with Caffeine keeps parallel projection fan-out lock-free.
- **Know where single-JVM projection stops**: If you need `10,000+` street-level viewers all zoomed into the exact same square kilometer at `60 Hz` with unbounded historical trajectory queries, shard by geographic region or pair this hot-state engine with a columnar analytical store.

Explore the live geospatial radar yourself at [qtga-transit.quantoga.com](https://qtga-transit.quantoga.com/) *(desktop browser recommended)* — toggle between live Nordic/global feeds and 50,000 simulated vehicles, switch RBAC personas, and watch the viewport cache hit rate live in the HUD.
