Situational DevOps questions rarely test whether you remember a flag. They test whether you can ship a change to a running system without hurting users, notice when something breaks, and recover quickly. Strong answers name the mechanism, the trade-off and the failure mode in the same breath. This guide covers the ideas behind those answers: how rollouts actually replace instances, why health checks and shutdown handling matter, how to change a database schema under live traffic, how flags separate deploy from release, why artifacts should be built once, how SLOs drive alerting, how infrastructure and secrets are managed, and how incidents are run. Each concept uses an invented system so you can reason from a concrete case rather than a slogan.
Study order
If time is short, go in this order.
- Rolling, blue-green and canary deployments
Almost every situational question starts with how a change reaches production; knowing rollout mechanics and their mixed-version window frames everything else.
- Schema changes with expand and contract
Schema changes under live traffic are where deploys most often go wrong, and expand and contract is a favourite senior-level probe.
- Readiness, liveness and graceful shutdown
Explains the 502s and restart loops behind many real outages and shows you understand what the orchestrator actually does.
- SLOs, error budgets and alerting on symptoms
Interviewers expect you to define reliability in user terms and to know what deserves a page.
- Feature flags and separating deploy from release
Separating deploy from release is the fastest mitigation tool you have and a common follow-up to rollout questions.
- Incident response and blameless postmortems
Shows judgement under pressure: mitigate first, communicate, then fix the system rather than the person.
- Build once, promote the same artifact
Underpins reproducible releases and reliable rollbacks; a short but frequently checked principle.
- Configuration and secrets management
Security and misconfiguration questions come up in most operating discussions.
- Infrastructure as code, state and drift
Rounds out the picture with state, plan review and drift, which matter once you own infrastructure.
Rolling, blue-green and canary deployments
A rolling deployment replaces instances a few at a time. In Kubernetes, maxSurge controls how many extra pods may exist above the desired count and maxUnavailable how many may be missing. With maxUnavailable: 0 capacity never drops, but the rollout needs spare cluster room for the surge pods. During a rolling update, old and new versions serve traffic at the same time, so every change must be compatible in both directions for that window.
Blue-green runs a full second environment and switches traffic at once, usually at the load balancer or service selector. Rollback is a switch back, which is fast, but you pay for double capacity and the shared database still has to work with both versions. Canary sends a small slice of traffic, say 5 percent, to the new version, compares its error rate and latency with the baseline, then widens the slice in steps.
Pick by risk and cost. Rolling is the cheap default for stateless services. Blue-green suits releases where you want an instant cutover and can afford the duplicate. Canary is the right answer when you need real production signal before full exposure, and it only works if you have per-version metrics to compare.
YAML
apiVersion: apps/v1
kind: Deployment
metadata:
name: ledger-api
namespace: brightpay
spec:
replicas: 6
revisionHistoryLimit: 5
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 0
minReadySeconds: 15
selector:
matchLabels:
app: ledger-api
template:
metadata:
labels:
app: ledger-api
spec:
terminationGracePeriodSeconds: 40
containers:
- name: api
image: ghcr.io/brightpay/ledger-api:3f9c2e1
ports:
- containerPort: 8080
readinessProbe:
httpGet:
path: /healthz/ready
port: 8080
periodSeconds: 5
failureThreshold: 2Brightpay's ledger-api replaces one pod at a time, never drops below 6 ready pods, and waits 15 seconds of readiness before counting a new pod as available.
Traps
- Assuming a rolling update is atomic. For several minutes old and new pods serve requests together, so API, message and schema changes must tolerate both versions.
- Setting
maxUnavailable: 0on a cluster with no spare capacity. The surge pod stays Pending and the rollout stalls untilprogressDeadlineSecondsmarks it failed. - Running a canary without per-version metrics. If dashboards aggregate all pods, a 5 percent canary throwing errors is invisible in the average.
- Claiming blue-green makes rollback free. Switching traffic back is instant, but any data the green version wrote in a new format is still there.
Readiness, liveness and graceful shutdown
Readiness answers whether this instance should receive traffic right now. Liveness answers whether the process is stuck and needs a restart. They are different questions: a pod that is warming its cache or draining is alive but not ready. If you point liveness at a check that calls the database, a database blip restarts every pod at once and turns a partial outage into a full one.
On shutdown, Kubernetes sends SIGTERM and, in parallel, removes the pod from service endpoints. Those two things are not ordered, so for a few seconds the load balancer can still route new requests to a process that is exiting. The usual fix is to keep serving for a short delay after SIGTERM, fail readiness, stop accepting new connections, let in-flight requests finish, then exit before terminationGracePeriodSeconds runs out and SIGKILL arrives.
Workers need the same care: stop pulling new jobs, finish or release the current one, and make sure jobs are idempotent so a killed worker that leaves a job half done can safely have it retried.
TypeScript
import http from "node:http";
let draining = false;
const server = http.createServer((req, res) => {
if (req.url === "/healthz/ready") {
res.writeHead(draining ? 503 : 200).end(draining ? "draining" : "ok");
return;
}
if (req.url === "/healthz/live") {
res.writeHead(200).end("ok");
return;
}
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify({ orderId: 1042, status: "posted" }));
});
server.listen(8080, () => console.log("listening on 8080"));
process.on("SIGTERM", () => {
draining = true;
// Keep serving while endpoints and load balancers catch up.
setTimeout(() => {
server.close(() => process.exit(0));
server.closeIdleConnections();
// Hard stop well before the 40s grace period ends.
setTimeout(() => process.exit(1), 20_000).unref();
}, 10_000);
});Readiness flips to 503 on SIGTERM, the server keeps answering for 10 seconds, then stops accepting connections and exits once in-flight requests finish.
Traps
- Making liveness depend on downstream services. A slow database then causes restart loops across the whole fleet.
- Running the app behind a shell entrypoint that does not forward signals, so the process never sees SIGTERM and is killed after the grace period.
- Setting a drain delay plus request timeout longer than
terminationGracePeriodSeconds; SIGKILL cuts requests off anyway. - Exiting immediately on SIGTERM and assuming the load balancer already stopped sending traffic. That race produces a burst of 502s on every deploy.
Schema changes with expand and contract
Because old and new code run side by side during a deploy, and because you may need to roll the code back, a schema change must never break the version that is currently live. Expand and contract splits a breaking change into compatible steps: add the new structure, make the code write to both and read safely, backfill, switch reads, and only then remove the old structure in a later release.
Take Tablehop, a restaurant booking service renaming customers.phone to phone_e164. Release 1 adds a nullable column and writes both. A batched backfill copies existing rows. Release 2 reads from the new column. Release 3, days later once rollback to release 1 is no longer plausible, drops the old one. Each step can be deployed and rolled back on its own.
Also think about locks. In PostgreSQL, adding a nullable column without a volatile default is a quick catalog change, but building an index without CONCURRENTLY blocks writes for the duration, and a long UPDATE across millions of rows holds row locks and bloats the table. Batch large backfills and set a lock_timeout so a migration waiting on a lock does not queue every other query behind it.
SQL
-- Release 1: expand (safe while old code is running)
SET lock_timeout = '3s';
ALTER TABLE customers ADD COLUMN phone_e164 text;
CREATE INDEX CONCURRENTLY idx_customers_phone_e164 ON customers (phone_e164);
-- Backfill in batches of 10,000, repeated by a job until it updates 0 rows
UPDATE customers
SET phone_e164 = phone
WHERE id IN (
SELECT id FROM customers
WHERE phone_e164 IS NULL AND phone IS NOT NULL
ORDER BY id
LIMIT 10000
);
-- Release 2: application reads phone_e164, still writes both
-- Release 3: contract (only after release 1 can no longer be rolled back to)
ALTER TABLE customers DROP COLUMN phone;Tablehop renames a column in three independently deployable steps. Note that CREATE INDEX CONCURRENTLY cannot run inside a transaction block.
Traps
- Renaming or dropping a column in the same release as the code change. Old pods still running during the rollout start failing immediately.
- Running the backfill as one giant UPDATE, which holds locks for a long time, generates heavy WAL and can lag replicas.
- Forgetting that rollback of code is easy but rollback of a destructive migration is not. Contract steps should come well after the expand.
- Adding a NOT NULL constraint before the backfill is complete and all writers populate the new column.
Feature flags and separating deploy from release
A deploy puts code on servers. A release exposes behaviour to users. Feature flags let you do the first without the second: the new checkout flow ships dark, then you enable it for staff, then 1 percent of users, then everyone. If something goes wrong, turning a flag off takes seconds and needs no new build, which is usually faster and safer than redeploying.
Percentage rollouts should be sticky. Hash the user id together with the flag name and compare the bucket to the percentage, so the same user always sees the same variant and raising the percentage from 10 to 20 only adds users. Including the flag name keeps different flags from always targeting the same unlucky users.
Rollback still matters for changes flags cannot cover, such as a dependency upgrade or a memory leak. Keep previous artifacts available, know the exact command to roll back, and prefer rolling back first and debugging second when users are affected. Flags are also debt: each one doubles a code path, so set an owner and a removal date.
TypeScript
import { createHash } from "node:crypto";
function bucket(flag: string, userId: string): number {
const digest = createHash("sha256").update(`${flag}:${userId}`).digest();
return digest.readUInt32BE(0) % 100;
}
export function isEnabled(flag: string, userId: string, rolloutPercent: number): boolean {
if (rolloutPercent <= 0) return false;
if (rolloutPercent >= 100) return true;
return bucket(flag, userId) < rolloutPercent;
}
const users = ["user-8812", "user-0031", "user-4470"];
for (const id of users) {
console.log(id, isEnabled("new-checkout", id, 10));
}A deterministic 10 percent rollout: the same user always lands in the same bucket, so raising the percentage only ever adds users.
Traps
- Using
Math.random()per request for rollouts. Users flip between variants and metrics become meaningless. - Leaving flags in place for months. Untested combinations of old flags become a source of incidents.
- Assuming a flag can undo a data change. If the new path already wrote rows in a new format, switching it off does not convert them back.
- Having no fallback when the flag service is unreachable. Decide on a safe default and cache the last known values.
Build once, promote the same artifact
An artifact, typically a container image, should be built once per commit and then promoted unchanged through staging and production. What you tested is then exactly what you run. Rebuilding per environment invites drift: a base image tag moved, a dependency resolved to a newer patch, and production runs bytes nobody tested.
Reference images by digest, not by a mutable tag like latest or even a reused version tag. A digest is a content hash, so it cannot point at different contents later. Environment differences belong in configuration injected at runtime, not in the image.
The pipeline itself encodes your release policy: tests and scans gate the build, staging deploys automatically, production waits on a protected environment or approval. Interviewers like to hear that the pipeline is the only path to production, so every change is traceable from commit to running pod.
YAML
name: release
on:
push:
branches: [main]
permissions:
contents: read
packages: write
jobs:
build:
runs-on: ubuntu-latest
outputs:
digest: ${{ steps.push.outputs.digest }}
steps:
- uses: actions/checkout@v4
- uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- id: push
uses: docker/build-push-action@v6
with:
push: true
tags: ghcr.io/brightpay/ledger-api:${{ github.sha }}
deploy-staging:
needs: build
runs-on: ubuntu-latest
environment: staging
steps:
- run: kubectl -n brightpay set image deployment/ledger-api api=ghcr.io/brightpay/ledger-api@${{ needs.build.outputs.digest }}
deploy-production:
needs: [build, deploy-staging]
runs-on: ubuntu-latest
environment: production
steps:
- run: kubectl -n brightpay set image deployment/ledger-api api=ghcr.io/brightpay/ledger-api@${{ needs.build.outputs.digest }}One build, one digest, deployed first to staging and then to a protected production environment. Cluster credential setup is omitted for brevity.
Traps
- Rebuilding the image in each environment and calling it the same release.
- Deploying with
:latest, which makes rollbacks ambiguous and lets nodes run different images under one tag. - Baking environment-specific URLs or secrets into the image, which forces a rebuild per environment and leaks secrets into registries.
- Allowing manual
kubectl applyto production alongside the pipeline, so the cluster no longer matches any recorded change.
SLOs, error budgets and alerting on symptoms
A service level indicator is a measured ratio, such as the share of requests that returned without a 5xx in under 300 ms. A service level objective sets a target for it over a window, for example 99.9 percent over 30 days. The remaining 0.1 percent is the error budget: about 43 minutes of full outage in 30 days, or a proportionally longer period of partial failure. When the budget is spent, the team slows risky releases and works on reliability.
Page on symptoms users feel, not on causes. High CPU on one node is not an emergency if requests are fine. Burn-rate alerts express this well: a burn rate of 1 consumes the budget exactly over the window; a burn rate of 14.4 sustained for one hour consumes 2 percent of a 30-day budget, which is worth waking someone. Requiring both a long and a short window to exceed the threshold makes the alert fire fast and clear fast once the problem stops.
Around that sits observability: metrics for trends and alerting, structured logs with request ids for detail, and traces for latency across services. Use the RED view for request-driven services (rate, errors, duration) and resource saturation for the things underneath.
YAML
groups:
- name: search-gateway-slo
rules:
- alert: SearchGatewayErrorBudgetFastBurn
expr: |
(
sum(rate(http_requests_total{job="search-gateway",code=~"5.."}[1h]))
/
sum(rate(http_requests_total{job="search-gateway"}[1h]))
) > (14.4 * 0.001)
and
(
sum(rate(http_requests_total{job="search-gateway",code=~"5.."}[5m]))
/
sum(rate(http_requests_total{job="search-gateway"}[5m]))
) > (14.4 * 0.001)
labels:
severity: page
annotations:
summary: "search-gateway is burning its 99.9% availability budget 14x too fast"A Prometheus rule for a 99.9 percent SLO: it pages only when both the 1-hour and 5-minute error ratios exceed 14.4 times the allowed rate.
Traps
- Paging on causes like CPU or disk thresholds. It produces alert fatigue while real user-facing failures slip past.
- Setting the SLO at 100 percent. It leaves no budget for deploys or dependencies and is not achievable.
- Averaging latency. Report percentiles such as p99 and compute them from histograms, because averaging precomputed percentiles across instances is mathematically wrong.
- Using high-cardinality labels like user id in metrics, which can overload the metrics backend.
Infrastructure as code, state and drift
Infrastructure as code describes servers, networks, databases and permissions in versioned files, reviewed and applied like application code. Tools such as Terraform compare the desired configuration with a state file and the real provider, then produce a plan of creates, updates and destroys. Read the plan carefully: a renamed resource or a changed immutable attribute can show as destroy-and-recreate, which for a database means data loss.
State must be stored remotely with locking, so two engineers or two pipeline runs cannot apply at once and corrupt it. Split state by environment and by blast radius, so a change to a staging DNS record cannot touch production networking.
Drift happens when someone changes infrastructure by hand in a console during an incident. Detect it on a schedule by running a plan and treating any diff as a finding, then either codify the manual change or revert it. Kubernetes manifests follow the same idea with GitOps controllers that continuously reconcile the cluster towards what is in the repository.
Shell
#!/usr/bin/env bash
# Nightly drift check for Parcelwise production infrastructure.
set -uo pipefail
cd infra/production || exit 1
terraform init -input=false >/dev/null || exit 1
terraform plan -input=false -lock=false -detailed-exitcode -out=drift.tfplan
status=$?
case "$status" in
0)
echo "No drift detected"
;;
2)
terraform show -no-color drift.tfplan > drift-report.txt
echo "Drift detected, see drift-report.txt"
exit 2
;;
*)
echo "terraform plan failed" >&2
exit 1
;;
esacWith -detailed-exitcode, terraform plan exits 0 for no changes, 2 for pending changes and 1 for errors, which makes drift easy to detect in CI.
Traps
- Keeping state on a laptop or in Git. It contains secrets in plain text and has no locking.
- Applying without reviewing the plan, missing a forced replacement of a stateful resource.
- One giant state for every environment, so every plan is slow and every mistake has maximum blast radius.
- Fixing an incident by hand and never codifying it; the next apply silently reverts the fix.
Configuration and secrets management
Configuration that differs between environments, such as URLs, pool sizes and feature defaults, should be injected at runtime through environment variables or mounted files, not built into the artifact. Validate it at startup and fail fast with a clear message. A service that starts with a missing database URL and fails on the first request is harder to diagnose and may pass its readiness checks.
Secrets need more than config: they belong in a secret manager or an encrypted store, with access granted per service identity, audit logs, and rotation. Prefer short-lived credentials, such as cloud workload identity or dynamically issued database users, over long-lived keys. Note that Kubernetes Secrets are only base64 encoded by default; protect them with encryption at rest and RBAC.
Plan for rotation from day one. If a key leaks, you want to issue a new one, roll it out, and revoke the old one without downtime, which usually means the consumer can accept two valid credentials for a short overlap.
TypeScript
type Config = {
port: number;
databaseUrl: string;
paymentsApiKey: string;
};
function required(name: string): string {
const value = process.env[name];
if (!value) {
throw new Error(`Missing required environment variable ${name}`);
}
return value;
}
export function loadConfig(): Config {
const port = Number(process.env.PORT ?? "8080");
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new Error(`Invalid PORT: ${process.env.PORT}`);
}
return {
port,
databaseUrl: required("DATABASE_URL"),
paymentsApiKey: required("PAYMENTS_API_KEY"),
};
}
const config = loadConfig();
console.log(`Config loaded, starting on port ${config.port}`);Startup validation that refuses to boot with missing or malformed config, and logs nothing secret.
Traps
- Committing secrets to the repository. Deleting them in a later commit does not remove them from history; rotate them.
- Logging the whole config object or environment on startup, which writes secrets into the log platform.
- Treating base64 in a Kubernetes Secret as encryption.
- Sharing one credential across many services, so a leak cannot be scoped and rotation needs a coordinated change everywhere.
Incident response and blameless postmortems
During an incident the priority is mitigation, not root cause. Roll back the last deploy, turn off the flag, shift traffic away from the bad region, or scale up, then investigate once users are safe. Assign clear roles: an incident commander who coordinates and decides, someone hands-on, and someone communicating status to stakeholders on a regular cadence.
Write a timeline as you go, with timestamps, because memory is unreliable an hour later. Afterwards, a blameless postmortem asks how the system allowed the failure and why detection and recovery took as long as they did. Blaming a person teaches people to hide mistakes; fixing the system prevents the next one.
Good action items are specific, owned and dated: add a canary stage, make the migration linter reject unbatched updates, page on burn rate instead of CPU. Measure time to detect and time to mitigate, because those are the numbers your process actually improves.
Text
Incident: Parcelwise label printing failures, 2 hours 6 minutes of degraded service
14:02 Deploy of label-service v412 starts (rolling, 8 pods)
14:09 Rollout completes
14:31 Fast-burn SLO alert pages on-call (5xx ratio 4.2 percent)
14:35 Incident commander assigned, status page set to Investigating
14:41 Errors correlate with v412; decision: roll back first
14:44 kubectl rollout undo deployment/label-service
14:52 Error ratio back under 0.05 percent, status Monitoring
16:08 Resolved
Contributing factors
- v412 read a config key that only existed in staging
- No startup validation, so pods passed readiness
- No canary stage for label-service
Action items
- Add startup config validation (owner: Dana, due 3 June)
- Add 10 percent canary with automated analysis (owner: Kofi, due 17 June)An invented postmortem excerpt: timeline first, contributing factors in system terms, and owned, dated action items.
Traps
- Debugging live while users are failing, when a rollback would have restored service in minutes.
- Postmortems that conclude with human error. That is where the investigation should start, not end.
- Action items without owners or dates, which quietly never get done.
- No one assigned to communication, so support and customers learn about the outage from social media.
Common questions
Short answers to the usual doubts.
How deep should I go into Kubernetes for a DevOps interview?
Know the behaviour rather than every field: how a rolling update uses maxSurge and maxUnavailable, how readiness differs from liveness, what happens between SIGTERM and SIGKILL, and how a rollout undo works. Being able to explain those mechanisms in a concrete scenario is worth more than reciting resource types.
Should I roll back or roll forward when a deploy breaks production?
Default to rolling back or disabling the flag when users are affected and the previous version is known to be good. Roll forward only when rollback is unsafe, for example after a data format change the old code cannot read, and the fix is small and well understood. Say explicitly why you chose one.
What is the difference between monitoring and observability in an answer?
Monitoring checks known failure conditions with predefined metrics and alerts. Observability is the ability to answer new questions about the system from its telemetry, using metrics, structured logs and traces correlated by request id. In practice, mention both: SLO alerts to detect, and traces and logs to diagnose.
How do I talk about a past outage without sounding negative?
Describe it like a blameless postmortem: what happened, how it was detected, what you did to mitigate, which system weaknesses contributed and what changed afterwards. Focus on the reasoning and the lasting fix, not on who made the mistake.
Is blue-green always safer than rolling deployments?
No. It gives a fast traffic switch, but it doubles capacity and does nothing for a shared database: both versions must still handle the same schema and data. For stateless services with good health checks, a rolling update with a canary step is often the better trade-off.
Now, practise it
Put it to work straight away.
Tests, exercises and problems that use what you've just read.
- DevOps: deploying and operatingTake the test