# How Bootstrap Hydration with 15 Redis Keys Achieves Sub-Second First Render

> Learn how WorldMonitor achieves sub-second first render using bootstrap hydration with 15 Redis keys for synchronous component state access eliminating network waterfalls.

- Repository: [Elie Habib/worldmonitor](https://github.com/koala73/worldmonitor)
- Tags: performance
- Published: 2026-03-09

---

**WorldMonitor achieves sub-second first render by hydrating an in-memory Map with data from 15 deterministic Redis keys, allowing components to access initial state synchronously without network waterfalls.**

The `worldmonitor` repository eliminates render-blocking API calls through a aggressive bootstrap hydration strategy that moves data from edge-cached Redis into the browser before React components mount. By pre-populating 15 specific seed keys—ranging from market quotes to aviation delays—the application paints data-heavy panels instantly, falling back to network requests only when cached values expire.

## The Three-Layer Bootstrap Architecture

The hydration system operates through three coordinated stages: background seeding, tiered client fetching, and synchronous in-memory consumption.

### Edge Redis Seeding

Long-running background jobs (managed by Railway and ais-relay) write snapshot data to **Upstash Redis** using deterministic keys defined in [`server/_shared/cache-keys.ts`](https://github.com/koala73/worldmonitor/blob/main/server/_shared/cache-keys.ts). These 15 keys follow strict naming conventions like `market:stocks-bootstrap:v1` and `aviation:delays-bootstrap:v1`, ensuring writers and readers agree on exact locations. The `getKeyPrefix()` utility in [`server/_shared/redis.ts`](https://github.com/koala73/worldmonitor/blob/main/server/_shared/redis.ts) isolates preview and production deployments to prevent cross-environment contamination.

Each key carries a TTL (e.g., `7200` seconds for aviation delays) that balances freshness with availability, ensuring the bootstrap payload contains recent data without requiring real-time computation on every page load.

### Tiered API Hydration

When the application loads, [`src/App.ts`](https://github.com/koala73/worldmonitor/blob/main/src/App.ts) immediately invokes `fetchBootstrapData()` from [`src/services/bootstrap.ts`](https://github.com/koala73/worldmonitor/blob/main/src/services/bootstrap.ts). This function queries the `/api/bootstrap` endpoint (implemented in [`server/worldmonitor/.../bootstrap.ts`](https://github.com/koala73/worldmonitor/blob/main/server/worldmonitor/.../bootstrap.ts)) using **two parallel requests** with distinct timeout priorities:

```typescript
// src/services/bootstrap.ts
const fastCtrl = new AbortController();
const slowCtrl = new AbortController();
setTimeout(() => fastCtrl.abort(), 3_000);   // Critical tier
setTimeout(() => slowCtrl.abort(), 5_000);   // Non-critical tier

await Promise.all([
  fetchTier('fast', fastCtrl.signal),
  fetchTier('slow', slowCtrl.signal),
]);

```

The **fast tier** (3-second timeout) fetches critical market data, while the **slow tier** (5-second timeout) retrieves detailed climate statistics. Because Redis resides at the edge, the round-trip for these 15 keys remains under 10 milliseconds, and the resulting JSON populates an in-memory `Map<string, unknown>` before any panel renders.

### Synchronous In-Memory Consumption

Data services consume hydrated values through `getHydratedData` in [`src/services/bootstrap.ts`](https://github.com/koala73/worldmonitor/blob/main/src/services/bootstrap.ts). This function performs a synchronous lookup against the in-memory Map:

```typescript
// src/services/renewable-energy-data.ts
import { getHydratedData } from '@/services/bootstrap';

export async function getRenewableEnergy(): Promise<RenewableEnergy> {
  const cached = getHydratedData('renewableEnergy');
  if (cached) return cached as RenewableEnergy;

  // Fallback: direct bootstrap endpoint request
  const resp = await fetch('/api/bootstrap?keys=renewableEnergy', {
    signal: AbortSignal.timeout(8_000),
  });
  const { data } = await resp.json();
  return data;
}

```

When a key is present, the value returns **instantly** and the entry is immediately deleted from the Map to prevent stale reuse. This memory-only path enables sub-second first paint because the UI never waits for network I/O during initial render. The fallback 8-second timeout handles rare cache misses without blocking the interface.

## Deterministic Key Design

The 15 Redis keys use a deterministic naming pattern that eliminates ambiguity between background jobs and the bootstrap endpoint. The [`server/_shared/redis.ts`](https://github.com/koala73/worldmonitor/blob/main/server/_shared/redis.ts) module provides `setCachedJson` and `getCachedJson` utilities that handle serialization and prefix management.

**Writing seed data** occurs in background handlers:

```typescript
// server/worldmonitor/aviation/v1/list-airport-delays.ts
import { setCachedJson } from '../../../_shared/redis';

await setCachedJson(
  'aviation:delays-bootstrap:v1', 
  { alerts: allAlerts }, 
  7200  // 2-hour TTL
);

```

**Reading seed data** happens in API handlers to return instant responses:

```typescript
// server/worldmonitor/market/v1/list-market-quotes.ts
import { getCachedJson } from '../../../_shared/redis';

const bootstrap = await getCachedJson('market:stocks-bootstrap:v1', true);
if (bootstrap?.quotes?.length) {
  return bootstrap;  // Instant return from seed
}

```

## Summary

- **Bootstrap hydration** uses 15 deterministic Redis keys to pre-seed the client with market, aviation, and climate data.
- A **three-layer pipeline** moves data from Redis → `/api/bootstrap` → in-memory `Map<string, unknown>` before React mounts.
- **Tiered fetching** with 3-second and 5-second `AbortController` timeouts prioritizes critical data without blocking on slower sources.
- **Synchronous consumption** via `getHydratedData` serves data from memory in under a millisecond, enabling sub-second first render.
- **TTL and key prefixing** in [`server/_shared/redis.ts`](https://github.com/koala73/worldmonitor/blob/main/server/_shared/redis.ts) ensures fresh data and environment isolation.

## Frequently Asked Questions

### What is bootstrap hydration in worldmonitor?

Bootstrap hydration is a pre-rendering strategy where the application fetches data from 15 Redis keys into a JavaScript Map before components mount. This allows services to return initial state synchronously rather than triggering network requests after the UI paints, eliminating the traditional loading spinner waterfall.

### Why does worldmonitor use exactly 15 Redis keys?

The 15 keys correspond to distinct data domains (stocks, aviation delays, renewable energy, etc.) that follow deterministic naming conventions ending in `-bootstrap:v1`. This fixed set allows the `/api/bootstrap` endpoint to perform targeted `GET` operations for specific tiers without Redis scanning or pattern matching, keeping latency under 10 milliseconds.

### How does tiered fetching improve perceived performance?

Tiered fetching splits the 15 keys into critical (3-second timeout) and non-critical (5-second timeout) groups. This ensures essential market quotes hydrate immediately while allowing detailed climate statistics to load asynchronously. The UI renders the fast tier within 300 milliseconds, meeting the sub-second goal even if the slow tier arrives later.

### What happens if the in-memory bootstrap cache misses?

If `getHydratedData` returns undefined, the service falls back to a direct request to `/api/bootstrap?keys=...` with an 8-second timeout. While this introduces network latency, the Redis-backed endpoint still responds quickly. The retrieved data is then cached for subsequent navigation, though the initial render may exceed the one-second target only in this fallback scenario.