Logging, Config, and Safe Deployments in Python
Difficulty: Hard | Companies: Google, Meta, Amazon, Netflix, Stripe
Interviewers use production questions to find out whether you have actually operated something you wrote. The distinguishing answers are about failure: what happens when the dependency is down, when the config is missing, and when the deploy must be undone in a hurry.
Prerequisites
- !HTTP services and process lifecycles
- !Environment variables and 12-factor configuration
- !Basic Docker and CI familiarity
What You'll Learn
- 1Emit structured logs that a query language can filter
- 2Validate configuration once at startup instead of deep in a request
- 3Instrument request counts, latency, and health
- 4Deploy with a strategy that assumes rollback is normal
Treat logs as data, not as prose
Free-text logs look fine in a terminal and become useless the moment a service has more than one instance. Structured logging turns every line into a record with stable keys, so a single query can answer "give me all 500s for checkout in the last fifteen minutes that had a retry", which is impossible when the answer is buried inside sentences that vary by author.
The design that scales has three parts. A formatter emits one JSON object per line. A context variable carries a request id through async and threaded call stacks so unrelated work never interleaves ambiguously. And a filter attaches that id to every record automatically, which means individual call sites cannot forget it.
import json
import logging
import sys
import uuid
from contextvars import ContextVar
from datetime import datetime, timezone
request_id: ContextVar[str] = ContextVar("request_id", default="-")
class JsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
payload = {
"ts": datetime.now(timezone.utc).isoformat(),
"level": record.levelname,
"logger": record.name,
"msg": record.getMessage(),
"module": record.module,
"line": record.lineno,
"request_id": request_id.get(),
}
if record.exc_info:
payload["exception"] = self.formatException(record.exc_info)
extra = getattr(record, "fields", None)
if extra:
payload["fields"] = extra
return json.dumps(payload, default=str)
def configure_logging(level: str = "INFO") -> logging.Logger:
root = logging.getLogger()
root.setLevel(level)
root.handlers.clear()
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter())
root.addHandler(handler)
return root
logger = configure_logging()
def log_request(method: str, path: str, status: int, ms: float) -> None:
logger.info("request", extra={"fields": {
"method": method, "path": path,
"status": status, "duration_ms": round(ms, 2)}})
Equally important is what stays out of the logs. Passwords, authorization headers, and personal data must be redacted at the formatter, because logs end up in third-party aggregators with looser access control than your database. Log identifiers and counts, not payloads. And prefer a handful of meaningful fields over a megabyte of nested context — someone will page on this at three in the morning.
Configuration that fails fast
A configuration that silently falls back to a default is how a production service ends up writing to SQLite because DATABASE_URL was misspelled. Validate everything once, at startup, and refuse to boot if a required value is missing or malformed. Crashing in the first second is a feature: the orchestrator restarts the container, the deploy rolls back, and no request ever sees a half-configured process.
import os
from dataclasses import dataclass, field
from functools import lru_cache
VALID_ENVS = {"development", "staging", "production"}
@dataclass(frozen=True)
class Settings:
environment: str
database_url: str
secret_key: str
log_level: str = "INFO"
workers: int = 4
allowed_origins: tuple = field(default_factory=lambda: ("*",))
@classmethod
def from_env(cls) -> "Settings":
env = os.environ.get("ENVIRONMENT", "development")
if env not in VALID_ENVS:
raise RuntimeError(f"ENVIRONMENT must be one of {VALID_ENVS}")
db = os.environ.get("DATABASE_URL")
if not db:
raise RuntimeError("DATABASE_URL is required")
secret = os.environ.get("SECRET_KEY", "")
if env == "production" and len(secret) < 32:
raise RuntimeError("SECRET_KEY must be at least 32 chars in production")
return cls(
environment=env,
database_url=db,
secret_key=secret,
log_level=os.environ.get("LOG_LEVEL", "INFO"),
allowed_origins=tuple(
o.strip() for o in os.environ.get("ALLOWED_ORIGINS", "*").split(",")
),
)
@lru_cache(maxsize=1)
def get_settings() -> Settings:
return Settings.from_env()
frozen=True prevents runtime mutation, lru_cache gives you one validated instance instead of re-parsing on every call, and the environment-specific rule — a longer secret key in production — is stated where it cannot be bypassed. The interview follow-up is usually about twelve-factor principles: config comes from the environment, secrets are injected rather than baked into the image, and the same artifact moves through environments unchanged.
Metrics and health checks that mean something
Logs tell you what happened to one request; metrics tell you what is happening to all of them. Four instruments cover most needs: a counter of requests by method, route, and status; a histogram of latency; a gauge of in-flight work; and a counter of errors by type. From those you can build the alerts that matter — error rate above threshold, p99 latency regression, saturation climbing.
Health checks deserve more thought than they usually get. A liveness probe that merely returns 200 tells the orchestrator the process is awake, which is useful only for detecting deadlocks. A readiness probe must actually verify dependencies, because routing traffic to an instance whose database connection has died converts one outage into many.
import time
from contextlib import contextmanager
LATENCY = {"p50": 0.0, "p95": 0.0, "count": 0, "errors": 0}
_SAMPLES: list = []
@contextmanager
def timed(operation: str):
start = time.perf_counter()
try:
yield
except Exception:
LATENCY["errors"] += 1
raise
finally:
elapsed = time.perf_counter() - start
_SAMPLES.append(elapsed)
if len(_SAMPLES) > 1000:
_SAMPLES.pop(0)
ordered = sorted(_SAMPLES)
LATENCY["p50"] = ordered[len(ordered) // 2]
LATENCY["p95"] = ordered[int(len(ordered) * 0.95)]
LATENCY["count"] += 1
def readiness(checks: dict) -> tuple:
failures = [name for name, fn in checks.items() if not fn()]
return (200, {"status": "ok"}) if not failures else (
503, {"status": "degraded", "failing": failures})
Percentiles computed from a bounded in-process sample are approximate, which is fine for a dashboard and wrong for billing; that distinction is a good thing to raise unprompted. When one instance is not enough, aggregate at scrape time and keep the application code simple.
Containers that behave in production
A container image is a deploy artifact, so it should be small, reproducible, and unprivileged. Start from a slim base, install dependencies from a lock file in a separate layer so code changes do not invalidate the dependency cache, copy the application as a non-root user, and declare a health check the orchestrator can call.
Two Python-specific pitfalls show up repeatedly. First, the image must contain exactly the dependencies you tested: use a pinned lock file, not a floating requirements.txt, or a rebuild can silently pull a new minor version. Second, avoid running the development server — uvicorn or gunicorn with an explicit worker count tuned to CPU and memory, and a WEB_CONCURRENCY you can change without rebuilding.
| Concern | Default that bites you | Production choice |
|---|---|---|
| Server | Flask dev server or __main__ | gunicorn or uvicorn behind a proxy |
| Workers | One process by default | Roughly 2×CPU, adjusted for memory |
| Files in image | Whole repository copied | .dockerignore, only runtime files |
| User | root inside the container | Dedicated non-root user |
| Secrets | Baked into the image | Injected at runtime from a vault |
| Logs | Written to local files | Streamed to stdout for collection |
Deploy, observe, then roll back
Every deploy strategy is a different answer to the same question: how much traffic sees an unproven build at once? Rolling updates replace instances gradually, which is cheap and works for stateless services. Canary deployments send a small slice of real traffic to the new version and promote it only if error rates hold — the only strategy that catches problems a load test missed. Blue-green keeps two full environments and switches a load balancer, which makes rollback a switch rather than a rebuild, at the cost of running double capacity.
Whichever you choose, the pipeline must gate on something real: lint, unit tests, a container build, a smoke test against the built image, then deploy with automatic rollback when health checks fail for a defined window. A rollback that requires a human to interpret a dashboard at midnight is not a rollback plan; it is a hope.
Graceful shutdown is part of correctness
When a container receives a termination signal, work in flight does not stop existing. Draining properly means: stop accepting new connections, let in-flight requests finish within a deadline, flush buffers and logs, close database pools, then exit. Without that sequence you get truncated log lines, half-written writes, and clients retrying operations that half-succeeded.
import signal
import threading
import time
class GracefulStop:
def __init__(self, timeout: float = 25.0):
self.stopping = threading.Event()
self.timeout = timeout
self._hooks = []
def on_shutdown(self, hook) -> None:
self._hooks.append(hook)
def install(self) -> None:
for sig in (signal.SIGTERM, signal.SIGINT):
signal.signal(sig, self._begin)
def _begin(self, signum, frame) -> None:
self.stopping.set()
deadline = time.time() + self.timeout
for hook in self._hooks:
remaining = deadline - time.time()
if remaining <= 0:
break
try:
hook()
except Exception as exc:
print(f"shutdown hook failed: {exc}")
stop = GracefulStop()
stop.on_shutdown(lambda: pool.dispose())
stop.on_shutdown(flush_buffers)
stop.install()
while not stop.stopping.is_set():
stop.stopping.wait(timeout=1.0)
Set the termination grace period in the orchestrator longer than your application timeout, or the platform will kill the process mid-drain and the whole exercise is theatre. The same principle applies to background consumers: commit or requeue the message you are handling before acknowledging it, so a restart never loses work.
Common Mistakes
Logging with print and interpolated sentences
Fix: Emit one JSON record per line with stable field names so queries and alerts can rely on them.
Reading configuration deep inside a request handler
Fix: Parse and validate once at startup, crash if invalid, and pass a frozen settings object around.
A liveness probe that returns 200 unconditionally
Fix: Split liveness from readiness and make readiness fail when a critical dependency is unavailable.
Deploying without a rehearsed rollback
Fix: Gate deploys on a smoke test and automate rollback on failed health checks inside a fixed window.
Best Practices
- Stream structured logs to stdout and let the platform collect them
- Pin dependencies in a lock file and build images that contain exactly what you tested
- Instrument request count, latency percentiles, and errors before you need them
- Run containers as a non-root user with a health check the orchestrator understands
- Give shutdown a deadline that fits inside the platform's grace period
- Keep a dashboard and an alert for every failure mode you claim to handle
Interview Questions
Q1: What makes a log line useful during an incident?
Structured JSON with a request id, level, duration, and stable field names, so you can filter and aggregate rather than grep through sentences.
Q2: Why should configuration validation crash the process?
Failing at startup keeps a misconfigured instance from serving traffic; the orchestrator restarts or rolls back before any request sees bad config.
Q3: Liveness or readiness: which probe fails when the database is down?
Readiness. Liveness should only fail when the process cannot make progress at all, otherwise restarts mask the real problem.
Q4: Compare rolling, canary, and blue-green deployments.
Rolling replaces instances gradually; canary exposes a small slice of real traffic and promotes on healthy signals; blue-green keeps two environments and switches traffic, making rollback a switch.
Q5: What does graceful shutdown guarantee?
New work stops, in-flight work finishes within a deadline, buffers and pools close, and the process exits — so no request is truncated mid-write.
Q6: How many workers should a Python service run?
It depends on whether the workload is I/O or CPU bound: roughly two per core for I/O-heavy services, closer to one per core for CPU-bound ones, bounded by memory.
Key Takeaways
- Structured logs with a request id turn debugging into querying
- Validate configuration once at startup and fail before serving traffic
- Metrics cover the fleet; logs explain the individual request
- Container hygiene — non-root, pinned deps, real health check — is not optional
- Pick a deploy strategy by how much traffic can see an unproven build
- Graceful shutdown plus a rehearsed rollback is what makes deploys boring