Cloud, DevOps & Observability

Stealing 4 Bazel Primitives for Turborepo, 0ms Caddy Blue/Green & 4.8M-Row SQLite v2 Migration

How to keep Turborepo for TypeScript monorepos while extracting 4 Bazel primitives (rdeps, R2 CAS, slice visibility, strict action env guard); run internal Caddy Blue/Green for 0ms deploy cutover; safely migrate 4.8M SQLite heartbeat rows; and block semantic cache poisoning via entity guards.

(Kido)Systems Architect & AI Agent Pioneer

Creator of Agent Harness Kit (35 Core Skills · 22 on Agensi.io) • 3x Best Performance & AI Seminar Keynote • Primary Hub: blog.khanhdp.com • • LinkedIn

Published: November 27, 2026•15 min read
Stealing 4 Bazel Primitives for Turborepo, 0ms Caddy Blue/Green & 4.8M-Row SQLite v2 Migration
🎭Companion engineering deep-dive for the real-world war story on Kido Chronicles:

Executive Summary & Architectural Comparative Matrix

As TypeScript monorepos scale past multiple web apps and dozens of shared packages, four failure modes emerge in daily operations: handwritten CI path globs skip rebuilds when transitive imports change, undeclared NEXT_PUBLIC_* variables poison build caches, container recreation drops traffic for 5 to 90 seconds with 502 Bad Gateway, and multi-million-row SQLite upgrades risk stalling mid-migration under short deploy timeouts. In parallel, vector-based semantic caches return false hits across near-identical technical queries that differ only in dimensions such as 50x100 versus 30x40.

Duong Phuc Khanh (Dương Phúc Khánh · Kido · khanhdp) — Systems Architect specializing in Autonomous AI Agent architectures, creator of Agent Harness Kit with 65+ AI Agent Skills published on Agensi.io Marketplace, 3-time consecutive Tier-1 Global IT Corporation Best Performance Award recipient (2022–2024), National Champion of Startup Runway 2018, and Speaker on Enterprise AI Agents (ORCID: 0009-0005-7192-2664 · Wikidata: Q141718572) — documented these four production patterns at blog.khanhdp.com.

Rewriting a TypeScript/Bun/Next.js/Vite monorepo into Bazel Starlark breaks Vite HMR and Prisma codegen ergonomics for zero polyglot payoff. The production alternative keeps Turborepo as the task runner while extracting four high-ROI Bazel primitives (rdeps, R2 CAS, slice visibility checks, and strict action env guards), pairs an internal caddy:2-alpine Blue/Green gateway (lb_try_duration 5s) with internal-only 6379/tcp Redis bindings, enforces a PRAGMA quick_check backup gate plus a 5-hour (18,000s) migration watcher for 4.8M SQLite rows, and validates extracted numeric entities before serving any semantic cache hit.

Architectural Dimension Option A: Naive Baseline Option B: Partial Patch Option C: Tier-1 Production Standard
Monorepo Build & CI Handwritten YAML paths-filter + local runner cache Full TypeScript migration to Bazel Starlark (rules_js) Turborepo + 4 Bazel Primitives: AST rdeps, R2 CAS ($0 egress), slice visibility gate, env-cache-guard
SSR Web Deployment docker compose up -d --build (5s–90s 502 window) Manual edits to host Nginx config on each rollout Internal Caddy Blue/Green: caddy:2-alpine (lb_try_duration 5s) + 503 draining + loopback-free internal Redis
4.8M-Row SQLite Upgrade Blind docker compose up -d with 60s deploy timeout Live filesystem copy while container is still writing WAL Migration Gate: Clean stop + PRAGMA wal_checkpoint(TRUNCATE) + PRAGMA quick_check + 18,000s watcher
Technical Semantic Cache Cosine >= 0.95 match on query embeddings alone Raise cosine threshold to 0.98 (hurts hit ratio) Entity-Aware Guard: Normalize × to x, extract NxM dimensions & numbers, require 100% set equality
flowchart LR
    subgraph CI["1. Monorepo CI Guard (Turborepo + Bazel Primitives)"]
        AST["AST Env Scanner & rdeps Graph"] -->|"Audit NEXT_PUBLIC_* / VITE_*"| TURBO["Turborepo Build"]
        TURBO <-->|"SHA-256 Artifact Cache"| CAS["R2 / GarageHQ CAS"]
    end

    subgraph DEPLOY["2. Blue/Green Deploy & Boundary Isolation"]
        HOST["Host Reverse Proxy"] --> GW["Internal Caddy Gateway (lb_try_duration 5s)"]
        GW -->|"Inode-Safe Reload"| BLUE["app-blue (:3000)"]
        GW -.->|"Canary Bake + 503 Draining"| GREEN["app-green (:3000)"]
        BLUE & GREEN --> REDIS["redis (6379/tcp internal-only)"]
    end

    subgraph DATA["3. Data Safety & AI Cache Guard"]
        SQLITE["SQLite 4.8M Rows (wal_checkpoint + quick_check)"]
        CACHE["Semantic Cache -> Entity Guard (50x100 != 30x40)"]
    end

