This is Part 2 of a 3-part series on the post-hackathon backend and UX engineering behind Star Hunters (live app). Part 1 covered the hackathon problem and 3-layer architecture. Here, I dive into spatial_cache.py and its browser counterpart clientPatchCache.ts.

Background: Why Caching Is User Experience

"Good design, when it's done well, becomes invisible. It's only when it's done poorly that we notice it." (Jared Spool)

When a user opens Star Hunters' detailed Blinker view, they see a dark sky canvas with a wavelength slider, Blink/Subtract buttons, pinned object callouts, and a quality selector in the top bar:

Star Hunters Blinker view showing instant client-side frame blinking, pinned brown-dwarf callout, wavelength slice slider, and adaptive Auto/Full precision controls

Nobody looking at that screen thinks about SQLite Write-Ahead Logging (WAL), IEEE-754 half-precision floats, or cache eviction math. They only notice the absence of friction:

  • Dragging the 0.75-5.0 µm wavelength slider updates the canvas in under 2 milliseconds with zero network spinners.
  • Toggling between Blink and Subtract happens instantaneously.
  • Exploring on a congested mobile link still loads frames instead of timing out at 15 seconds.

When I audited our initial AI-generated hackathon code after November 15, the cache was a basic single-table SQLite lookup. Over two weeks of profiling and stress testing, I rebuilt it into a coordinated 4-tier caching pipeline spanning browser RAM, IndexedDB, backend RAM, and popularity-scored SQLite storage:

4-Tier Spatial Cache & Invisible UX Pipeline

1. Coordinate Quantization: Turning Continuous Float Keys into Shared Buckets

The Context

In a typical CRUD app, cache keys are discrete IDs like user:42. On a 3D sky globe, clicks arrive as continuous floating-point coordinates such as (133.8124°, -7.2419°). If a second user clicks (133.7981°, -7.2582°) (less than a hundredth of a degree away, looking at the exact same 5-arcminute sky tile where 1 degree equals 60 arcminutes), a naive stringified key (f"{ra}_{dec}") treats them as two completely different misses and triggers duplicate multi-second image builds.

The Fix

Both the backend (spatial_cache.py) and frontend (wcsViewport.ts) snap incoming coordinates to a 0.05° (3-arcminute) grid before checking any cache tier:

# Source: https://github.com/Eddy-Odero/star-hunters/blob/3a49453/backend/app/services/spatial_cache.py#L265-L288 GRID_STEP_DEG = 0.05 # 3 arcminutes (1/20th of a degree) def compute_grid_key(ra: float, dec: float, fov_arcmin: float = 5.0) -> tuple[str, float, float]: ra_wrapped = ra % 360.0 dec_clamped = max(-90.0, min(90.0, dec)) ra_snapped = round(round(ra_wrapped / GRID_STEP_DEG) * GRID_STEP_DEG, 2) % 360.0 dec_snapped = round(round(dec_clamped / GRID_STEP_DEG) * GRID_STEP_DEG, 2) grid_key = f"ra{ra_snapped:.2f}_dec{dec_snapped:.2f}_fov{fov_arcmin:.1f}" return grid_key, ra_snapped, dec_snapped 

Both clicks resolve deterministically to ra133.80_dec-7.25_fov5.0, turning near-misses into instant cache hits.

2. Store 32-Bit Once on Disk, Downsample 16-Bit on the Fly in RAM

The Context

Each timestamped pass of a sky tile holds 6 detector images at 256 x 256 pixels:

  • Full 32-bit float (float32): 6 x 256 x 256 x 4 = 1,572,864 bytes (~1.5 MiB uncompressed)
  • Half-precision 16-bit float (float16): 6 x 256 x 256 x 2 = 786,432 bytes (~768 KiB, 50% smaller over the network)
  • Pixel hygiene mask (uint8): 256 x 256 x 1 = 65,536 bytes

Midway through my post-hackathon refactors (a0ecd9b), I tried pre-generating and storing both compressed float32 and float16 blobs in SQLite. On a constrained 2 GB Fly.io persistent volume (SQLITE_MAX_CACHE_MB = 1536), storing both representations ate ~50% extra disk space per patch, meaning we could cache 33% fewer sky tiles overall.

The Fix

In put_sky_patch and get_frame_bytes, I separated canonical persistence from ephemeral wire formatting:

  1. SQLite disk stores only canonical gzip_float32 cubes and gzip_uint8 hygiene masks.
  2. When a slow-network client requests precision=float16, the service converts the float32 cube to float16 on the fly (10.12 ms including gzip) and caches that wire-ready gzipped float16 blob inside our in-process _MemoryLruCache (1024 MB RAM budget in fly.toml).
  3. To make evicting or refreshing all keys belonging to one grid_key fast, _MemoryLruCache maintains a reverse tag index (_tag_to_keys) so invalidating a patch deletes its manifest, catalogs, float32, and float16 entries in O(k) time instead of scanning thousands of RAM entries:
# Simplified from spatial_cache.py # Full source: https://github.com/Eddy-Odero/star-hunters/blob/3a49453/backend/app/services/spatial_cache.py#L140-L153 class _MemoryLruCache: @staticmethod def _grid_tag_for_key(key: str) -> str | None: # Keys follow "<kind>:<grid_key>[:<filename>:<dtype>]" if key.startswith(("manifest:", "catalogs:", "frame_raw:", "frame_gz:")): parts = key.split(":", 2) return parts[1] if len(parts) >= 2 and parts[1] else None return None def delete_tag(self, grid_key: str) -> None: """Evict manifest, catalogs, float32, and float16 blobs for one patch in O(k).""" with self._lock: for key in self._tag_to_keys.pop(grid_key, ()): if evicted := self._entries.pop(key, None): self._current_bytes -= len(evicted) 

3. Segmented LRU & Time-Invariant Logarithmic Decay

The Context: Scan Pollution

Standard Least-Recently-Used (LRU) eviction has a classic blind spot called scan pollution: if one curious user pans across 300 random patches of empty sky, plain LRU happily evicts popular targets that dozens of other visitors are actively using, simply because those 300 one-off clicks have newer timestamps.

In caching literature, Segmented LRU (SLRU) solves this by splitting storage into a probationary segment (seen by only one visitor) and a protected segment (seen by two or more distinct visitors).

There was just one catch: our Fly.io machine scales to zero (auto_stop_machines = "suspend"). If a protected patch was popular two weeks ago, its popularity should decay over time, yet we cannot run a background timer every minute to decay rows in SQLite because that timer would prevent the VM from suspending (or stall on resume).

The Fix: Cancelling Current Time t Algebraically

Suppose a patch's decayed popularity score at any future time t follows exponential decay with rate λ, and SQLite needs to compare two patches A and B to decide which one is less popular:

Decayed score at time t: S(t) = S_last * exp(-λ * (t - t_last)) Ordering two patches A and B (taking natural log preserves order): S_A(t) < S_B(t) <=> ln(S_A) - λ * (t - t_A) < ln(S_B) - λ * (t - t_B) Add λ * (t - t0) to both sides (where t0 is a fixed epoch constant): ln(S_A) + λ * (t_A - t0) < ln(S_B) + λ * (t_B - t0) 

Current wall-clock time t cancels out completely. By storing popularity_rank = ln(S) + λ * (now - t0) on write in record_patch_hit, SQLite ranks decayed popularity at any future moment using a static B-tree index with zero background jobs:

# Source: https://github.com/Eddy-Odero/star-hunters/blob/3a49453/backend/app/services/spatial_cache.py#L936-L956 POPULARITY_EPOCH_T0 = 1_700_000_000.0 # Fixed anchor timestamp dt = max(0.0, now - last_popularity_ts) decayed_score = old_score * math.exp(-decay_lambda * dt) + 1.0 popularity_rank = math.log(decayed_score) + decay_lambda * (now - POPULARITY_EPOCH_T0) 

When SQLite crosses its 1536 MB cap, _prune_if_needed evicts Pass 1 probationary rows (distinct_visitors < 2) in oldest-last_accessed order first. If a single user clicks 300 obscure patches, their own probationary entries evict each other when the cache fills, leaving Pass 2 protected multi-visitor patches (distinct_visitors >= 2, ranked by popularity_rank) untouched unless Pass 1 is completely empty.

4. Counting Distinct Visitors Privately with 4-Byte HMAC Rings

To prevent a single user hitting F5 twenty times from promoting a patch into the protected multi-user tier, we needed visitor deduplication without storing raw IP addresses or setting tracking cookies.

For a tiny open-source project, storing raw IPs or managing cookies carries real baggage: IP addresses and persistent identifiers count as personally identifiable information (PII) under GDPR and similar privacy laws, pulling in privacy-policy declarations, cookie-consent banners, retention rules, and security liability if a SQLite volume ever leaked.

Instead, compute_visitor_token hashes (client_ip, user_agent) with an in-memory random 32-byte secret key rotated every UTC day (os.urandom(32), never written to disk) and truncates the HMAC-SHA256 digest to a 4-byte anonymous daily token (VisitorToken). Each patch stores a fixed-size 128-slot ring buffer (recent_visitors BLOB, capped at 512 bytes per patch):

