This is Part 3 (final) of a 3-part series on the post-hackathon engineering behind Star Hunters (live app). Part 1 covered the architecture and UI redesign, and Part 2 unpacked our 4-tier caching pipeline. Here, I dive into backend_service.py, spherex_coadd.py, and archival_resolver.py.

Background: When Fast async def Routes Secretly Block Each Other

"Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once." (Rob Pike)

One of the easiest traps in AI-generated FastAPI code is sprinkling async def and run_in_executor everywhere and assuming concurrency is "solved."

When I started stress-testing our post-hackathon server on a shared-cpu-2x (2048 MB RAM) Fly.io configuration, two completely different user actions were fighting over the exact same resources:

  1. Heavy Background Sky-Tile Builds (get_sky_patch_async): When a user pans onto an uncached sky coordinate, the server downloads up to 18 scientific images, aligns their camera projections onto a common 256 x 256 grid, and stacks them. Even after optimization, this burns hundreds of milliseconds of pure CPU and ~32-40 MB of transient RAM per worker.
  2. Interactive Clicks (get_spectrum & cached /frames): Inside the Blinker, clicking any object opens a 102-channel infrared brightness plot:

102-channel infrared spectrum inspector opened when clicking an object inside the Blinker

When a user clicks an object to inspect that plot, they expect an immediate UI response rather than a 6-second stall because three background sky-tile jobs clogged Python's single default ThreadPoolExecutor.

Over two weeks of studying Python concurrency, resource scheduling, and tail-latency resilience, I restructured StarHuntersBackendService around four cooperating mechanisms:

Concurrency, Per-Provider I/O Timeouts & Aging Semaphores

1. First, Eliminate Wasted CPU: Vectorizing Image Alignment (15.6x Faster)

The Context

Before tuning semaphores or thread pools, it pays to check why each worker is holding the CPU so long. In our November 16 baseline, stacking 18 rotated detector cutouts into 3 aligned passes took 4,865 ms of wall time (5,374 ms of CPU).

Profiling with profile_resources.py revealed why: the initial code ran general-purpose astronomical image reprojection three separate times per cutout (image, variance, and pixel-hygiene mask) and recomputed the spherical-to-pixel coordinate matrix from scratch even when all 6 detectors came from the exact same telescope pointing.

The Fix

In _reproject_cutout, I cached the projected (y_in, x_in) pixel lookup arrays per pointing signature (coord_cache[pointing_sig]) and sampled the image in a single C-level bilinear pass via scipy.ndimage.map_coordinates:

# Simplified from spherex_coadd.py # Full source: https://github.com/Eddy-Odero/star-hunters/blob/3a49453/backend/app/services/spherex_coadd.py#L314-L355 if pointing_sig not in coord_cache: # Compute expensive spherical -> detector pixel mapping once per telescope pointing world_ra, world_dec = target_wcs.pixel_to_world_values(TARGET_X_GRID, TARGET_Y_GRID) x_in, y_in = source_wcs.world_to_pixel_values(world_ra, world_dec) in_bounds = ( np.isfinite(x_in) & np.isfinite(y_in) & (x_in >= -0.5) & (x_in <= in_w - 0.5) & (y_in >= -0.5) & (y_in <= in_h - 0.5) ) y_safe = np.where(in_bounds, y_in, 0.0).astype(np.float32) x_safe = np.where(in_bounds, x_in, 0.0).astype(np.float32) yi = np.clip(np.rint(y_safe).astype(np.intp), 0, in_h - 1) xi = np.clip(np.rint(x_safe).astype(np.intp), 0, in_w - 1) coord_cache[pointing_sig] = (y_safe, x_safe, in_bounds, yi, xi) y_safe, x_safe, in_bounds, yi, xi = coord_cache[pointing_sig] # Single C-level bilinear pass for flux; direct integer indexing for variance & flags projected_image = map_coordinates(masked_image, [y_safe, x_safe], order=1, prefilter=False) projected_variance = np.where(in_bounds, masked_variance[yi, xi], np.nan) projected_flags = np.where(in_bounds, flags[yi, xi], np.uint8(0)) 

