Chapter 5. Infrastructure reliability, secret management and incident response
Learning objectives
- Establish procedures to rotate JWT signing secrets, webhook secrets, API keys, and TLS certificates without service interruption through a Dual-Key (Dual-Key / Overlapping Validity) acceptance structure, and to execute emergency replacement procedures in the event of key leakage.
- Compare periodic snapshot backups and Write-Ahead Log (WAL)-based Point-in-Time Recovery (PITR) from the perspectives of Recovery Point Objective (RPO) and Recovery Time Objective (RTO), and verify the validity of backups through regular recovery rehearsals.
- Design a three-stage zero-downtime Expand-Contract (parallel change, Parallel Change) migration so that applications and database schemas can coexist in a rolling deployment environment, and avoid destructive DDL locks.
- Trace bottlenecks from the edge all the way to databases and LLMs using OpenTelemetry-based logs, metrics, and distributed traces (
trace_id), and scrub (mask) sensitive information and secret values within the collection pipeline. - Combine cloud and AI infrastructure cost and usage anomaly alerts (soft limits) with automatic cut-off caps (hard limits) and circuit breakers to prevent cascading failures and sudden cost explosions.
- Under the principle that "mitigation and isolation of damage come before root-cause analysis" when an incident occurs, execute feature flag and traffic rollback runbooks, and write a blameless postmortem (Blameless Postmortem).
Introduction
There is an adage passed down among infrastructure engineers: "Every system will eventually fail, every secret key must be replaced someday, and a backup that has not been tested is not a backup."
The first testing ground is secret rotation (Secret Rotation). Under security policies, session signing secrets or webhook verification keys must be changed every quarter; however, when environment variables are overwritten with a new key and deployed, tens of thousands of currently logged-in users are simultaneously logged out, or half of all webhooks are lost due to verification failures (401) during the 3 minutes while deployment is in progress. An even more urgent situation arises when a developer accidentally exposes an API key in a public repository and the key must be revoked within 10 minutes.
The second testing ground is database incidents and schema changes. A bug in a batch script deployed at 2:17 PM executed an UPDATE statement without a WHERE clause, completely overwriting all customer grade data. If you roll back to the daily snapshot taken at 0:00 midnight yesterday, 14 hours' worth of payment and exam-taking records accumulated from this morning until 2:16 PM today will be lost. Furthermore, the moment someone executes ALTER TABLE RENAME COLUMN to change a column name during a zero-downtime deployment, server instances that are still running the old version of the code simultaneously crash while spewing column does not exist errors.
In this chapter, you will learn techniques for safely changing secret keys and database schemas without stopping service for even a single second, designing Point-in-Time Recovery (PITR) backups that can restore data to any desired point in time (down to the second) in any data loss incident, observability (Observability) and log masking that open up the black box of distributed environments, and incident response runbooks to stop the bleeding within 5 minutes without panicking when an alarm rings at 3:00 AM.
Key concepts
Zero-downtime secret and certificate rotation: Dual-Key Acceptance Pattern
Why do service interruptions or authentication failures occur when changing session cookie signing keys (SESSION_SECRET), internal inter-service authentication tokens, external payment webhook signing keys, or database account passwords?
This occurs because in a traditional single-key (Single-Key) structure, only one single key (SECRET_KEY) exists in the code.
- A user session cookie issued at 10:00 AM is signed with the old version key (
Key_V1) and stored in the browser. - At 10:10 AM, an administrator changes the server's environment variable to the new key (
Key_V2) and initiates a rolling deployment. - While the deployment is underway, some server instances are still using
Key_V1and some are usingKey_V2. - Even after the deployment finishes, the cookies signed with
Key_V1presented by users are all rejected as "forged signatures" by the new servers that only recognizeKey_V2, causing all users to be forcibly logged out! With external webhooks as well, because the exact moment the sender changes the key cannot be synchronized down to 0.001 seconds with the moment the receiver (our server) is redeployed, an interval of lost requests will inevitably occur.
The standard architecture that resolves this problem is precisely the Dual-Key Acceptance Pattern (or multi-key slot CURRENT + PREVIOUS pattern). The core idea is that "signing (issuance) is always performed with only the single latest key, whereas verification (acceptance) allows a grace period (Grace Period) during which a list containing both the latest key and the immediately preceding old version key is permitted."
// Example of a dual-key (keyring) verification structure supporting zero-downtime rotation
// Injected in the form of SESSION_SECRETS="v2_new_secret_key,v1_old_secret_key"
const keyRing = (process.env.SESSION_SECRETS ?? "")
.split(",")
.map((k) => k.trim())
.filter(Boolean);
export function signToken(payload: string): string {
// Newly issued tokens are always signed only with the first key (latest key, keyRing[0]).
return hmacSign(payload, keyRing[0]);
}
export function verifyToken(token: string): boolean {
// When verifying, try the latest key first, and if that fails, attempt verification with the immediately preceding key (keyRing[1]) as well.
return keyRing.some((secret) => hmacVerify(token, secret));
}
With this structure in place, any secret key can be replaced without a single failure through the following four-stage zero-downtime rotation procedure.
| Stage | Tasks performed | Signing (issuance) key | Verification (allowed) key list | Impact on users and webhooks |
|---|---|---|---|---|
| Stage 1 (Preparation and concurrent acceptance) | Generate the new key (V2) and deploy it added to the verification allowed list |
V1 (or V2) |
Allow both [V2, V1] |
0 interruptions (passes regardless of whether V1 or V2 arrives) |
| Stage 2 (Sender switchover) | Switch new token issuance and external webhook sender settings to V2 |
V2 |
Allow both [V2, V1] |
New requests are stamped with V2, and existing V1 sessions also pass normally during the grace period |
| Stage 3 (Grace period and observation) | Wait for the duration of the existing token expiration time (TTL) and verify from logs that the number of V1 matches decreases to 0 |
V2 |
[V2, V1] |
Confirmed convergence of V1 usage to 0 occurrences |
| Stage 4 (Old key revocation) | Remove V1 from the verification list and permanently revoke (Revoke) V1 at the cloud/vendor |
V2 |
[V2] alone |
Rotation complete (leakage risk eliminated) |
The principle is identical when rotating database passwords without downtime. If you use an alternating users (Alternating Users) strategy that alternates between two database users (app_user_blue, app_user_green) possessing the same permissions, when the application is currently running on the blue account, you can change the password of the green account to a new one, deploy the application connection string switched to green, and lock the blue account after all previous connections have drained, ensuring that not even a single second of connection errors occurs.
Criteria for deciding between scheduled rotation and emergency revocation in key exposure incidents
If so, should one rotate keys leisurely with a 24-hour grace period as described above even in an emergency situation (active compromise, Active Compromise) where a developer accidentally pushed a .env file to a public GitHub repository or where it has been confirmed that keys were seized by an attacker?
The decision depends on the situation.
- External API keys where we directly control both the issuer and the consumer (e.g., OpenAI API keys, AWS IAM keys, Supabase secret keys):
- First, immediately obtain a newly issued key (
V2) and deploy it to our production environment variables to migrate normal service traffic toV2within 1 to 2 minutes, and then immediately and permanently revoke (Revoke/Delete) the old key (V1) from the console without a grace period. If an attacker is actively extracting data using the leakedV1key or generating millions of KRW in API charges at this very moment, immediate revocation and blocking of the old key takes precedence over deploying the new key (because temporary errors are far preferable to a full data breach).
- First, immediately obtain a newly issued key (
- When user session signing keys (
SESSION_SECRET) are leaked:- Because the attacker is in a state where they can forge and generate arbitrary administrator session cookies on their own, if
V1is left in the verification list, the attacker's forged cookies will also continue to pass through. Therefore, in this case, unlike scheduled rotation,V1must be immediately removed from the verification list to forcibly expire all existing sessions and require users to log in again to ensure safety.
- Because the attacker is in a state where they can forge and generate arbitrary administrator session cookies on their own, if
Backup strategies and Point-in-Time Recovery (PITR): RPO/RTO design and recovery rehearsals
When evaluating infrastructure reliability, there are two time metrics that are defined first and foremost.
- RPO (Recovery Point Objective): "What is the maximum amount of past data loss that can be tolerated?" (quantity of time). For example, an RPO of 24 hours means it is acceptable to lose 24 hours' worth of data accumulated today since yesterday's backup, whereas an RPO of 1 minute means data must be restored to a state within 1 minute immediately prior to the incident.
- RTO (Recovery Time Objective): "From the moment an outage occurs, within how many minutes or hours at maximum must recovery be completed before the service is operating normally again?" (recovery duration).
Database backup methods are broadly divided into periodic snapshots (Periodic Snapshot / Dump) and Point-in-Time Recovery (PITR), and the RPOs guaranteed by the two are worlds apart.
| Classification | Daily periodic snapshot (Daily Snapshot) | Point-in-Time Recovery (PITR) |
|---|---|---|
| Operating principle | Captures and stores an entire disk snapshot or logical dump once a day (e.g., at 03:00 AM) | On top of a base physical backup (Base Backup), continuously archives Write-Ahead Logs (WAL) whenever changes occur |
| Achievable RPO | Data loss of up to 24 hours (if an accident occurs at 2:00 PM after a 3:00 AM backup, 11 hours' worth evaporates) | Within seconds to minutes (target time can be specified down to the second) |
Recovery from fatal mistakes (accidental execution of DROP/DELETE) |
All normal transactions that occurred throughout that entire day must also be sacrificed | By replaying WAL up to the exact point in time 14:17:04, immediately prior to 14:17:05 when the accidental query was executed, recovery is possible without data loss |
Therefore, for production databases handling payments, certificate issuance, and customer documents where data loss cannot be tolerated, PITR (continuous WAL archiving) must be enabled without exception.
However, merely enabling backups accomplishes only half the task. In actual practice, when an outage strikes and an attempt is made to restore from backup, countless issues frequently occur, such as (1) backup files being corrupted, (2) lacking permissions for encryption keys (KMS), (3) the restoration process alone taking 8 hours and far exceeding the RTO, or (4) the database being restored but failing to maintain consistency with files in storage buckets. For this reason, teams must mandate regular recovery rehearsals (Restore Drills) every quarter to actually restore PITR backups onto a new instance isolated from production, execute integrity queries, and measure the elapsed time (actual RTO).
Zero-downtime schema migration: Expand-Contract (parallel change) pattern
Cloud services continue running without stopping even during deployments (rolling deployments or canary deployments). That is, during the several minutes while the new version of application code (App v2) is spinning up, the existing version of application code (App v1) remains simultaneously active, reading and writing to the same database together. Furthermore, if a bug is discovered in App v2, you may need to roll back immediately to App v1 10 minutes later.
What happens if you forget this reality and execute the following migration all at once to change a database column name from full_name to display_name?
-- Absolutely forbidden! (Destructive single-stage migration that instantly causes service outages and renders rollback impossible)
ALTER TABLE users RENAME COLUMN full_name TO display_name;
The moment this SQL is executed, surviving App v1 instances will all fail with 500 Internal Server Error every time they issue SELECT full_name FROM users! Even if traffic has transitioned completely to App v2, if another bug emerges in App v2 and you hit the rollback button, App v1 will be incompatible with the already-altered schema, leaving you trapped in a dead-end corner where even rolling back is impossible.
The only standard best-practice technique to solve this is precisely the Expand-Contract (expand-contract, or parallel change Parallel Change) pattern. Rather than making destructive changes all at once, work is broken down and advanced through 3 to 4 stages of incremental deployments that preserve backward compatibility (Backward Compatibility).
| Stage | Database change | Application deployment | Rollback capability and safety |
|---|---|---|---|
| Stage 1: Expand | Leave existing full_name as is, and add new column display_name as nullable (NULL permitted) (ADD COLUMN display_name text) |
App v1 continues running as is (reads and writes only full_name) |
Because full_name remains intact, App v1 operates 100% normally |
| Stage 2: Dual-write and backfill (Dual-Write & Backfill) | Copy past rows' full_name values to display_name in batches (small chunk units) (Backfill) |
Deploy App v2: When writing data, record to both full_name and display_name (Dual-Write); when reading, read display_name (or full_name if absent) |
Even if you immediately roll back to App v1 at any time, the latest data continues accumulating in full_name, resulting in 0 data loss! |
| Stage 3: Cutover | Verify that all rows are populated, then validate constraints (NOT NULL VALIDATE) |
Deploy App v3: Completely remove references to full_name from code, reading and writing only display_name |
All instances no longer reference the old column |
| Stage 4: Contract | After confirming stabilization of all App v3 instances, finally drop the old column full_name (DROP COLUMN full_name) |
App v3 operating normally |
Zero-downtime schema change accomplished |
When executing DDL on large tables in PostgreSQL, one must also be cautious about table locks (Lock).
- Standard
CREATE INDEXcompletely blocks writes (INSERT/UPDATE/DELETE) on the table until index creation is fully completed; therefore, during production operations, you must useCREATE INDEX CONCURRENTLY, which does not block writes (note, however, thatCONCURRENTLYcannot be executed inside a transaction blockBEGIN ... COMMIT, so execute it with transaction wrapping disabled in your migration tool). - When adding new foreign keys or check constraints as well, instead of scanning and locking the entire table, execute
ADD CONSTRAINT ... NOT VALIDfirst (skips checking existing rows and completes immediately), and then separate the validation intoVALIDATE CONSTRAINT(validates in the background with a weaker lock that does not block writes); furthermore, setSET lock_timeout = '3s'on all migration sessions so that if waiting for a lock takes too long, rather than causing the entire service to stall (Lock Queue Pile-up), the migration safely fails first by design.
The three pillars of observability and OpenTelemetry distributed tracing
When an outage strikes, the difference between "it seems slow somewhere" and "a request with trace_id=4bf92f... originating from a Seoul region function went through Supavisor, where the DB query finished in 4ms, but was stalled for 28.4 seconds in the external LLM API span" is like night and day. Observability, the ability to infer the internal states of a system from the outside, is built upon three pillars.
| The three pillars of observability | Question answered | Representative metrics in infrastructure and AI operations |
|---|---|---|
| Metrics | "Are there symptoms right now? How bad are they?" (Numerical time-series aggregations) | Request rate (RPS), error rate (5xx/429 ratio), latency percentiles (p50, p95, p99), active DB connection count, hourly token consumption |
| Logs | "What event occurred at that exact moment?" (Structured individual event JSON) | Request path, status code, error stack, fallback trigger reason, audit events (must use searchable JSON structured logs) |
| Traces | "Where did a single request spend all its time?" (Connecting spans across segments) | Waterfall of [Edge → App Function → DB Query → AI Gateway → LLM Call] bound together by W3C traceparent / OpenTelemetry trace_id |
Here, looking only at average latency (Average Latency) is extremely dangerous. If 99 cache-hit requests finish in 10ms and 1 AI inference request takes 20,000ms (20 seconds), the average appears quite respectable at 210ms, but actual users are suffering severe delays. Therefore, infrastructure SLOs (Service Level Objectives) and alerts must be established based on tail latency (Tail Latency), namely p95 and p99.
Log scrubbing and sensitive information masking
When building an observability pipeline, the absolute security ironclad rule that must never be broken is log scrubbing (Log Scrubbing / Redaction, masking sensitive information). If you dump entire HTTP request headers (headers), request bodies (body), or environment variables directly into console.log or OpenTelemetry span attributes for convenience in debugging, the following values will be permanently stored in plaintext within external log collection services (Datadog, Sentry, CloudWatch, etc.):
Authorization: Bearer ...headers and session cookies (Cookie,Set-Cookie)- API keys (
sk-...), database connection strings (postgresql://user:password@...) - Users' passwords, resident registration numbers, credit card numbers, and original raw text of personal sensitive prompts
Therefore, at the application logger and OpenTelemetry Collector stages, a scrubber must be enforced to automatically replace keys and patterns matching password, secret, token, authorization, cookie, and api_key with [REDACTED]; furthermore, when user identification is necessary, an irreversible hashed identifier and trace_id must be logged instead of the raw email address.
Cost and usage anomaly alerts and circuit breakers
Cloud services and AI APIs operate on a pay-as-you-go (Pay-as-you-go) basis, charging according to actual consumption. With traditional physical servers, when traffic surged, the servers simply crashed and that was the end of it; however, with cloud functions and LLM APIs that have autoscaling enabled, if there is an infinite retry bug in the code or a denial-of-wallet (Denial of Wallet) attack strikes, it will result in a billing bomb of tens of millions of KRW overnight.
Therefore, cost and resource controls must be designed with a dual safety mechanism consisting of notifications (Soft Limits) and forced cut-offs (Hard Limits).
- Anomaly alerts (Anomaly Detection & Budget Alerts): In addition to thresholds at 50%, 80%, and 100% of the daily projected budget, an alert is sent immediately to the on-call channel when consumption surges to three or more times the normal hourly average consumption rate.
- Hard caps and rate limits (Hard Caps & Quotas): At 3:00 AM, there may be no one monitoring email alerts. Therefore, at the provider, AI Gateway, and application levels, daily token caps and concurrency limits per user and per organization must be enforced programmatically in code, so that if limits are exceeded, requests are automatically rejected (
429) or gracefully degraded to a low-cost, lightweight model (Graceful Degradation). - Exponential backoff with jitter and circuit breakers: When downstream databases or external LLM APIs are failing under heavy load, if all server instances bombard them with simultaneous retries every 0.1 seconds (Thundering Herd / Retry Storm), a system that was momentarily faltering will completely collapse. Retries must increase wait times from 1s → 2s → 4s and mix in random jitter (Jitter) to distribute the load; furthermore, when the consecutive failure rate exceeds a threshold, the circuit breaker must be opened (Open) to immediately cut off downstream calls for a set duration and return fallback responses (Fallback), giving the downstream system breathing room and time to recover.
Incident isolation and rollback runbooks and blameless postmortems
When an actual production incident occurs, the most fatal mistake is neglecting the outage state for an hour while insisting on "dissecting the code line by line to uncover why this bug happened before fixing and redeploying it"!
The first principle of incident response is always "mitigate first, investigate later (Mitigate First, Investigate Later) — stop the bleeding first."
A standard incident response runbook proceeds according to the following five-stage sequence.
- Detection and triage (Detect & Triage): When an SLO breach alarm triggers (e.g., 5xx error rate exceeding 5% for 5 minutes), immediately assign an Incident Commander and determine the blast radius (complete outage P1 vs. partial feature degradation P2).
- Immediate isolation and mitigation (Isolate & Mitigate — target within 5 minutes):
- If there is even the slightest possibility that recently deployed code is the cause, do not try to fix the code and build anew; instead, immediately roll back to the immediately preceding healthy deployment (such as Vercel Instant Rollback).
- If a specific new feature or external integration is the cause, turn off the feature flag (Feature Flag / Kill Switch) to isolate only the problematic capability while keeping core services alive.
- In the case of an external LLM provider outage, force activation of AI Gateway fallbacks, and in the case of attack traffic, raise WAF blocking rules or rate limits.
- Communication (Communicate): Transparently share current symptoms and mitigation status with internal stakeholders and on customer status pages (Status Page).
- Root cause analysis, verification, and recovery (Resolve & Verify): After the bleeding has stopped, analyze logs, traces (
trace_id), and metrics to fix the root cause, verify that regression tests pass, and restore normal operational mode. - Blameless postmortem (Blameless Postmortem): If, after an incident ends, people interrogate "who made the mistake (blaming individuals)," engineers will begin concealing failures and mistakes in the future. Instead, ask, "What systemic and architectural vulnerabilities permitted that mistake to propagate all the way into a production incident?" Then document a chronological timeline, 5 Whys root causes, and remedial action items to prevent recurrence assigned to specific owners with explicit deadlines (e.g., adding a destructive migration linter to CI, introducing circuit breakers), thereby making the system one step more robust.
Changes in secret management tools in 2026: Vercel Secret, AWS managed rotation, and Vault 2.0
The principles of dual-key rotation remain unchanged. What changed in 2026 are the rules of the tools used to store and replace secrets.
- Vercel (2026-08-28): Environment variable types were reorganized into two categories: Config and Secret. Passwords, API keys, and tokens are placed in Secret. Once stored, Secret values are write-only and cannot be viewed again. Existing Sensitive variables continue to operate as Secret, and Secrets can now also be placed in Development environments, where they were previously blocked.
- AWS Secrets Manager: There are three rotation methods. Managed rotation and managed external secrets run without Lambda, while the remaining one is Lambda function rotation written directly by the user. Managed external secrets rotate partner secrets such as Salesforce without requiring customers to author separate rotation logic. If a secret can be handled in a managed fashion, there is no reason to maintain rotation code manually.
- HashiCorp Vault 2.0.0 (2026-04-16): Vault transitioned from the 1.x family (latest 1.21) to 2.x, which follows IBM's versioning scheme. The latest confirmed version is 2.2.1, released on 2026-10-22. Endpoints
sys/rekeyandsys/generate-root, which previously could be called with only key shares, are now standard endpoints requiring authentication. The only exception is whenenable_unauthenticated_accessis configured. Instead of storing static credentials, Secret Sync connects to AWS, GCP, and Azure via WIF, and authenticated workloads obtain SPIFFE JWT-SVIDs from Vault.
For example, World Store stored its payment gateway keys in Vault. In the 1.x era, the emergency runbook was a procedure where three custodians gathered with only key shares to call sys/generate-root. After upgrading to 2.x, executing this procedure as-is became blocked at the authentication step. The team included emergency procedure rehearsals in the upgrade checklist and determined in advance the authentication paths to be used at that time. When long-term AWS access keys stored for Secret Sync were converted to WIF, the rotation target itself vanished entirely.
GPU memory on self-hosted inference servers: weight dtype and KV cache
When serving a model directly, GPU memory is broadly divided into two portions: model weights, and the KV cache that accumulates while generating tokens.
The size of the weights is determined by the dtype. Measuring bert-base-cased with the estimate-memory tool of Hugging Face Accelerate yields the following:
| dtype | Weight memory |
|---|---|
| float32 | 418.18 MB |
| float16 | 206.59 MB |
| int8 | 103.29 MB |
| int4 | 51.65 MB |
Every time the bit-width is halved, the weight memory is also reduced by almost half. When generating long contexts, however, the situation is different. As the KV cache occupies a substantial portion of memory, it easily becomes a bottleneck even before the weights do.
vLLM pre-allocates GPU memory for the KV cache according to the gpu_memory_utilization ratio. Increasing this value widens the space available for the KV cache. If there is insufficient space to accommodate the entire batch, some requests are preempted and evicted, only to be recomputed when space becomes available again. Although no error is thrown, the response for that request is delayed by that amount. Decreasing max_num_seqs, which sets the concurrency limit, reduces the number of requests entering a batch, thereby decreasing the required KV cache.
Consider an in-house contract summarization server. The p99 latency spiked only in the afternoons when long PDFs flooded in, and the number of preempted requests during the same time window also increased. Before adding GPUs, the team examined two tuning knobs. Because there were no other processes sharing the same GPU, they raised gpu_memory_utilization to expand the KV cache. When preemptions still persisted, they lowered max_num_seqs. Because reducing concurrency lowers throughput, they recorded p99 and throughput side by side before and after the change.
Deserialization risks in model serving and vLLM patch decisions
A model server is a program that accepts and executes weight files and model code created by others. Risks enter through two distinct avenues.
First is pickle. pickle.loads() can execute arbitrary code while deserializing data. Because safetensors is a format created to eliminate the pickle format that PyTorch previously used by default, one should prioritize choosing safetensors files for weights. Second is remote code. When loading custom model code with trust_remote_code=True, pin the revision to a specific commit hash. Even if code in the repository changes later, only the version that was reviewed will be executed.
Cases demonstrating that one must not rely on a single configuration setting have emerged successively in vLLM.
| Advisory | Details | Affected scope → Fixed version |
|---|---|---|
| CVE-2026-27893 (2026-03-26) | Two model implementation files hardcoded trust_remote_code=True, causing settings disabled by users to be ignored |
0.10.1 or higher and below 0.18.0 → 0.18.0 |
| GHSA-6757-hggm-hp2w, CVE-2026-115912 (2026-10-20) | Forged multimodal shared-memory handles reached worker pickle.loads() even when unsafe deserialization was disabled |
0.25.1 or lower → 0.32.0 |
Because the second advisory cannot be mitigated merely by disabling unsafe deserialization in the configuration, upgrading to the fixed version is the standard procedure. Starting from vLLM 0.32.0, support for Python 3.10 was dropped, making the minimum supported version 3.11. This is why a runtime upgrade must be incorporated into the patching plan.
Consider a team using NVIDIA NIM for LLMs 2.0.2 as an example. Because this release upgraded its inference backend to vLLM 0.18.0, CVE-2026-27893 was fixed in terms of versioning. However, looking at the version number alone, 0.18.0 fell within the affected scope of GHSA-6757-hggm-hp2w, which applied to 0.25.1 or lower. The team recorded the bundled engine version rather than the commercial product name on their inspection checklist, and cross-referenced advisories against that specific version number.
Going deeper
Zero-Lock DDL Checklist in Large-Scale PostgreSQL Operations
Even when practically executing the Expand-Contract pattern learned in Chapter 5, if you do not understand PostgreSQL's internal locking mechanisms, you may experience an incident where "you thought you were simply adding a column or applying a constraint, but the site freezes for 3 minutes."
Why is this? In PostgreSQL, depending on the command type, ALTER TABLE requires an ACCESS EXCLUSIVE lock (the highest-level lock that blocks all queries on that table, including SELECT reads).
Even though ALTER TABLE ADD COLUMN new_col text; itself finishes in 1 millisecond because it only changes metadata, what happens if a slow 50-second analytical query was already running on that table at that exact moment?
- The slow query holds a weak read lock (
ACCESS SHARE) on the table. - The
ALTER TABLEwe executed queues up in the lock queue until the slow query finishes to acquire theACCESS EXCLUSIVElock. - This is where the real disaster occurs! Thousands of incoming regular user
SELECTandINSERTqueries could have originally run concurrently with the slow query, but they are all blocked, lining up behind theALTER TABLEthat is waiting at the front of the line forACCESS EXCLUSIVE! As a result, simply because a single 1-millisecondALTER TABLElined up behind a slow query, all reads and writes across the entire service halt for 50 seconds.
Therefore, production PostgreSQL migration scripts must embed the following safety rules into code:
-- 1) Limit the lock wait time to be short so that if the lock is not acquired within 3s,
-- the migration itself fails immediately and retries without blocking service queries.
SET lock_timeout = '3s';
SET statement_timeout = '30s';
-- 2) Apply new foreign keys or check constraints immediately (metadata only) with NOT VALID first,
ALTER TABLE orders
ADD CONSTRAINT orders_amount_positive CHECK (amount >= 0) NOT VALID;
-- 3) Later, validate them in a separate step using VALIDATE CONSTRAINT without blocking reads and writes.
ALTER TABLE orders
VALIDATE CONSTRAINT orders_amount_positive;
Layered Health Checks and Graceful Degradation in Multi-Region and Multi-Vendor AI Services
In AI services with numerous external dependencies, designing so that "a failure in a single secondary feature does not spread into an entire service outage (Bulkhead pattern)" is the core of reliability engineering.
For example, suppose a critical path where users take a certification exam and a secondary path where an AI generates a review study guide after the exam finishes reside on a single server. If an external LLM API experiences a total outage, what happens if the server's overall health check (/api/health) is written to bundle the LLM API's availability and return 503? The load balancer determines that "our server is dead!" and takes down the entire site, encompassing exam taking, login, and score report lookup.
Therefore, dependencies must be separated into the critical path (Critical Path / Hard Dependency) and the non-critical path (Non-critical Path / Soft Dependency).
- The liveness health check (Liveness / Readiness Check) referenced by load balancers and DNS checks only the essential conditions under which that server can receive normal traffic, such as the application process and the primary database.
- When a failure is detected in a non-critical external dependency such as an external LLM API, recommendation engine, or email dispatcher, instead of killing the server, it switches to a graceful degradation mode. That is, it serves core exam taking and grading 100% normally, and replaces only the AI explanation area with a notice stating, "AI explanation generation is currently delayed and will be sent via notification shortly (enqueued in Queues)," thereby preserving the user experience.
At work
All Light Pay: Signing Key Rotation Completed Without a Single User Logged Out and Emergency Revocation of a Leaked API Key
All Light Pay, which operated an AI-based corporate expense settlement service, faced two challenges simultaneously while preparing for a security audit. One was a routine rotation task to replace the user session JWT signing secret (AUTH_SECRET) and credit card company webhook verification key—neither of which had been changed for a year—with zero downtime. The other was an urgent security incident that afternoon, in which an external AI API key for production receipt OCR was exposed in plaintext when a contract developer posted a test script to a personal public GitHub Gist.
The platform security lead recognized that the natures of the two incidents were completely different and directed two separate procedures simultaneously.
- Exposed External AI API Key → Emergency Revocation Procedure (Time taken: 4 minutes):
- Because every single second mattered for a key already exposed on the public internet, no grace period was granted. A new API key (
Key_New) was immediately issued from the vendor console, injected into Vercel Production environment variables, and redeployed (taking 2 minutes) so that normal OCR requests went out with the new key. Immediately following this, the exposed old key (Key_Old) was permanently deleted immediately (Revoked) in the vendor console. Subsequently, a complete audit of AI Gateway logs across the 18 minutes from exposure to revocation confirmed that there were no anomalous requests called from external IP addresses.
- Because every single second mattered for a key already exposed on the public internet, no grace period was granted. A new API key (
- Session Signing Secret and Webhook Key → Dual-Key Zero-Downtime Rotation Procedure:
- Because disconnecting the sessions of 3,000 currently logged-in accounting staff members or dropping even a single real-time corporate card approval webhook was unacceptable, a four-stage dual-key procedure was followed.
- First, the verification code was deployed to permit both keys in the
[new key, existing key]array in order (Stage 1). Then, token signing and card company webhook transmission settings were switched to thenew key(Stage 2). After monitoring the metric of requests verified with the existing key over the 24-hour session expiration cycle and confirming that it converged to 0 (Stage 3), the existing key was finally removed completely from environment variables (Stage 4). Key rotation was completed without a single forced logout or a single lost webhook.
Sunlit Clinic: PITR and Expand-Contract That Rolled Back Overwritten Reservation Data to 3 Minutes Prior After a Faulty Deployment
At Sunlit Clinic, which facilitated telehealth appointments, a deployment was underway on Tuesday at 3:12 PM to replace the doctor_name column in the appointments table with practitioner_id and clean up status values. However, the developer made two fatal mistakes. First, while old-version application instances were still running, they immediately executed ALTER TABLE appointments DROP COLUMN doctor_name, causing all old-version servers to spew 500 errors simultaneously. Second, because the WHERE status = 'expired' condition was omitted from the data-cleanup migration SQL, the query executed at 3:12:10 PM overwrote the statuses of all 14,000 future appointments to 'cancelled'!
As the alarm sounded, the Incident Commander (IC) moved immediately according to the runbook.
| Time | Stage | Action Taken and Rationale |
|---|---|---|
| 15:13 | Containment and Stopping the Bleeding | Switched the appointment modification feature flag (Kill Switch) immediately to 'Maintenance Notice (Read-Only)' to prevent additional data corruption, and immediately rolled back the application deployment to the previous healthy version |
| 15:15 | Point-in-Time Recovery (PITR) | Restoring from the morning daily snapshot (04:00) would vaporize 11 hours' worth of appointments from this morning through afternoon. Executed precision recovery to the point in time 15:12:05, exactly 5 seconds before the incident query ran, using Supabase PITR (WAL archiving) |
| 15:24 | Consistency Verification and Resumption | Verified that all 14,000 appointment statuses and new morning appointments were intact without a single loss in the restored data, and resumed normal service (achieved an actual RTO of 12 minutes and RPO of several seconds) |
| Next day | Expand-Contract Redesign and Retrospective | Held a blameless post-mortem to (1) add a rule in CI blocking builds if DROP COLUMN/RENAME COLUMN is executed before application code removal, and (2) completed zero-downtime redeployment by separating schema changes into 4 stages: Expand (add column) → Dual-Write & Backfill → Cutover → Contract (delete old column) |
Common mistakes
- "When rotating secret keys, simply overwriting the existing environment variable value with the new key in the dashboard and redeploying achieves zero downtime." Directly overwriting a single key causes discrepancies between instances during deployment, and all active sessions signed with the existing key or external webhooks sent right before the switchover will fail. You must go through a Dual-Key grace period phase that simultaneously permits verification of both
[new key, existing key]. - "Since full database snapshot backups are taken every day at dawn, even if data is accidentally deleted in the afternoon, it can be recovered without any loss." If you only have daily snapshots, half a day's worth of data accumulated from the dawn backup time to the afternoon incident time cannot be recovered (RPO up to 24 hours). For point-in-time recovery down to the second or minute, WAL-based Point-in-Time Recovery (PITR) must be enabled.
- "Since the platform supports zero-downtime rolling deployments, database column names can also be changed in one go using
ALTER TABLE RENAME COLUMN." During a rolling deployment, the old-version code and the new-version code point to the same database simultaneously. If a column name is renamed or dropped directly, old-version instances will throw immediate errors and rollbacks will become impossible, so you must follow the Expand-Contract (parallel change) phases. - "To debug quickly, it is best to leave the raw
headersandbodyof all requests intact on the central log server." Request headers and bodies containAuthorizationtokens, session cookies, passwords, API keys, and personal information, turning log storage into a secondary leakage path. Sensitive fields must be automatically masked (scrubbed) prior to collection, and requests should be tracked usingtrace_id. - "Since the service's average response time (Average Latency) is 200ms, all users are enjoying a comfortable experience." When fast static/cached responses make up the vast majority, the average value conceals a small number of extreme delays (AI/DB bottlenecks taking over 20 seconds). Reliability metrics must always be viewed via p95 and p99 percentiles (tail latency).
- "When a production incident occurs, do not hastily roll back; instead, first analyze the logs to completely identify why the bug occurred, and then deploy a fix patch." While spending an hour on root cause analysis, customer damage snowballs. The cardinal rule of incident response is mitigate and isolate first (immediate rollback, kill switch, fallback), then analyze root cause.
Summary at a glance
| Core topic | Key takeaway for exams and practical work |
|---|---|
| Dual-Key rotation | Rotate without downtime by providing a grace period where signing and issuance use the latest key (V2), but verification permits both [V2, V1] |
| Emergency key revocation | In an emergency incident where a key is exposed externally, immediately and permanently revoke the exposed old key without a grace period after deploying the new key, and investigate audit logs |
| RPO, RTO, and PITR | RPO is the acceptable data loss window, and RTO is the target recovery time. WAL-based PITR and regular recovery rehearsals are essential for second-level restoration and reverting accidental queries |
| Expand-Contract migration | Maintain backward compatibility and rollback capability in the order of 1) Expand (add nullable) → 2) Dual-write and backfill → 3) Switch reads → 4) Contract (delete old column) |
| Lock-free DDL | Use CREATE INDEX CONCURRENTLY for large indexes, add constraints as NOT VALID followed by VALIDATE, and set a short lock_timeout on sessions |
| Observability and log scrubbing | Connect metrics (p95/p99), structured logs, and distributed traces (trace_id), and redact tokens, keys, cookies, passwords, and personal information before collection |
| Cost limits and circuit breakers | Establish both alerts (soft limit) and code-blocking caps (hard limit), and prevent retry storms and budget exhaustion using exponential backoff with jitter and circuit breakers |
| Incident response and postmortem | Follow the sequence of mitigate first (immediate rollback, kill switch) → root cause analysis and verification → blameless postmortem (deriving systemic action items to prevent recurrence) |
Check the official docs
- Supabase — Database Backups & Point-in-Time Recovery (PITR): RPO differences and restoration principles between daily physical backups and WAL-based PITR.
- PostgreSQL Documentation — Routine Database Maintenance & Concurrently:
CREATE INDEX CONCURRENTLYand table lock levels. - OpenTelemetry Documentation — Context Propagation & Collector Scrubbing: Metric, log, and trace signal standards and sensitive data transformation processors.
- OWASP — Secrets Management Cheat Sheet: Secret lifecycle and zero-downtime automated rotation design.
- NIST — SP 800-61 Rev. 3 Incident Response Recommendations: Incident detection, containment and mitigation, recovery, and post-incident lessons-learned frameworks.
- Vercel — Sensitive environment variables: Distinction between Config and Secret types, write-only behavior of Secret values, and whether they are allowed in Development environments.
- AWS — Rotate AWS Secrets Manager secrets: Differences between managed rotation, managed external secrets, and Lambda function rotation.
- vLLM — Optimization and Tuning:
gpu_memory_utilization, recomputation of preempted requests, and the impact ofmax_num_seqson KV cache requirements. - vLLM — Security Advisory GHSA-6757-hggm-hp2w: Affected versions and fixed versions of the multimodal shared memory handle forgery vulnerability.
Self-check
5-1. Explain in order the four phases of the "Dual-Key Acceptance Pattern" for replacing webhook signature verification secrets or session signing keys without service interruption or request loss, and conversely compare why an external API key must be immediately revoked without a grace period when it is leaked to a public GitHub repository.
5-2. Define the meanings of Recovery Point Objective (RPO) and Recovery Time Objective (RTO) respectively, explain why a snapshot alone cannot restore data without loss when a DELETE query was accidentally executed at 2:00 PM in a database that only takes snapshots at 4:00 AM every day, and write the backup method that resolves this.
5-3. Explain why executing ALTER TABLE RENAME COLUMN directly causes an outage and even prevents rollbacks when modifying a column of an active table in a zero-downtime rolling deployment environment, and write in order the phases of Expand-Contract (parallel change) that resolve this.
5-4. Explain why p95 and p99 percentile metrics must be examined instead of average latency in observability, and write three or more sensitive items that must be scrubbed (removed or redacted) when collecting distributed traces (trace_id) and structured logs.
5-5. Explain what phenomenon (Retry Storm) occurs when all servers repeatedly retry immediately at short intervals when an underlying database or external LLM API falls into temporary overload, and write two approaches—a retry method and a blocking pattern—to mitigate this.
5-6. Design task: A P1 incident alarm sounded at 2:00 AM as the 500 error rate of the payment API spiked to 15% immediately following a new deployment. When the on-call engineer said, "I will debug the code and write a new fix patch," explain why the incident commander had to stop them, and describe the standard mitigation actions that should be taken within the first 10 minutes and the principles of the postmortem to be written after resolving the incident.
Hands-on tasks
Exercise
Writing an Expand-Contract Zero-Downtime Schema Migration and Rollback Plan (50 minutes)
- In a
userstable currently holding millions of records, the single string columnphoneis to be split without downtime into two columns:phone_countrywith the country code separated, andphone_number. - Write a deployment sequence table divided into Phase 1 (Expand), Phase 2 (Dual-Write & chunked backfill), Phase 3 (switch reads and
NOT VALID→VALIDATEconstraints), and Phase 4 (Contract), along with the SQL for each phase (includingSET lock_timeout = '3s'). - Prove in two sentences why no data loss occurs if an application bug is discovered immediately after the Phase 2 deployment and the system is immediately rolled back to the previous code version.
Done when: The old-version app and new-version app can operate simultaneously at any point among the four phases, there is no DDL holding long locks on the entire table, and the rationale for lossless rollback in Phase 2 is clear.
Exercise
Writing Dual-Key Rotation Code and a P1 Incident Response Runbook (45 minutes)
- Write functions that read the environment variable
WEBHOOK_SECRETS="v2_secret,v1_secret"to generate an HMAC-SHA256 signature (always using the first key) and verify it (allowing iteration through the keys in the list and recording which key slot matched in a structured log, while never recording the actual key value in logs). - Create a one-page runbook in tabular form covering mitigation actions within 5 minutes, dashboard metrics to inspect (
trace_id, p99, cost limits), and recurrence prevention measures for the following two incident scenarios:- Scenario A: When the number of concurrent serverless function executions surges due to consecutive timeouts from an external LLM API
- Scenario B: When the API error rate spikes due to an erroneous database migration deployment
Done when: There is zero plaintext secret logging in the key verification code, old-key usage can be tracked, and both runbooks follow the "Mitigate First (Fallback, Rollback, Circuit Breaker), Then Analyze Root Cause" sequence.