# Simplified from spatial_cache.py # Full source: https://github.com/Eddy-Odero/star-hunters/blob/3a49453/backend/app/services/spatial_cache.py#L114-L128, #L453-L465 MAX_RING_BYTES = 128 * 4 # 128 tokens * 4 bytes = 512 bytes max def compute_daily_visitor_token(ip: str, user_agent: str, daily_ram_secret: bytes) -> bytes: # daily_ram_secret rotates via os.urandom(32) every UTC day and never touches disk payload = f"{ip}|{user_agent}".encode("utf-8") return hmac.new(daily_ram_secret, payload, hashlib.sha256).digest()[:4] def visitor_in_ring(ring: bytes, token: bytes) -> bool: return any(ring[i : i + 4] == token for i in range(0, len(ring) - 3, 4)) def append_visitor_ring(ring: bytes, token: bytes) -> bytes: combined = ring + token return combined[-MAX_RING_BYTES:] if len(combined) > MAX_RING_BYTES else combined 

Because the 32-byte HMAC key lives only in RAM and rotates daily, the 4-byte truncated slots cannot be reversed back into IP addresses, yet they cleanly separate genuine multi-user popularity from single-user refreshes.

5. Browser-Side Caching & Automatic Stall Downgrades

Even a 10 ms backend response still faces network latency on a 3G link. On the frontend, ClientPatchCache mirrors the two-tier pattern inside the browser:

  • Tier 1 (In-memory Map LRU): Stores decoded Float32Array[][] cubes so every slider drag or Blink/Subtract toggle executes synchronously in < 5 ms.
  • Tier 2 (IndexedDB): Persists binary ArrayBuffers across tab reloads with a 7-day TTL synced passively from X-Patch-TTL-Seconds.

Meanwhile, progressivePatchLoader.ts monitors live download throughput. In Auto quality mode, if a float32 binary frame stalls past 4.5 seconds (AUTO_FLOAT32_STALL_MS = 4500), it aborts the request and transparently retries ?precision=float16, halving payload size mid-flight so the user lands in the Blinker instead of staring at a timeout error:

// Simplified from progressivePatchLoader.ts // Full source: https://github.com/Eddy-Odero/star-hunters/blob/3a49453/frontend/src/services/progressivePatchLoader.ts#L294-L327 const STALL_GUARD_MS = 4_500; async function fetchEpochAdaptive(epochUrl: string, signal?: AbortSignal) { try { // Try full 32-bit precision first with a 4.5s stall guard return await fetchWithThroughput( `${epochUrl}?precision=float32`, Math.min(FRAME_TIMEOUT_MS, STALL_GUARD_MS), signal, ); } catch (err) { if (signal?.aborted) throw err; networkTracker.recordStall(); // Transparently retry 50%-smaller 16-bit half-precision payload return await fetchWithThroughput( `${epochUrl}?precision=float16`, FRAME_TIMEOUT_MS, signal, ); } } 

When checking local ClientPatchCache before fetching, loadLiveCoordinatesFlow checks float32 cache keys before float16 keys, ensuring a user who already cached full precision on Wi-Fi is never downgraded later on mobile.

6. Measured Results: Post-Hackathon Baseline vs. Current Pipeline

Using my airgapped loopback benchmark suite (profile_resources.py and run_stress_test.py), I compared our November 16 post-hackathon commit against the current caching pipeline in isolated subprocesses:

Isolated Operation Nov 16 Baseline Current Pipeline Measured Improvement
sqlite_put_sky_patch (gzip + WAL write) 35.40 ms / +1.45 MB RSS 36.87 ms / +1.06 MB RSS 27% lower peak RAM (dropped duplicate float16 row)
sqlite_get_frame_f16_gzip (SQLite -> float16 -> gzip) 14.60 ms wall 10.12 ms wall 31% faster (1.44x speedup)
end_to_end_cold_patch_1x (uncached build) 6,349.97 ms / +139.17 MB RSS 1,571.04 ms / +69.71 MB RSS 4.04x faster, 50% less peak RAM (~155x slower than SQLite hit)

Across our 5x5 concurrency-by-saturation stress matrix (241 unique sky patches, 2 to 40 concurrent workers):

  • 90.3% to 92.7% combined backend cache hit rate when working sets fit within 75%-97% of RAM, and 67.0% to 71.5% hit rate with zero errors even when the dataset oversubscribes SQLite disk capacity by 125%.
  • Sub-3ms client compute: Decoding float16 buffers takes 2.03 ms p50, rendering RGBA canvas frames takes 1.54 ms p50, and ClientPatchCache reaches up to an 80.85% repeat-session hit rate at 192 entries. Under steady repeat-visitor patterns (an optimistic upper-bound estimate on the high side), that stretches a $5/month Fly.io shared-cpu-2x budget at 20 connections/minute from 15.0 hours (18,042 sessions) with cold browsers up to 60.2 hours (72,270 sessions).

In Part 3, I'll tackle what happens when those 20%-30% cold cache misses hit our tiny 2-vCPU server all at once, and how backend_service.py uses thread-pool isolation, an aging priority semaphore, and independent per-provider I/O timeouts to keep interactive clicks fast under heavy load.