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:
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 µmwavelength 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:
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,864bytes (~1.5 MiB uncompressed) -
Half-precision 16-bit float (
float16):6 x 256 x 256 x 2=786,432bytes (~768 KiB, 50% smaller over the network) -
Pixel hygiene mask (
uint8):256 x 256 x 1=65,536bytes
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:
-
SQLite disk stores only canonical
gzip_float32cubes andgzip_uint8hygiene masks. - When a slow-network client requests
precision=float16, the service converts thefloat32cube tofloat16on the fly (10.12 msincluding gzip) and caches that wire-ready gzippedfloat16blob inside our in-process_MemoryLruCache(1024 MBRAM budget infly.toml). - To make evicting or refreshing all keys belonging to one
grid_keyfast,_MemoryLruCachemaintains a reverse tag index (_tag_to_keys) so invalidating a patch deletes its manifest, catalogs,float32, andfloat16entries inO(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
MapLRU): Stores decodedFloat32Array[][]cubes so every slider drag or Blink/Subtract toggle executes synchronously in< 5 ms. -
Tier 2 (
IndexedDB): Persists binaryArrayBuffers across tab reloads with a 7-day TTL synced passively fromX-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
float16buffers takes2.03 msp50, rendering RGBA canvas frames takes1.54 msp50, andClientPatchCachereaches up to an80.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/monthFly.ioshared-cpu-2xbudget at 20 connections/minute from15.0hours (18,042sessions) with cold browsers up to60.2hours (72,270sessions).
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.


Top comments (5)
The piece that stopped me is the time-invariant decay trick — storing popularity_rank = ln(S) + λ * (now - t0) so wall-clock time cancels out and SQLite can rank decayed popularity with a static B-tree index and zero background jobs on a machine that scales to zero. That is the kind of constraint-driven design that only appears when you cannot run a timer every minute, and it is the most portable idea in the post.
The 4-byte HMAC ring is the other one I will borrow: a 128-slot ring, 512 bytes per patch, daily-rotated key that never touches disk, so an F5-spammer cannot promote a patch into the protected segment. My one worry is the other end of the same mechanism — a 4-byte truncated token across a 128-slot ring must collide sometimes, so two different visitors could look like one. Did you measure how often that happens at your 241-patch stress scale, or is the collision rate small enough that the probationary/protected boundary just absorbs it?
For Part 3, the question I would love to see answered is the stampede one: when those 20-30% cold misses hit the 2-vCPU server at once, what stops ten concurrent requests for the same uncached patch from each building it?
Thanks for reading! Necessity really was the mother of innovation here. Not being able to run a background decay cron job pushed straight for that time-anchored rank formula.
On the 4-byte ring, I didn't measure collisions because the ring stores up to 128 exact 32-bit tokens. Against a full 128-slot ring, a random 32-bit hash collision is
128/2^32 ≈ 3×10^(−8)(~1 in 33.5 million).What does collide in practice is the input used to generate the keys. Two users on identical devices behind the same NAT IP hash to the exact same IP + User-Agent token. Undershooting the popularity rank a bit is fine for eviction since the frontend also caches patches locally. This tradeoff is something that was not compromisable in limiting network requests, which I discuss in Part 3! Along with how we handle cold-miss stampedes on the 2-vCPU container. I am still brushing off a few details but it will be published later today.
two clicks a hundredth of a degree apart hitting the same bucket is the whole trick. continuous coordinates make terrible cache keys.
Thanks for the read. I am basically taking advantage of the principal of locality to group data into manageable chunks.
locality doing the heavy lifting here. the bucket trick is what makes the rest of the tiers pay off.