# Dhruv Mishra — Engineering Notes

Source: https://whoisdhruv.com/notes

Concise technical teardowns from Dhruv Mishra's lab notebook covering voice AI, low-RAM Next.js hosting, and high-scale Azure backend systems.

---

## Interruptible Voice Agents with Gemini Live & 25+ Site Tools

- URL: https://whoisdhruv.com/notes/voice-agent-barge-in
- Date: 2026-11-28
- Reading time: 5 min read
- Tags: voice-ai, gemini-live, audioworklet, websockets, tool-calling, architecture
- Related project: https://whoisdhruv.com/projects?project=personal-portfolio

> Architecture notes on full-duplex 16 kHz PCM streaming, client-side barge-in, and keeping 25+ live UI tools deterministic across route changes.

## Why Turn-Based Voice Feels Broken

Most browser voice demos bolt three request-response stages together: record until silence, send audio to STT, wait for an LLM completion, then stream TTS back. Even with fast models, end-to-end turn latency sits around 1.5 to 3 seconds—and worse, you cannot interrupt the assistant mid-sentence without awkwardly hitting a stop button.

For both this site's live voice agent and **Jarvis** (my voice-controlled freight dispatch demo), the goal was a phone-call feel: full-duplex audio over a single persistent WebSocket, native voice activity detection (VAD), sub-second turn-taking, and real-time UI actions while the conversation is still happening.

## The Audio Pipeline: Worklet to WebSocket and Back

The browser captures microphone input inside an `AudioWorklet` at 16 kHz mono PCM rather than `MediaRecorder`. Raw PCM frames avoid container framing overhead and let us stream tiny chunks continuously with predictable latency.

```text
Mic -> AudioWorklet (16 kHz PCM16) -> WebSocket -> Gemini Live
                                                       |
Speaker <- Web Audio Playback Queue <- PCM24 frames <--+
```

Three small details mattered most in practice:

- **One long-lived shell:** The `AudioContext`, microphone stream, and WebSocket live above the route tree. Navigating from `/` to `/projects` or `/notes` never drops the call or tears down audio playback.
- **Instant barge-in flush:** The moment Gemini Live emits an interruption signal—or local speech starts over active playback—the client immediately stops scheduled `AudioBufferSourceNode` nodes and clears the playback queue. Waiting for the current buffer to finish makes interruption feel sluggish.
- **Zero audio before consent:** No mic stream opens and no audio leaves the browser until the visitor explicitly starts a voice call.

> Barge-in is mostly a playback-queue problem, not a model problem. If your client queues 800 ms of audio ahead without a synchronous cancel path, even a 100 ms model interruption feels broken.

## Making 25+ Site Tools Safe and Deterministic

This portfolio exposes more than 25 structured tools to the voice agent: route navigation, opening and closing project cards, controlling preview videos, filling form fields, toggling site preferences, running safe terminal commands, and querying RAG facts via `lookup_site_facts`.

Giving a real-time voice model that many tools fails quickly unless you enforce strict boundaries:

- **Allowlisted schemas at the edge:** Every route target, project slug, form field ID, preference key, and terminal command is validated against explicit static allowlists before execution. Arbitrary paths or shell arguments are rejected outright.
- **Stable prompts and tool declarations:** System instructions and tool schemas stay byte-stable across turns so prompt caching remains effective, while ephemeral page state (current route, theme, open modal) rides in a compact session snapshot.
- **Queued UI execution:** Tool calls execute through a serialized client action queue so overlapping tool responses (for example, navigating to `/guestbook` and filling a field) land in order instead of racing React transitions.

## Context Hygiene Over Long Calls

Live voice sessions accumulate audio tokens quickly. Keeping transcripts bounded with a sliding context window and grounding factual answers through on-demand `lookup_site_facts` retrieval—instead of stuffing the entire portfolio into the system prompt—keeps both latency and token burn predictable over multi-minute calls.

## Trade-Offs Worth Knowing

