CYDERCODER // PLAYBOOK
SYS.STATUS: OK 00%
> INITIALIZING...
Install this playbook for offline access
You're offline — reading cached content
WHO THIS IS FOR

Built for every stage of the builder journey

Beginners

Clear path from zero to deployed product in one afternoon. Exact AI prompts to copy. Explains the why, not just the how — all the way to production with a custom domain.

  • Build your first website end-to-end
  • Deploy with Vercel, set up Google Search Console
  • Understand what React is doing behind the scenes

Senior Devs

A reference manual for AI architecture decisions. RAG chunking, MCP, multi-agent systems, CDN caching, deployment strategies — without the fluff.

  • RAG chunking strategies, MCP protocol architecture
  • Typography scale, color theory, motion design systems
  • CDN caching, edge functions, deployment strategies
Portrait Lock Active
Please rotate your device back to Portrait orientation to read the playbook content.
Back to Dashboard

Production & Operations: Architecting for the Wild

01. The Production Mindset

The ultimate test of an application isn’t how smoothly it runs on your local machine — it is how it handles thousands of parallel users, hostile network drops, and malicious traffic scripts without crashing.

The Operational Reality: If a bug crashes your local server, you refresh the page. If a bug crashes your production server at 3:00 AM, your business stops, alerts fire, and costs spike. Seniors spend just as much time engineering the containment walls around code as they do writing the code itself.

What Changes Between Local and Production

ConcernLocal DevelopmentProduction
ErrorsStack trace in terminal, refresh and retryError must be caught, logged, and reported without crashing
DataSQLite or local Postgres, throwaway dataManaged database with backups, migrations, and point-in-time recovery
Secrets.env file in root, committed to gitInjected at runtime, encrypted at rest, never in version control
TrafficYou, maybe 2-3 tabsHundreds to thousands of concurrent connections
UptimeServer crashes, you restart itServer crashes, an orchestrator restarts it automatically
Logsconsole.log in terminalStructured JSON streamed to a log aggregator
Deploymentsnpm start in terminalCI/CD pipeline validates, builds, and deploys on merge

The Pre-Deployment Checklist

Before any code touches production, verify:

□ Environment variables validated at startup (not at first use)
□ No secrets in client bundles (grep for NEXT_PUBLIC_ with secret values)
□ Database migrations tested against a staging database
□ Error boundaries catch all rendering failures
□ Rate limiting active on public API endpoints
□ Health check endpoint returns 200 under normal conditions
□ Logging outputs structured JSON, not console.log strings
□ Build succeeds in a clean environment (no node_modules cached)

02. Environment Variables & Secret Isolation

The quickest way to get your server exploited or your database drained is letting API keys leak into public files or client bundles.

The Client-Side Leak

When using frameworks like Next.js or Astro, any environment variable prefixed with NEXT_PUBLIC_ or PUBLIC_ is baked directly into the JavaScript bundle sent to the user’s browser. Anyone can open DevTools → Network → find your bundle → search for your key.

The Rule:

  • Variables with NEXT_PUBLIC_ or PUBLIC_ prefix → Visible to everyone (use for public URLs only)
  • Variables WITHOUT these prefixes → Server-only, hidden from users (use for API keys, secrets)

The Rule: Client vs. Server Secrets

PrefixWhere It LivesAccessible FromUse Case
NEXT_PUBLIC_*JavaScript bundleBrowser (anyone)Public URLs, published IDs, feature flags
*_SECRET_KEYServer runtimeYour server onlyAPI keys, database credentials, JWT secrets
*_URL (no prefix)Server runtimeYour server onlyDatabase connections, internal API endpoints

The test: Open your deployed app, open DevTools, search the page source and network tab for the variable name. If you find it, it’s leaking.

Runtime Validation at Boot

Do not wait for your server to crash halfway through a user’s checkout because an environment variable was missing. Validate every secret at startup.

Tell your AI tool: “Add environment variable validation at application startup. Check that DATABASE_URL, STRIPE_SECRET_KEY, and JWT_SECRET are present and properly formatted. If any are missing, log a clear error and refuse to start.”