That single change dropped 3-pass stacking from 4,865.5 ms to 312.4 ms (15.6x faster) and cut retained RAM after garbage collection from +8.09 MB to +1.84 MB.

2. Splitting CPU and I/O Thread Pools

The Context

In Python's asyncio, calling await loop.run_in_executor(None, fn) dispatches synchronous work to a single shared default ThreadPoolExecutor. If heavy NumPy/SciPy jobs fill all worker threads, lightweight SQLite cache reads (get_manifest, get_frame) get stuck waiting in the same queue, turning a 10 ms cache hit into a 1,500 ms stall.

The Fix

In StarHuntersBackendService.__init__, I split execution into two isolated pools:

  • _io_executor (spherex-io, 8 to 32 threads): Dedicated to fast SQLite WAL queries, JSON serialization, and upstream HTTP downloads that spend most of their time waiting on sockets rather than burning CPU.
  • _cpu_executor (spherex-cpu): Sized dynamically by compute_max_concurrent_coadds. We inspect container CPU affinity (os.sched_getaffinity(0)), set aside 1 core on < 6-core VMs (or 2 cores on larger hosts) so asyncio and _io_executor always keep scheduling headroom, and give all remaining cores (total - reserved_for_io) to _cpu_executor:
# Simplified from backend_service.py # Full source: https://github.com/Eddy-Odero/star-hunters/blob/3a49453/backend/app/services/backend_service.py#L289-L312 def compute_cpu_pool_workers() -> int: if hasattr(os, "sched_getaffinity"): visible_cores = len(os.sched_getaffinity(0)) else: visible_cores = os.cpu_count() or 2 # Keep 1-2 cores free for asyncio + _io_executor; give the rest to _cpu_executor reserved_for_io = 1 if visible_cores < 6 else 2 return max(1, visible_cores - reserved_for_io) 

3. Fair Resource Gating with _AgingPrioritySemaphore

The Context: FIFO Head-of-Line Blocking vs. Priority Starvation

A counting semaphore caps how many coroutines can enter _cpu_executor at once.

Python's built-in asyncio.Semaphore wakes waiters in strict First-In, First-Out (FIFO) order. On a 2-vCPU VM (cpu_workers = 1), if four sky-patch builds (priority = 10) are queued and a user clicks an object to view its spectrum (priority = 0), FIFO forces that interactive click to wait behind all four heavy builds.

On the flip side, a textbook asyncio.PriorityQueue introduces starvation: if multiple users keep clicking spectra continuously, priority = 0 jobs perpetually cut in front of priority = 10 sky-patch builds. You also cannot solve aging with a static binary heap, because every waiter's elapsed wait time (now - enqueued_at) changes continuously while it sits in the queue.

The Fix: Recomputing Aging Tiers on release()

In _AgingPrioritySemaphore, each queued caller appends a _WaiterEntry(priority, enqueued_at, seq, future). Whenever a worker finishes and calls release(), we scan active waiters against time.monotonic(). Any job that has waited at least 2.0 seconds (STARVATION_THRESHOLD_S) is promoted to starved_tier = 0 and dispatched oldest-first ahead of fresh high-priority clicks:

# Simplified from backend_service.py # Full source: https://github.com/Eddy-Odero/star-hunters/blob/3a49453/backend/app/services/backend_service.py#L116-L171 class _AgingPrioritySemaphore: async def acquire(self, priority: int) -> None: self._prune_done_waiters() if self._in_use < self._capacity and not self._waiters: self._in_use += 1 return fut = asyncio.get_running_loop().create_future() self._seq += 1 entry = _WaiterEntry(priority, time.monotonic(), self._seq, fut) self._waiters.append(entry) try: await fut except BaseException: if entry in self._waiters: self._waiters.remove(entry) # Subtle race guard: if release() already resolved `fut` on the same # event-loop tick right before this task was cancelled, pass the permit on! if fut.done() and not fut.cancelled(): self.release() raise def release(self) -> None: self._prune_done_waiters() if not self._waiters: self._in_use = max(0, self._in_use - 1) return now = time.monotonic() def rank_key(idx_and_waiter: tuple[int, _WaiterEntry]) -> tuple[int, int, float, int]: _, w = idx_and_waiter is_starved = (now - w.enqueued_at) >= self._starvation_threshold_s if is_starved: return (0, 0, w.enqueued_at, w.seq) return (1, w.priority, w.enqueued_at, w.seq) winner_idx, _ = min(enumerate(self._waiters), key=rank_key) winner = self._waiters.pop(winner_idx) winner.future.set_result(None) 

Look closely at the except BaseException: block inside acquire() above, which handles one of my favorite asyncio subtleties from this project. If a user closes their browser tab on the exact event-loop tick after release() called winner.future.set_result(None) but before acquire() resumed, raising CancelledError without calling self.release() would permanently leak that semaphore permit and deadlock a 1-worker CPU pool.

4. Ingress Deduplication, Per-Provider I/O Timeouts & CPU-Only Gating

Single-Flight Coalescing + Stale-Before-429 Rate Limiting

Before a cold miss ever reaches our executors, get_sky_patch_async deduplicates concurrent requests using single-flight coalescing (_inflight_tasks[sf_key]): if 15 clients request the same uncached grid_key simultaneously, 14 await the first caller's Future and bypass ColdMissRateLimiter (12 cold misses/min per session or IP, 30/min per-IP ceiling, 50/min globally).

When a single IP does exceed its cold-miss quota, we first check SQLite for an expired 7-day stale cache entry (allow_stale=True) and serve that stale manifest if available. Only when a throttled caller requests a coordinate that has never been cached at all do we raise ColdMissRateLimitError and return HTTP 429 Too Many Requests with a Retry-After header.

Why a Pure Per-IP Limiter Wasn't Enough

I added this guard when I realised that continuous uptime would eat into my Fly.io budget; bots or a sudden surge of visitors could burn through it overnight. Right after, I noticed the flip side: a classroom or hackathon room often sits behind one NAT address, so a per-IP key can throttle a whole room of real users who are just exploring different parts of the sky.

I needed some way to tell real users apart from budget-burning bots without fingerprinting anyone. User-Agent strings (and even Client Hints) are now deliberately low-entropy, so a room of identical laptops all look the same. I settled on a compromise: the backend mints an anonymous, HMAC-signed session token (SessionToken via X-SH-Session) on the first API response, and the frontend echoes it back from sessionStorage (no cookie). The limiter now has three layers:

Request Bucket
Valid session token its own 12/min bucket, so one NAT neighbour can't starve another
No/invalid token strict 12/min per-IP bucket
Every cold miss, either kind also counts toward a 30/min per-IP aggregate ceiling (deliberately below the 50/min global cap, so one IP can never exhaust it)

The aggregate ceiling stops a bot from rotating tokens to dodge the IP limit. It deliberately sits below the global cap; if it were higher, a single NAT room or bot could eat the entire global budget before its own ceiling ever applied. Stale-before-429 still softens the blow for everyone.

Where the Numbers Come From

A cold miss is CPU-bound: my resource profile measures about 1.7 CPU-seconds per full cold patch (ingest, FITS cleaning, co-add). A 2-vCPU VM has 120 CPU-seconds per minute, so raw capacity is roughly 120 / 1.7 ≈ 70 cold misses/min. The 50/min global cap keeps the box about 70% busy on cold work and leaves headroom for hot reads, the event loop, and gzip. Pushing it to 60 would mean ~85% utilisation, which is exactly where tail latency starts to climb.