- **WebSocket lifecycle vs. serverless:** Full-duplex voice wants a stateful connection or a short-lived session token minting endpoint; keeping the control plane minimal lets the browser connect cleanly without proxying every audio frame through heavy middleware.
- **Echo cancellation:** Browser AEC (`echoCancellation: true`, `noiseSuppression: true`) is non-negotiable on laptop speakers; without it, the agent interrupts itself on its own voice.
- **Network jitter:** Exposing a low-network preference and graceful reconnect state matters far more on mobile connections than shaving another 20 ms off desktop audio framing.

---

## Sub-400ms LCP Next.js 16 on 1 GB VMs Behind Cloudflare

- URL: https://whoisdhruv.com/notes/sub-400ms-portfolio-on-1gb-vms
- Date: 2026-11-21
- Reading time: 4 min read
- Tags: nextjs, performance, nginx, cloudflare, docker, linux, infrastructure
- Related project: https://whoisdhruv.com/projects?project=personal-portfolio

> How this portfolio runs Next.js 16 standalone, multi-cloud 1 GB Linux VMs, Nginx RSC-safe caching, and Docker deploys for zero hosting cost.

## The Constraint: Free-Tier 1 GB RAM VMs

Everything powering [whoisdhruv.com](https://whoisdhruv.com) is free except the domain name. The app runs as Docker images built by GitHub Actions and deployed to small 1 GB Linux VMs across Oracle Cloud, GCP, and Azure, sitting behind Nginx and Cloudflare.

On a 1 GB VM, you cannot brute-force latency with oversized Node heaps or uncached SSR renders. Sub-400ms LCP comes from doing less work per request and making sure the right layers cache the right bytes.

```text
Browser -> Cloudflare Edge -> Nginx (RSC-safe cache) -> Next.js 16 Standalone
```

## Next.js 16 Standalone + Static-First Routes

Packaging Next.js with `output: 'standalone'` strips `node_modules` down to the exact runtime dependency graph, which keeps Docker images lean and cold container restarts fast.

- **Static by default:** Pages like `/`, `/about`, `/projects`, `/notes`, and the markdown mirrors (`/llms.txt`, `/projects.md`, `/notes.md`) compile as `force-static` routes. Node serves pre-rendered responses directly from memory/disk instead of running React renders on every hit.
- **Dynamic only where state demands it:** Routes that actually mutate or read live data—like `/guestbook` (`revalidate = 60`), `/api/chat`, and `/api/voice/*`—bypass static caching cleanly.
- **Precomputed RAG embeddings:** Rather than querying an embedding API on startup or per request, `content/facts/**` and `content/notes/**` are embedded at build time into a compact JSON bundle shipped inside the image.

## Nginx Caching Without Breaking React Server Components

App Router introduces a subtle caching trap: the same URL path (`/about`) can be requested either as full HTML (initial document navigation) or as an RSC flight payload (client-side `next/link` transition carrying the `RSC: 1` header).

If a reverse proxy keys its cache only on `$scheme$request_method$host$request_uri`, a client-side RSC fetch can poison the cache and serve raw flight text to the next full-page reload—or vice versa.

```nginx
# Include RSC/router headers in the cache key so HTML and flight payloads never collide
proxy_cache_key "$scheme$request_method$host$request_uri|$http_rsc|$http_next_router_state_tree|$http_next_router_prefetch";
```

Separating the cache key by `$http_rsc` and Next router headers eliminates HTML/RSC collisions completely while still giving repeat visitors single-digit millisecond origin responses.

> Never cache an App Router URL by URI alone. Always partition proxy cache keys by `RSC` and Next router headers—or serve dedicated static routes (like `/notes.md`) with clean `text/markdown` content types instead of `Accept`-header content negotiation.

## Shipping Safely on Small Boxes

A single OOM kill during a deploy can take down a 1 GB VM if you build on the host. Instead:

- **Build in CI, not on the VM:** GitHub Actions compiles the Next.js standalone app and builds multi-architecture Docker images (including the local TTS runtime). The VM only pulls a finished image and swaps the container.
- **Verify locally before trusting the edge:** Deploy workflows validate each VM's container health, deployed release SHA, and TTS synthesis locally on the host before marking a release live and retaining the previous image for rollback.
- **Keep client JS disciplined:** Heavy interactive pieces (terminal, voice session, modals) lazy-load on demand so the initial paint stays light on mobile CPUs as well as desktop.

---

## Principles Behind Cutting $240K/yr on a 7B Req/Day Azure Backend

- URL: https://whoisdhruv.com/notes/azure-backend-cost-and-latency
- Date: 2026-11-12
- Reading time: 5 min read
- Tags: azure, distributed-systems, caching, redis, autoscaling, cost-optimization, reliability

> Universal systems-engineering lessons from trimming 15% off a high-scale Azure Service Fabric backend while holding 99.99% availability.

## Start With Telemetry, Not Intuition

At Microsoft, one of my favorite backend projects was cutting **$240K/year (~15%)** off the Azure bill of a Service Fabric backend handling **7+ billion requests per day**, while staying strictly inside a **99.99% availability** target—validated over three months of production telemetry.

Without touching any proprietary details, the engineering playbook itself is universal. High-scale cloud waste almost never comes from one dramatic bug; it compounds across three quiet places: underperforming caches, over-retained storage/logs, and pessimistic autoscaling rules.

## 1. Fix Cache Hit Ratio Before Buying More Compute

In our case, raising the Redis cache hit ratio from **31% to 80%** was the highest-leverage change of the entire effort.

At 7B+ requests/day, every percentage point of cache misses multiplies directly into downstream database RUs, serialization CPU, and network egress. Common culprits behind a 30%-range hit rate include:

- **Unnormalized cache keys:** Case sensitivity, unstable parameter ordering, or volatile metadata baked into keys fragments the keyspace so identical logical reads miss repeatedly.
- **Short TTLs chosen defensively:** Teams often pick a conservative TTL at launch and never revisit it once traffic grows 10x. Pairing slightly longer TTLs with explicit invalidation or stale-while-revalidate recovers huge hit-rate headroom.
- **Memory eviction thrashing:** Storing oversized payloads without compression or field projection pushes hot keys out of Redis before they can be reused.

> Measure cache efficiency by *bytes and downstream latency saved*, not just raw hit count. Eliminating a slow fan-out query saves far more compute than caching a trivial lookup.

## 2. Treat Log Retention and Database Provisioning as Capacity

Storage and observability bills grow silently because they rarely trigger an alert until a quarterly review.

- **Audit high-volume telemetry:** Verbose debug logs emitted on the hot path at billions of calls per day burn ingestion, indexing, and retention budget fast. Sampling success paths while keeping 100% of errors preserves debuggability at a fraction of the cost.
- **Right-size Cosmos DB / NoSQL throughput:** Once cache hit rates climb, downstream RU peaks flatten. Re-evaluating partition key distribution and provisioned vs. autoscale throughput turns cache wins into real dollar savings instead of idle headroom.

## 3. Retune Autoscaling With Real Headroom Math

Across **12+ VM Scale Sets**, legacy scale-out thresholds are often calibrated for a traffic profile from two years ago—scaling out too early, scaling in too slowly, or pinning minimum instance counts far above trough demand.

```text
Good autoscale loop:
  1. Measure true p99 latency knee vs. CPU / RPS per node
  2. Set scale-out trigger safely below the knee (with warm-up margin)
  3. Use asymmetric cooldowns: fast scale-out, steady step-down scale-in
  4. Validate under peak + single-zone failure before lowering floor
```

The rule that kept 99.99% availability intact: **never tune scale-in speed and minimum floor in the same week**. Change one lever, watch a full weekly traffic cycle in telemetry, confirm p99 latency and error budgets stay flat, then move to the next scale set.

## The Takeaway

Cost optimization at scale is just reliability engineering with a budget constraint. Raising cache efficiency, trimming noisy telemetry, and aligning autoscale policies with actual latency knees makes the system both cheaper *and* calmer under load—and pairs naturally with AI-assisted incident triage agents (which cut our manual low/mid-severity on-call triage by 40%) so engineers spend their time on architecture instead of firefighting.
