Skip to content
MiraiTech
All writing
Career

· 8 min read

The work between a prototype and production

What a working demo still needs before real users arrive: error handling, database migrations, monitoring, security, performance work and a readiness checklist.

The demo worked

Every prototype works, and that's the trap. The demo runs on localhost, the database has twelve rows, the only user is you and the network is a loopback interface. Then someone says "ship it," and you find out how much work sits between a working demo and a production system.

We've taken enough projects from prototype to production to know where that work goes. This is what we wish someone had told us before our first production deploy.

Error handling is an architecture decision

The prototype has try/catch blocks that log to the console. Production needs one error handling strategy across the whole stack. This is where most teams pile up tech debt fastest, because error handling feels like cleanup work rather than design work.

We use a Result type pattern inspired by Rust. Every function that can fail returns either a success or a typed error, and thrown exceptions never cross module boundaries.

lib/result.ts
type Success<T> = { ok: true; value: T };
type Failure<E> = { ok: false; error: E };
type Result<T, E = AppError> = Success<T> | Failure<E>;
 
function ok<T>(value: T): Success<T> {
  return { ok: true, value };
}
 
function err<E>(error: E): Failure<E> {
  return { ok: false, error };
}
 
// Domain errors are explicit, not stringly typed
type AppError =
  | { code: "NOT_FOUND"; resource: string; id: string }
  | { code: "VALIDATION"; field: string; message: string }
  | { code: "UNAUTHORIZED"; reason: string }
  | { code: "RATE_LIMITED"; retryAfter: number }
  | { code: "UPSTREAM_FAILURE"; service: string; statusCode: number };
 
export { ok, err, type Result, type AppError };
services/project.ts
async function getProject(
  id: string,
  userId: string
): Promise<Result<Project>> {
  const project = await db.query.projects.findFirst({
    where: eq(schema.projects.id, id),
  });
 
  if (!project) {
    return err({ code: "NOT_FOUND", resource: "project", id });
  }
 
  if (project.organizationId !== userId) {
    return err({
      code: "UNAUTHORIZED",
      reason: "Project belongs to another organization",
    });
  }
 
  return ok(project);
}

Error states become visible in the type system. You can't forget to handle them, because the compiler won't let you access .value without checking .ok first.

Database migrations

The prototype uses db push to sync schema changes. Production uses migrations, and migrations are unforgiving.

Rules we learned the hard way

  1. Never rename a column in one step. Add the new column, backfill data, deploy code that reads both, drop the old column. Three deploys minimum.
  2. Every migration must be reversible. If you can't write the down migration, you don't understand the up well enough.
  3. Test migrations against a production-sized dataset. A migration that runs in 2ms on 100 rows can lock a table for 40 minutes on 2 million rows.
migrations/0024_add_project_slug.sql
-- Step 1: Add nullable column (safe, no lock)
ALTER TABLE projects ADD COLUMN slug TEXT;
 
-- Step 2: Backfill in batches (avoid long-running transactions)
-- Run this as a script, NOT in the migration file
-- UPDATE projects SET slug = generate_slug(title)
-- WHERE slug IS NULL
-- LIMIT 1000;
 
-- Step 3: After backfill is verified complete
-- ALTER TABLE projects ALTER COLUMN slug SET NOT NULL;
-- CREATE UNIQUE INDEX CONCURRENTLY idx_projects_slug ON projects(slug);
Migration risk levelExampleStrategy
LowAdd nullable columnSingle migration, deploy freely
MediumAdd index on large tableUse CONCURRENTLY, run off-peak
HighRename columnMulti-step expand/contract pattern
CriticalChange column typeNew column + backfill + swap reads
AvoidDrop column with no backupJust don't. Add a deprecated_at flag

Logging, monitoring and alerting

The prototype has console.log. Production needs observability, which is a different thing.

Logs record what happened. Monitoring shows what is happening now, and alerts should fire only when something needs attention. Most teams conflate the three and end up with noisy logs nobody reads and alerts everyone ignores.

Our observability stack