That also tells me how the limits scale with vertical scaling: CPU capacity grows roughly linearly with vCPUs, so going from 2 to 4 vCPUs should raise the safe cold-miss budget by about +100% (roughly 50 → 100/min), and co-add workers go from 1 to 3. Extra RAM doesn't raise the cold-miss ceiling (each worker only needs about 40 MB); it mostly helps the cache hit rate, which reduces how many cold misses happen in the first place. I haven't load-tested the scaled-up numbers, so treat them as a model, not a measurement.

To be clear, this is a good-citizen guard, not a defense against a determined attacker: anyone can discard the token and fall back to the strict per-IP bucket (the hard budget cut-offs live in fly.toml and CI). I didn't want to over-complicate the project, and for runaway bots and well-behaved rooms it was enough. I haven't yet been able to stress-test it with a full room since the demo, so treat the 30/min ceiling as an educated guess. Unique-visitor analytics still use a daily-rotating hash of IP + User-Agent, which undercounts users behind one NAT.

Independent ~10s Network Timeouts vs. CPU Runaway Guards

External science archives suffer unpredictable tail latency, and mixing network timeouts with local CPU work creates two subtle bugs:

  1. If WISE shares a single countdown timer with SPHEREx, a slow 7s SPHEREx response leaves WISE almost no time to finish.
  2. If a single asyncio.wait_for() wraps semaphore queueing, network downloads, and NumPy image stacking together, a temporary CPU traffic spike can falsely time out healthy requests (and waste scarce _cpu_executor threads waiting on sockets).

In archival_resolver.py and _run_cpu_guarded, we decoupled per-provider I/O timeouts from CPU semaphore work:

# Simplified from archival_resolver.py + backend_service.py # Full source: https://github.com/Eddy-Odero/star-hunters/blob/3a49453/backend/app/services/archival_resolver.py#L600-L760 PROVIDER_IO_TIMEOUT_S = 10.0 # Independent ~10s I/O budget per archive HEDGE_DELAY_S = 3.0 # Grace window before parallel fallback launches CPU_RUNAWAY_GUARD_S = 60.0 # Generous safeguard once a CPU worker starts async def run_cpu_guarded(priority: int, fn): # Queueing on the semaphore during request spikes does NOT burn timeout budget async with cpu_priority_semaphore.slot(priority): return await asyncio.wait_for( loop.run_in_executor(cpu_executor, fn), timeout=CPU_RUNAWAY_GUARD_S, ) async def resolve_patch_epochs(ra: float, dec: float, fov: float, target_wcs: dict): # 1. Start primary SPHEREx download on _io_executor (zero CPU slots held) t_spherex = time.monotonic() fut_spherex = loop.run_in_executor(io_executor, download_spherex_cutouts, ra, dec, fov) await asyncio.wait([fut_spherex], timeout=HEDGE_DELAY_S) fut_wise = fut_skyview = None if not fut_spherex.done(): # 2. Primary exceeded 3s: hedge WISE and SkyView downloads in parallel, # each with its own independent 10s I/O clock (total wait stays < 15s) t_wise = t_skyview = time.monotonic() fut_wise = loop.run_in_executor(io_executor, download_wise_raw, ra, dec, fov) fut_skyview = loop.run_in_executor(io_executor, download_skyview_raw, ra, dec, fov) rem_spherex = max(0.0, PROVIDER_IO_TIMEOUT_S - (time.monotonic() - t_spherex)) await asyncio.wait([fut_spherex], timeout=rem_spherex) cutouts = fut_spherex.result() if fut_spherex.done() else [] # 3. Pure CPU alignment & stacking runs inside the priority semaphore, # completely decoupled from upstream network I/O timeouts if cutouts: coadd = await run_cpu_guarded(PRIO_SKY_PATCH, lambda: coadd_spherex(cutouts, target_wcs)) if not coadd.needs_wise_fallback: return coadd # 4. WISE awaits its own independent 10s I/O window, then reprojects on CPU pool if fut_wise is None: t_wise = time.monotonic() fut_wise = loop.run_in_executor(io_executor, download_wise_raw, ra, dec, fov) if not fut_wise.done(): await asyncio.wait([fut_wise], timeout=max(0.0, PROVIDER_IO_TIMEOUT_S - (time.monotonic() - t_wise))) raw_wise = fut_wise.result() return await run_cpu_guarded(PRIO_SKY_PATCH, lambda: reproject_wise(raw_wise, target_wcs)) 

