Quantoga

Streaming 50,000–150,000 Live Vehicles to 1,000 Viewports on One JVM

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.

Published 2026-12-05 9 min read Raw Markdown
ClojureJVMPerformanceCaffeineGeospatialReal-Time
4.5s live capture of the viewport-culled geospatial radar (buses, trams, trains, ferries, planes). Interactive demo linked at right (desktop browser recommended). Open Live Transit Radar (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:

(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, 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.
(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

ScenarioAvg Latencyp99 Latencyidentical? SkipsWhat Happened
Distant-feed tick1.65 ms2.37 ms79 / 100Upstream feed updated tiles outside 79 viewports' FOVs; Tier-2 footprint cache skipped diffing & encoding
Mixed-zoom cadence tick6.68 ms18.89 ms72 / 100Macro/regional viewers held within cadence windows; street viewers projected from z=12
Full cold refresh7.48 ms8.97 ms0 / 100All 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:

VehiclesViewportsCadence Tick AvgCadence Tick p99Full Refresh AvgResident RSSWithin 10 Hz (100 ms)?
25,00010025.06 ms67.17 ms37.37 ms835.5 MBYes
50,00010031.90 ms105.42 ms38.74 ms1,275.5 MBYes
50,00025058.95 ms102.25 ms65.58 ms1,431.2 MBYes
50,00050090.99 ms101.41 ms138.08 ms1,722.5 MBYes (Peak)
100,000500147.86 ms201.81 ms227.17 ms1,445.8 MBNo (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)

VehiclesViewportsCadence Tick AvgCadence Tick p99Full Refresh AvgResident RSSWithin 10 Hz (100 ms)?
50,0001005.64 ms6.48 ms8.96 ms1,313.4 MBYes
50,00050016.34 ms24.50 ms26.11 ms2,548.5 MBYes
100,00050025.42 ms48.49 ms36.36 ms3,648.2 MBYes
100,0001,00047.17 ms63.07 ms71.09 ms4,202.2 MBYes
150,0001,00065.19 ms97.40 ms86.68 ms4,776.1 MBYes

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 (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.