Why this matters: A server that crashes on startup is better than one that crashes mid-request. You find the problem immediately, not after users are affected.

Secret Rotation

Secrets should be rotated periodically. The pattern:

  1. Generate a new key in the provider dashboard (Stripe, Supabase, etc.)
  2. Add the new key as a new environment variable in your hosting platform
  3. Deploy with the new key
  4. Verify the deployment works
  5. Delete the old key from the hosting platform
  6. Only then delete the old key from the provider dashboard

Never delete the old key before verifying the new one works. This is the most common deployment outage for teams new to secret rotation.


03. CI/CD: The Automated Pipeline

Seniors do not manually drag files to servers or run git push production from their terminals. Every change is validated through automated Continuous Integration / Continuous Deployment.

The Git Flow Pattern

The flow:

  1. main branch is locked — no direct commits allowed
  2. Create a feature branch (e.g., feature/auth-refresh-tokens)
  3. Open a Pull Request — CI automatically validates (lint, test, build)
  4. Merge to main — triggers deployment to production

Rules:

  1. main is locked. No direct commits. All changes go through Pull Requests.
  2. Every PR triggers a full validation suite (lint, test, build).
  3. Merging to main triggers deployment to production automatically.

The Validation Pipeline

Tell your AI tool: “Create a GitHub Actions workflow that runs on pull requests to main. It should: install dependencies, run the linter, run type checking, run tests, and build the project. If any step fails, the PR cannot be merged.”

The Deployment Pipeline

Tell your AI tool: “Create a GitHub Actions workflow that runs when code is pushed to main. It should: download the build artifact, deploy to Vercel using the VERCEL_TOKEN secret, and only run if the validation workflow passed.”

Branch Protection Rules

In your GitHub repository settings, configure:

RuleSetting
Require pull request before merging✅
Require approvals (at least 1)✅
Require status checks to pass✅ (lint, test, build)
Require branches to be up to date✅
Require conversation resolution✅
Do not allow bypassing above settings✅ (even for admins)

This means no one can push broken code to production — not even the repository owner.


04. Docker: Immutable Environments

The phrase “But it worked perfectly on my local machine” has no place in senior engineering. Different OS versions, mismatched Node.js versions, and conflicting global packages break apps instantly. Docker solves this by packaging your code, runtime, and dependencies into a single immutable container.

The Production Dockerfile

A Dockerfile is a recipe that tells Docker how to build your application into a container. Think of it as a script that installs dependencies, compiles your code, and sets up the runtime.

Tell your AI tool: “Create a production Dockerfile with multi-stage builds. Stage 1: install dependencies and build the project. Stage 2: copy only the built files and production dependencies. Add a health check endpoint. Expose port 3000.”

Why multi-stage builds matter: The build stage installs dev tools (TypeScript, ESLint) that aren’t needed in production. The final image only contains what’s needed to run, reducing size from ~800MB to ~150MB.

Why Multi-Stage Builds Matter

The builder stage installs dev dependencies (TypeScript, ESLint, testing libraries) and compiles your code. The runner stage copies only the compiled output and production dependencies. This reduces your final image from ~800MB to ~150MB.

The .dockerignore File

Without this, Docker copies your node_modules, .git, and other unnecessary files into the build context, slowing everything down.

Tell your AI tool: “Create a .dockerignore file that excludes node_modules, .git, .env files, dist, coverage, markdown files, and IDE config from the Docker build context.”

Docker Compose for Local Development

Docker Compose lets you run multiple services (your app + database) together with one command.

Tell your AI tool: “Create a docker-compose.yml with two services: my app (build from Dockerfile, port 3000) and PostgreSQL (port 5432). The app should wait for the database to be healthy before starting. Use a named volume for database data.”