In the fast 95% case (< 3s), WISE and SkyView are never called. When SPHEREx lags, both fallbacks download concurrently on _io_executor with independent 10.0s I/O budgets (keeping combined wait time around 13s, well under 15s), while CPU bursts get graceful queueing without causing false upstream timeouts.

5. Measured Progression: Nov 16 Baseline vs. Current Backend

Running profile_resources.py against both our November 16 post-hackathon baseline and our current codebase shows the cumulative impact of vectorization, client pooling, and executor isolation:

Stage / Concurrency Benchmark Nov 16 Baseline Current Backend Improvement
spherex_wcs_coadd_3pass (18 rotated frames -> 3 cubes) 4,865.53 ms wall (5,374.4 ms CPU) 312.42 ms wall (326.95 ms CPU) 15.6x faster wall, 16.4x less CPU
spherex_wcs_coadd_3pass retained RAM after GC +8.09 MB +1.84 MB 4.4x lower retained RAM
catalog_pipeline_gaia_simbad (star catalog lookup) 180.39 ms wall 124.58 ms wall 31% faster
end_to_end_cold_patch_1x (full uncached request) 6,349.97 ms / +139.17 MB peak RSS 1,571.04 ms / +69.71 MB peak RSS 4.04x faster, 50% lower peak RAM
4 Simultaneous Co-add Workers (k = 4 batch) 12,689.52 ms wall (33,039.7 ms CPU) 2,922.76 ms wall (4,290.8 ms CPU) 4.34x faster batch, 7.7x less CPU

Combining run_stress_test.py with Little's Law (N = X * (R_avg + Z), modeling real humans with a 1.5s think interval Z between interactions):

  • Bounded Memory Scaling: Idle FastAPI starts at 151.83 MB RSS, and scaling from 1 to 4 simultaneous co-add workers adds just +32.15 MB per worker (279.55 MB peak RSS at k=4), fitting comfortably inside a 2048 MB VM alongside a 1024 MB RAM cache.
  • Sub-20ms Priority Clicks: On a constrained 2-vCPU setup under concurrent load, warm spectrum clicks drop to 19.87 ms mean / 9.05 ms p50.
  • Real-World Capacity: At 75%-97% RAM cache residency, that tiny server sustainably supports 87 to 176 concurrent active users (up to 104 new sessions/minute).

Closing Thoughts

Looking back at those two weeks after NASA Space Apps Challenge Kisumu, the biggest takeaway for me wasn't any single astronomy algorithm. It was realizing how much headroom hides inside "working" AI-generated code once you measure it honestly:

  1. Measure in isolation before guessing: Subprocess RSS high-water marks and loopback replay servers turn vague "it feels slow" hunches into exact millisecond and megabyte deltas.
  2. Design caches around access patterns, not just recency: Grid quantization, single-precision persistence, and time-invariant SLRU decay let a tiny SQLite file punch far above its weight.
  3. Gate scarce resources explicitly: Splitting CPU from I/O pools, timing network calls independently from CPU bursts, and aging queued priority waiters keep interactive UX snappy even when the backend is working flat out.

You can try the live Star Hunters web app, explore the full source code in Eddy-Odero/star-hunters, and inspect the benchmark harness in carsonak/star-hunters/benchmarks. Thanks for reading, and if you've tackled similar asyncio or SQLite scaling puzzles, I'd love to hear how you approached them in the comments!