Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 15 min · revision 3

What Changes Between Your Laptop and Production

See which laptop assumptions break when a service runs as containers with several replicas: disposable disks, CPU limits, proxies in front, fail-fast configuration and signals from the orchestrator.

Contentsand lesson path

What you will learn

  • Run the service under a production ASGI server setup with a justified worker and process count, correct forwarded-header handling behind a reverse proxy, and request timeouts and body-size limits.
  • Validate configuration at startup so the process fails fast on missing or malformed settings, with secrets supplied by the runtime environment rather than code or images.

Prerequisites: Database Schema Migrations

01. Why it matters

Suppose a FastAPI service passes every test on your laptop. In its first week on Kubernetes, uploaded photos vanish after a deploy, p99 latency jumps under a CPU limit although average CPU use looks low, HTTPS redirects loop, and a release with a missing variable starts cleanly and fails hours later on the first checkout. None of these is a bug in the code you tested. Each comes from an assumption that held on the laptop and does not hold in production. This lesson names those assumptions, so you can check for them before the first incident instead of after it.

02. Localhost assumptions and production reality

While you build a backend service with a framework such as FastAPI or Express, you run it for weeks on your own machine, for example with uvicorn main:app --reload on localhost:8000. That environment is simple and forgiving:

  • One process on its own host: The application runs as a single process with the whole machine's disk, memory and CPU. There are no other containers, resource quotas or noisy neighbours.
  • A disk that keeps your files: Files saved to ./data survive code edits and reboots, because your laptop's disk belongs to you.
  • No layers in between: Requests travel over the loopback interface (127.0.0.1) without passing reverse proxies, load balancers, web application firewalls (WAFs) or TLS-terminating ingress controllers.
  • Few requests at a time: Requests arrive one by one or in small bursts. When something crashes, you read the traceback in the terminal and restart the process.

When the same service runs as containers under an orchestrator such as Kubernetes, Amazon ECS or Nomad, each of these assumptions can fail. Container filesystems are thrown away, replicas come and go with autoscaling, CPU limits throttle bursts, requests pass several network hops, and the orchestrator sends lifecycle signals (SIGTERM, then SIGKILL) without anyone at a keyboard.

03. Five shifts: disposability, CPU, proxies, configuration and shutdown

Moving a service from your laptop to production means designing for five shifts.

1. Disposable containers and stateless processes. In a cluster, any container can be replaced at any time: the orchestrator evicts Pods to rebalance nodes, runs rolling updates and replaces failed machines. Anything written to the container's own writable layer, such as uploaded photos, in-memory sessions or a SQLite file, is lost when the container is replaced. The Twelve-Factor App calls for stateless processes that share nothing: treat the local filesystem as scratch space and keep durable state in backing services such as PostgreSQL, Redis or object storage (Amazon S3). Logs follow the same rule: a log file inside the container is deleted with it, often just when you need it to explain a crash. Write logs to stdout and stderr instead; the container runtime captures both streams, and a log agent on the node ships them to central storage, so they outlive the container.

2. Several processes and CPU quotas. On your laptop, an async Python event loop has a multi-core CPU with plenty of spare capacity for bursts. In production, containers usually get CPU limits (e.g. resources.limits.cpu: "2", or 2000 millicores). The Linux scheduler enforces a limit as a quota per 100 ms period: a container that uses its quota early in the period is paused until the next one starts (CFS throttling). And with the standard CPython build, the Global Interpreter Lock (GIL) lets one Uvicorn process run Python code on only one core at a time. To use four CPUs, run several worker processes, managed by Uvicorn or Gunicorn.

3. Proxies, TLS and header trust. Locally, the client connects straight to the app over plain HTTP. In production, a user might connect over HTTPS to a CDN, which forwards to a cloud load balancer, which forwards to an ingress proxy (Nginx or Envoy), which sends plain HTTP over the private network to your container. Your application then sees the proxy's private IP (such as 10.0.2.14) as the client, and request.url.scheme is http instead of https. Unless the app reads the forwarded headers (X-Forwarded-For, X-Forwarded-Proto), and only from your own proxies' addresses, HTTPS redirects can loop and logs record the proxy instead of the real client.

4. Configuration that fails fast. Locally, a developer might hardcode a database connection string or tolerate a missing environment variable until hitting a specific endpoint. In production, configuration should come from the environment at run time, as environment variables or mounted secret files. The service should fail fast at start-up: if a required setting (such as the database URL or a webhook secret) is missing or malformed, it exits at once with a clear message, so a bad release never becomes ready for traffic.

The example below uses pydantic-settings with env_prefix="APP_", so every field is read from a prefixed variable: database_url comes from APP_DATABASE_URL, debug from APP_DEBUG. Setting plain DATABASE_URL does nothing, and the validation error names the field (database_url), not the variable, so remember the prefix when you read it. A field that has a default is the dangerous case: an unprefixed variable is ignored without any error, and the service starts with the default value. A prefix is worth having: it keeps your settings apart from variables that the platform or other tools set.