Senior Moves for Docker

  1. Never run as root. Add USER node before CMD in your Dockerfile. Running as root inside a container is a security risk if the container is compromised.
  2. Pin your base image versions. node:20-alpine is fine. node:latest is a disaster waiting to happen — the base image changes and your app breaks silently.
  3. Use .dockerignore religiously. Every file you exclude makes the build faster and the image smaller.
  4. Health checks are non-negotiable. Without them, orchestrators (Kubernetes, Docker Swarm, ECS) can’t tell if your container is alive or stuck.

05. Rate Limiting & API Protection

An unprotected API is an invitation for abuse. Without rate limiting, a single malicious script can exhaust your database connections, burn your API budget, or crash your server.

The Rate Limiting Stack

Defense Layers
Layer 1
CDN / Edge (Cloudflare)
Blocks DDoS, filters bad IPs
Layer 2
API Gateway
Global rate limits (1000 req/min per IP)
Layer 3
Application Middleware
Per-user limits (100 req/min per user)
Layer 4
Database
Connection pooling, query timeouts

Implementation

Tell your AI tool: “Add rate limiting to all API endpoints. Use Redis for shared state across server instances. Set these limits:

  • Global: 100 requests per minute per IP
  • Auth endpoints (login, signup): 5 attempts per 15 minutes
  • Return proper 429 status codes with retry-after headers”

What the rate limiter does:

  • Counts requests from each IP address
  • Blocks requests that exceed the limit
  • Returns a 429 “Too Many Requests” response
  • Resets the counter after the time window expires

What Rate Limiting Headers Look Like

What rate limiting headers look like:

Your API responses should include these headers:

  • RateLimit-Limit: 100 — Maximum requests allowed per window
  • RateLimit-Remaining: 67 — Requests left in current window
  • RateLimit-Reset: 1710000060 — Unix timestamp when the window resets

The client can read these headers and show the user how many requests they have left — or proactively slow down before hitting the limit.


06. Production Telemetry: Logging & Monitoring

Once your application is live, you need clear eyes on how it behaves under load. You cannot fix what you cannot measure.

Structured Logging over console.log

Standard console.log() outputs unformatted strings that are impossible to parse or query when thousands of operations happen simultaneously. Structured JSON logging lets monitoring tools index, filter, and alert on specific events.

Tell your AI tool: “Add structured logging. Every log entry should be a JSON object with timestamp, level (info/warn/error), message, and context (userId, requestId, any relevant data). In production, output as JSON. In development, pretty-print for readability.”

Good logging example: When a payment succeeds, log: { "timestamp": "2026-07-11T10:00:00Z", "level": "info", "message": "Payment processed", "userId": "abc123", "amount": 49.99, "paymentId": "pay_xyz" }

Bad logging example: console.log("payment failed") — No timestamp, no context, impossible to search or debug.

Log Levels: When to Use Each

Log Levels: When to Use Each

LevelWhenExample
debugDevelopment only, verbose troubleshooting”Query returned 42 rows”
infoNormal operations worth recording”User signed up”, “Payment processed”
warnUnexpected but non-fatal events”Rate limit approaching”, “Deprecated API called”
errorFailures that need attention”Payment failed”, “Database connection lost”

The rule: In production, debug logs are typically disabled. info is your baseline. warn and error trigger alerts.

Global Error Handlers

Implement global exception barriers to catch unhandled errors gracefully — your service stays running for other users while your team gets notified immediately.

Tell your AI tool: “Add global error handlers that:

  1. Catch unhandled promise rejections and log them with context
  2. Catch uncaught exceptions, log them, and exit gracefully
  3. Handle SIGTERM for graceful shutdown (stop accepting requests, finish in-flight work, close database connections, exit)”

Why this matters: Without global handlers, an unhandled error crashes the entire server. With them, the error is logged, the server stays running for other users, and your monitoring tool alerts you.

External Monitoring Services

ServicePurposeFree Tier
SentryError tracking, stack traces, release tracking5k errors/month
LogflareStructured log aggregation1GB/month
BetterStackUptime monitoring + incident management20 monitors
Grafana CloudMetrics, logs, traces, dashboards10k metrics

The Monitoring Dashboard

At minimum, track these metrics:

Monitoring Dashboard
Health
Request Rate: 342/min
Error Rate: 0.3%
P50: 120ms
P95: 450ms
P99: 1.2s
Resources
CPU: 34%
RAM: 62%
Disk: 28%
DB Conns: 12/50
Alerts
P99 latency spike
DB pool exhaustion (resolved)
Deployment v2.4.1 (success)

07. Database Migrations in Production

Running prisma migrate dev or drizzle push from your local machine against a production database is a ticking time bomb. Migrations in production need a controlled, reversible process.

The Migration Pipeline

1. Write migration file locally
        │
        ▼
2. Test against staging database (copy of production schema)
        │
        ▼
3. Commit migration file to git
        │
        ▼
4. CI/CD pipeline runs migration against production
   (only AFTER deployment succeeds)
        │
        ▼
5. Verify migration completed (check logs, run smoke tests)

The Safe Migration Pattern

Tell your AI tool: “Create a migration that adds a contributions table with columns: id (UUID primary key), user_id (foreign key to users), amount (integer, must be positive), cycle_id (foreign key to cycles), created_at (timestamp with default). Also create a rollback function that drops the table if needed.”

Why this matters: Every migration needs a rollback path. If something goes wrong mid-deployment, you need to undo the change cleanly.

Senior Moves for Migrations

  1. Never drop a column in the same migration that adds its replacement. Deploy the new column first, update all code to use it, then drop the old column in a separate migration.
  2. Always write a down function. If a migration fails mid-way, you need a clean rollback path.
  3. Test migrations against a copy of production data. Schema-only tests miss constraint violations, foreign key issues, and data type mismatches.
  4. Use lock timeouts. A migration that locks a table for 10 minutes will block every user request. Set lock_timeout = '5s' on PostgreSQL migrations.

08. Incident Response: When Things Break

Things will break. The difference between a junior and a senior is how fast they detect, respond, and recover.

The Incident Response Playbook

DETECT (automated)
│  Monitoring alerts fire (error rate spike, latency spike, uptime check fails)
│
├──▶ ASSESS (human, < 5 minutes)
│    Is it user-facing? How many users affected? Is data at risk?
│
├──▶ COMMUNICATE (if user-facing)
│    Status page update: "Investigating reports of [issue]"
│
├──▶ MITIGATE (fastest path to recovery)
│    ├── Rollback the last deployment? (most common fix)
│    ├── Scale up resources? (traffic spike)
│    ├── Feature flag off the broken feature?
│    └── Failover to backup region? (infrastructure failure)
│
├──▶ RESOLVE
│    Service restored. Confirm via monitoring dashboards.
│
└──▶ RETROSPECTIVE (within 48 hours)
     What caused it? Why didn't CI catch it? How do we prevent it next time?

The Rollback Pattern

The fastest recovery is almost always rolling back to the last known good state:

# Vercel — instant rollback to previous deployment
npx vercel rollback

# Docker — roll back to previous image tag
docker pull myapp:v2.3.0  # Previous version
docker-compose up -d      # Restart with old image

# Database — if migration caused the issue
npx drizzle-kit migrate:rollback

The rule: If you can’t rollback within 5 minutes, your deployment process is too complex.


Key Takeaways

ConceptMental ModelSenior Insight
Production MindsetContainment walls around codePre-deployment checklist catches 90% of outages before they happen
Environment VariablesSecrets in server only, never clientValidate at boot, rotate periodically, never delete old before verifying new
CI/CDAutomated validation before every mergeLint → Type Check → Test → Build — all must pass, no exceptions
DockerImmutable, reproducible environmentsMulti-stage builds, .dockerignore, health checks, never run as root
Rate LimitingProtect your API from abuseThree layers: edge, gateway, application — each with different limits
Structured LoggingJSON over console.logTimestamp + level + message + context — queryable, alertable, indexable
MigrationsTest against staging, deploy via CINever drop columns in the same migration that adds replacements
Incident ResponseDetect → Assess → Mitigate → RetrospectiveThe fastest fix is almost always a rollback