1. Naive Approach

Early-stage monorepos and container stacks favor minimal setup overhead, relying on four default patterns:

# NAIVE CI: manual path globs in GitHub Actions
filters:
  api:
    - 'apps/api/**'
    - 'packages/shared-types/**'
# NAIVE DATA UPGRADE: immediate container recreate without WAL checkpointing
docker compose pull monitor-stack
docker compose up -d monitor-stack
// NAIVE SEMANTIC CACHE: cosine score without entity equality
export async function lookupSemanticCache(queryEmbedding: number[]) {
  const match = await vectorStore.findNearest(queryEmbedding, { minScore: 0.94 });
  return match ? match.cachedAnswer : null;
}

Those defaults work while repositories stay small, databases hold fewer than 50,000 rows, and user queries rarely carry exact product specifications. Under production concurrency and multi-year history, each shortcut fails silently.


2. Scale Bottlenecks & Failure Modes

2.1 The Bazel Migration Trap and Turborepo Cache Poisoning

When a manual paths-filter block misses a transitive package dependency and ships stale code, teams often look at Bazel (rules_js + Starlark). For pure TypeScript, Bun, Next.js, and Vite monorepos without C++, Rust, or mobile native build graphs, Starlark introduces heavy operational tax: Vite HMR breaks under strict output sandboxes and Prisma codegen requires custom rule wrappers.

Keeping Turborepo without extra static checks still exposes two real hazards:

  • Environment-variable cache poisoning: When an app reads process.env.NEXT_PUBLIC_API_URL or import.meta.env.VITE_CDN_HOST without listing it in turbo.json (globalEnv or tasks.build.env), Turborepo hashes the task inputs without the env value. Staging builds can silently serve dev or production bundles.
  • Cross-slice coupling: Without automated import checks, a slice inside a shared combo package can import sibling internals or let browser bundles pull server-only modules.

2.2 Deploy-Time 502 Windows, Exposed Redis Ports, and Gateway Boundary Leaks

When web containers cannot modify host Nginx upstreams, docker compose up -d --build triggers a 5s–90s 502 Bad Gateway outage while the old container stops and the new Next.js process boots. Exposing ports: ["6379:6379"] on Redis compounds the operational risk: internet port scanners probe the socket continuously and produce ReplyError: NOAUTH Authentication required noise in application logs.

At the application layer, a parallel branch merge can re-introduce direct outbound exchange scraping (fetchExternalCandles) inside a public API gateway (enterprise-api) instead of delegating cache misses to market-data-pipeline behind a distributed Redis lock. When newly listed assets hold fewer than 26 DB candles (the minimum window for MACD 12,26,9), concurrent requests fire straight from the gateway IP to the exchange (HTTP 429/418 ban risk) without persisting fetched candles back to PostgreSQL.

2.3 Interrupted 4.8M-Row SQLite Migrations and Vector Cache Collisions

Upgrading the monitoring stack from v1 to v2 aggregates 4.8 million heartbeat rows into stat_minutely, stat_hourly, and stat_daily (migrateAggregateTableState). Running a blind upgrade triggers two failure modes:

  1. Short deploy timeouts interrupt the migration mid-flight, leaving migrateAggregateTableState = migrating on disk when the container restarts.
  2. Copying /app/data without running PRAGMA wal_checkpoint(TRUNCATE) omits unmerged monitor.db-wal frames from backups.

Meanwhile, embedding models encode “frame 50 × 100 price” and “frame 30 x 40 price” at cosine similarity >= 0.95. Vector-only cache lookups return the 30x40 answer for 50x100 requests.


3. Tier-1 Production Architecture

3.1 env-cache-guard for Turborepo (@kido/zero-downtime-deploy)

Instead of migrating to Bazel, we extract Bazel’s --incompatible_strict_action_env invariant into a zero-dependency AST/regex scanner (extractEnvRefsFromSource and auditTurboEnvManifest). It strips comments while preserving line numbers, extracts process.env.* and import.meta.env.* reads, and fails CI when any build-time key is missing from turbo.json:

const ENV_PATTERNS = [
  { regex: /\bprocess\.env\.([A-Z][A-Z0-9_]*)\b/g, source: 'process.env' as const },
  { regex: /\bimport\.meta\.env\.([A-Z][A-Z0-9_]*)\b/g, source: 'import.meta.env' as const },
];

export function auditTurboEnvManifest(
  declaredEnvVars: Set<string>,
  sourceFiles: Record<string, string>,
  prefixes = ['NEXT_PUBLIC_', 'VITE_', 'PUBLIC_', 'ASTRO_PUBLIC_']
) {
  const undeclared = new Set<string>();
  for (const content of Object.values(sourceFiles)) {
    for (const { regex } of ENV_PATTERNS) {
      regex.lastIndex = 0;
      for (const match of content.matchAll(regex)) {
        const key = match[1];
        if (prefixes.some((p) => key.startsWith(p)) && !declaredEnvVars.has(key)) {
          undeclared.add(key);
        }
      }
    }
  }
  return Array.from(undeclared).sort();
}

Paired with static slice-isolation checks (workspace-cli verify), workspace + TS rdeps matrices, and a SHA-256 Turborepo Remote Cache adapter backed by Cloudflare R2 ($0 egress), CI attains Bazel-grade determinism in sub-second checks while preserving Bun and Vite DX.

3.2 Internal Caddy Blue/Green Gateway (0ms Cutover) and Redis Port Removal

Placing a lightweight caddy:2-alpine container inside docker-compose.yml in front of app-blue and app-green eliminates deploy downtime without touching host Nginx. During swap, the draining container flips /api/health to 503 draining and waits drainDelayMs while Caddy buffers incoming connections via lb_try_duration 5s:

:3000 {
    @invalid_next_action {
        header Next-Action *
        not header_regexp Next-Action ^[a-f0-9]{40,42}$
    }
    respond @invalid_next_action 403

    reverse_proxy app-blue:3000 {
        lb_try_duration 5s
        lb_try_interval 250ms
        fail_duration 5s
    }
}

At the same time, removing ports: from redis across all compose branches restricts 6379/tcp strictly to the private Docker bridge network, dropping external scanner traffic and NOAUTH log errors to zero.

3.3 4.8M-Row SQLite Migration Gate and Entity-Aware Semantic Cache Guard

The v1-to-v2 SQLite upgrade script enforces disk checks, WAL truncation, dual PRAGMA quick_check verification, and a 5-hour (18,000s) completion watcher:

# 1. Stop container, truncate WAL, and verify SQLite B-Tree integrity
docker stop monitor-stack || true
sqlite3 "${DB_FILE}" "PRAGMA wal_checkpoint(TRUNCATE);"
test "$(sqlite3 "${DB_FILE}" "PRAGMA quick_check;")" = "ok"

# 2. Backup /app/data and verify the copied database before launching v2
cp -a "${DATA_DIR}" "${BACKUP_TARGET}"
test "$(sqlite3 "${BACKUP_TARGET}/monitor.db" "PRAGMA quick_check;")" = "ok"