We settled on three layers:

  • Structured logging, with correlation IDs that trace a request across services.
  • Metrics for business-critical numbers: response times, error rates, queue depths.
  • Alerts only on conditions someone can act on. If an alert doesn't have a runbook, it shouldn't exist.
lib/logger.ts
import { createId } from "@paralleldrive/cuid2";
 
type LogContext = {
  requestId: string;
  userId?: string;
  service: string;
  [key: string]: unknown;
};
 
function createLogger(baseContext: Partial<LogContext>) {
  const context: LogContext = {
    requestId: baseContext.requestId ?? createId(),
    service: baseContext.service ?? "unknown",
    ...baseContext,
  };
 
  return {
    info(message: string, data?: Record<string, unknown>) {
      emit("info", message, { ...context, ...data });
    },
    warn(message: string, data?: Record<string, unknown>) {
      emit("warn", message, { ...context, ...data });
    },
    error(message: string, error?: Error, data?: Record<string, unknown>) {
      emit("error", message, {
        ...context,
        ...data,
        error: error
          ? { message: error.message, stack: error.stack, name: error.name }
          : undefined,
      });
    },
  };
}
 
function emit(level: string, message: string, data: Record<string, unknown>) {
  const entry = JSON.stringify({
    timestamp: new Date().toISOString(),
    level,
    message,
    ...data,
  });
  process.stdout.write(entry + "\n");
}

Security

The prototype trusts all input. Production trusts nothing.

The minimum we ship with

  • Input validation at the boundary. Every API endpoint validates with Zod schemas. No raw req.body access anywhere.
  • Rate limiting per endpoint, not globally. Login gets 5 attempts per minute. Search gets 30. File upload gets 3.
  • CSRF tokens on every state-changing request. That includes API routes behind authentication.
  • Content Security Policy headers. Strict enough to block inline scripts, loose enough not to break the app.
  • Dependency auditing in CI. npm audit runs on every PR. Critical vulnerabilities block merge.

Performance: measure first

The prototype is fast because it's empty, and production is slow because it's real. The instinct is to optimize everything; resist it. Profile first, fix the bottleneck you find, then measure again.

The usual three

We've profiled dozens of production apps, and the same three issues account for roughly 80% of the performance problems we see:

  1. N+1 queries. The ORM fetches a list, then fetches related data one row at a time. Fix with eager loading or dataloaders.
  2. Missing database indexes. A full table scan on a 500K row table takes 400ms. Adding the right index drops it to 2ms.
  3. Unoptimized images and fonts. The browser downloads 4MB of assets before rendering anything useful. Fix with proper formats, lazy loading and font subsetting.

Everything else (memoization, code splitting, edge caching) is optimization. These three are bug fixes.

Team handoffs are a system design problem

One person built the prototype and holds the whole system in their head. A team maintains production, so the system has to make sense to people who didn't build it.

What every handoff includes

  • Architecture Decision Records (ADRs) for every non-obvious choice, explaining why we built it that way and which alternatives we rejected.
  • A RUNBOOK.md covering common operational tasks: how to deploy, roll back, restart services and investigate common alerts.
  • Seed scripts that build a realistic local development environment in one command: thousands of rows instead of 12, with realistic relationships and edge cases.

Production readiness checklist

After enough projects, we wrote down what "production ready" means at MiraiTech. A project doesn't ship until every item on this list has an owner and a status.

CategoryItemStatus required
ReliabilityError handling covers all API boundariesComplete
ReliabilityHealth check endpoint exists and is monitoredComplete
DataMigration strategy documented and testedComplete
DataBackup and restore procedure verifiedComplete
SecurityInput validation on all endpointsComplete
SecurityRate limiting configured per routeComplete
PerformanceCore Web Vitals passing on key pagesComplete
PerformanceDatabase queries profiled under loadComplete
OperationsStructured logging with correlation IDsComplete
OperationsAlerting configured with runbooksComplete
TeamArchitecture decisions documentedComplete
TeamLocal dev setup runs in under 5 minutesComplete

Written by the MiraiTech team in Tokyo

If something here is wrong, or you are working on a similar problem, write to us at contact@mirai-tech.net.