5. Graceful shutdown and connection draining. You stop a development server with Ctrl+C. An orchestrator stops old containers during every rolling release: it sends SIGTERM to the old Pod while, at the same time, removing it from the Service endpoints. If the service stops abruptly on SIGTERM, requests and uploads in flight are cut off and clients see errors such as 502 Bad Gateway. A well-behaved service stops accepting new connections and gives the requests in flight a grace period (30 seconds by default in Kubernetes) to finish; lesson 3 shows how, and why a short delay before shutdown helps.

Python · settings_check.py
import sys

from pydantic import Field, PostgresDsn, ValidationError
from pydantic_settings import BaseSettings, SettingsConfigDict


class ProductionSettings(BaseSettings):
    # Every field is read from an APP_-prefixed variable: APP_DATABASE_URL, ...
    model_config = SettingsConfigDict(env_prefix="APP_")

    app_env: str = Field("production", pattern="^(development|staging|production)$")
    database_url: PostgresDsn
    redis_url: str
    debug: bool = False
    allowed_proxy_cidrs: list[str] = ["10.0.0.0/8", "172.16.0.0/12"]
    port: int = 8000
    max_workers: int = Field(2, ge=1, le=16)
    graceful_timeout_seconds: int = Field(30, ge=5, le=120)


def validate_production_environment() -> ProductionSettings:
    try:
        # Build the settings at start-up, before the server opens its port
        settings = ProductionSettings()
    except ValidationError as err:
        # Fail fast. Print field and message only: str(err) would also print
        # the raw input values, secrets included (lesson 4)
        for error in err.errors():
            field = ".".join(str(loc) for loc in error["loc"])
            sys.stderr.write(f"FATAL: config {field}: {error['msg']}\n")
        sys.exit(1)
    if settings.app_env == "production" and settings.debug:
        sys.stderr.write("FATAL: APP_DEBUG=true is forbidden in production\n")
        sys.exit(1)
    return settings


if __name__ == "__main__":
    config = validate_production_environment()
    print(f"Service initialized successfully in {config.app_env} mode")
Bash · Run it with prefixed variables, then with unprefixed ones
pip install pydantic==2.14.4 pydantic-settings==2.16.3
export APP_DATABASE_URL=postgresql://app@db:5432/app
export APP_REDIS_URL=redis://cache:6379/0
python settings_check.py
DATABASE_URL=postgresql://app@db:5432/app REDIS_URL=redis://cache:6379/0 \
  env -u APP_DATABASE_URL -u APP_REDIS_URL python settings_check.py
Expected output (Python 3.13, pydantic 2.14.4, pydantic-settings 2.16.3)
Service initialized successfully in production mode
FATAL: config database_url: Field required
FATAL: config redis_url: Field required

04. Check your understanding

Practice check · 3 questions

Container logs, prefixed settings and CPU limits

Three questions on what changes when a service leaves the laptop.

Q1. A service runs with `limits.cpu: "1"`. Its average CPU use is 60%, yet p99 latency shows pauses of tens of milliseconds during bursts. What is a likely cause?
Q2. A settings class uses `env_prefix="APP_"` and has `redis_url: str = "redis://localhost:6379/0"`. The production manifest sets `REDIS_URL=redis://cache:6379/0`, without the prefix. What happens when the service starts?
Q3. A containerised service writes its logs to `/app/logs/app.log` inside the container. Why does the lesson recommend writing them to stdout and stderr instead?
Practice only: not graded, not saved, not evidence.

05. Apply it

Check the service from your skill project against these rules:

  • Do not treat the container disk as persistent: Keep user data and uploads out of the container's filesystem. Store files in object storage (S3, GCS) and write logs to stdout/stderr, unbuffered, so the platform collects them.
  • Validate environment variables at boot: Declare every required setting, its type and its limits in a pydantic-settings BaseSettings class, and make the process exit with code 1 when a required one is missing, so the release stops before it takes traffic.
  • Trust forwarded headers only from your proxies: Behind Nginx or an AWS ALB, run Uvicorn with --proxy-headers and a --forwarded-allow-ips list of your proxies' addresses. Never accept X-Forwarded-For from clients on the Internet.
  • Size workers to the container's CPU limit: Sizing workers to the host's cores on a shared node starts far too many processes, which the CPU limit then throttles. Work out the count from resources.limits.cpu.

The next lesson covers worker processes, the reverse proxy in front of them, and protection against slow clients.

06. Review prompt

Without looking back, name four laptop assumptions that fail when a service runs in containers. Explain why files on a container's disk break the Twelve-Factor rule of stateless processes, how a reverse proxy changes the client IP and scheme your app sees, and why failing at start-up is better than discovering a missing setting during live traffic.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check