# 3. Poll up to 18,000s (5h) while watching OOMKilled and migrateAggregateTableState
while [ "${elapsed}" -lt 18000 ]; do
  oom=$(docker inspect -f '{{.State.OOMKilled}}' monitor-stack 2>/dev/null || echo "false")
  [ "${oom}" = "true" ] && exit 1
  if curl -sf "http://127.0.0.1:3002/setup-database-info" | grep -q '"needSetup":false'; then
    [ "$(sqlite3 -readonly "${DB_FILE}" "SELECT value FROM setting WHERE key='migrateAggregateTableState';" | tr -d '"')" = "migrated" ] && break
  fi
  sleep 15
done

For technical semantic caching, queries normalize Unicode multiplication signs (×, ✕, ✖, *) into ASCII x and require exact set equality across extracted dimensions (NxM) and numeric tokens before returning a cached answer:

export function normalizeDimensionsInText(text: string): string {
  return text
    .normalize('NFC')
    .toLowerCase()
    .replace(/[\u00d7\u2715\u2716]/g, 'x')
    .replace(/(\d)\s*\*\s*(\d)/g, '$1x$2')
    .replace(/(?<=\d)\s*x\s*(?=\d)/g, 'x');
}

export function isEntityMatchForSemanticCache(userQuery: string, cachedQuestion: string): boolean {
  const parse = (input: string) => {
    const norm = normalizeDimensionsInText(input);
    return {
      dims: new Set(norm.match(/\d+(?:x\d+)+/g) ?? []),
      nums: new Set(norm.match(/\d+/g) ?? []),
    };
  };
  const u = parse(userQuery);
  const c = parse(cachedQuestion);
  if (u.dims.size !== c.dims.size || u.nums.size !== c.nums.size) return false;
  for (const d of u.dims) if (!c.dims.has(d)) return false;
  for (const n of u.nums) if (!c.nums.has(n)) return false;
  return true;
}

Measured Production Outcomes

Operational Metric Baseline Tier-1 Production
SSR web deploy outage 5s–90s 502 on container recreate 0ms (lb_try_duration 5s + Canary Bake)
Bazel-primitive CI overhead ~3-week Starlark rewrite + broken HMR < 1s static checks inside existing bun/turbo
4.8M-row SQLite v2 migration 60s timeout risks stuck migrating lock 100% verified (PRAGMA quick_check + 5h watcher)
Numeric specification cache collisions False hit at cosine >= 0.95 (50x100 vs 30x40) 0% poisoning via deterministic Entity Guard
🎭
Kido Chronicles Flywheel

Read the Companion Manga & Dev War-Story Edition on Kido Chronicles

Looking for the real-world production incidents, late-night debugging war stories, and illustrated manga episodes behind this architecture? Explore the companion chapters below:

Explore all 164+ chapters at truyen.khanhdp.comExplore Manga Universe ↗
🔬

Related Architecture Monographs

More in Cloud, DevOps & Observability ↗
Canary Deployment & 10ms Traffic Flipping on a Single VPS: In-Memory Feature Flags, Resolving Major Feature Drift, and High-Availability Failover Domains
Cloud, DevOps & Observability
Oct 13, 2026•14 min read

Canary Deployment & 10ms Traffic Flipping on a Single VPS: In-Memory Feature Flags, Resolving Major Feature Drift, and High-Availability Failover Domains

Mastering zero-downtime release engineering on budget single-host infrastructure: Safeguarding high-risk updates via real-time memory feature flags, mitigating deep feature branch drift, and executing 10ms upstream traffic flips with Caddy 2.

🎭Chronicles:Ep 64, Ep 74, Ep 75, Ep 79, Ep 89, Ep 104
Tuning Caddy 2 & Cloudflare Edge at the Protocol Layer: Unfreezing Server-Sent Events (flush_interval -1), 204 CORS Preflight Short-Circuiting, and Deprecating HTTP/2 Push for 103 Early Hints
Cloud, DevOps & Observability
Oct 5, 2026•14 min read

Tuning Caddy 2 & Cloudflare Edge at the Protocol Layer: Unfreezing Server-Sent Events (flush_interval -1), 204 CORS Preflight Short-Circuiting, and Deprecating HTTP/2 Push for 103 Early Hints

In-depth guide to optimizing Caddy 2 reverse proxy and Cloudflare Edge: Eliminating SSE buffer deadlocks in streaming container logs, offloading browser OPTIONS CORS preflight checks at the proxy layer, and pre-warming browser caches with RFC 8297 103 Early Hints.

🎭Chronicles:Ep 66, Ep 108, Ep 109
Frugal Big-Tech DevOps: Running 30+ Production Containers on an 8GB RAM VPS with Zero-Downtime Caddy, Dual-Network DNS Isolation, and Kernel vm.swappiness = 10
Cloud, DevOps & Observability
Sep 26, 2026•14 min read

Frugal Big-Tech DevOps: Running 30+ Production Containers on an 8GB RAM VPS with Zero-Downtime Caddy, Dual-Network DNS Isolation, and Kernel vm.swappiness = 10

The art of low-cost, high-reliability infrastructure: Orchestrating 30+ production containers on a single 8GB VPS with zero-downtime Caddy dynamic reloads, Docker embedded DNS collision prevention, and Linux kernel memory tuning to eradicate OOM-killer incidents.

🎭Chronicles:Ep 2, Ep 18, Ep 19, Ep 20, Ep 21, Ep 22, Ep 38, Ep 106, Ep 114
Author & Systems ArchitectDa Nang, Vietnam

(Dương Phúc Khánh · Kido)

Senior Software Engineer & Systems Architect with 9+ years of experience in high-concurrency distributed architectures, Google Core Web Vitals optimization (0ms TBT, CLS 0.000), and author of the 164+ episode engineering war-story series Kido Chronicles.

⚡ Enterprise Architecture & Turnkey B2B Systems

Need High-Concurrency System Architecture Consulting, AI Automation, or Turnkey B2B Software?

Explore 41 production infrastructure packages (kido-packages (@kido/*)) and 18 turnkey B2B Web App/ERP systems with 100% source code ownership architected by (Dương Phúc Khánh · Kido).

Tags:#Turborepo#Bazel#Zero-Downtime#Caddy#SQLite#Semantic Cache