Appendix B. Self-check answers and explanations
Chapter 1
1-1. Environment variables without NEXT_PUBLIC_ are isolated exclusively for the server, can only be read in server runtimes (such as Route Handlers and Server Actions), and are not transmitted to the browser. In contrast, for variables prefixed with NEXT_PUBLIC_, their actual string values are inlined in plaintext into client-side JavaScript bundle files at build time, so anyone in the world can view them in browser developer tools. Because they are baked into static files at build time, after modifying values in the dashboard, a redeployment (Redeploy, a new build) must be executed for the changes to be reflected in the browser.
1-2. Although there is only a single round trip between the client and the function per request, when processing a single request the serverless function performs multiple round trips (Multiple RTTs) with the database, conducting connection establishment (TCP + TLS + authentication handshakes) and multiple sequential queries (authentication verification, data retrieval, record saving, etc.). If the latency of a single round trip between the function (iad1, US East) and the DB (Seoul) is approximately 180 ms, just establishing a connection and executing a few queries incurs more than 1 second of cumulative network latency; therefore, the function region must be matched to Seoul (icn1), the same as the database.
1-3. Transaction mode (port 6543) borrows a backend Postgres connection only for the brief moment when an individual transaction (BEGIN–COMMIT) or a single query executes and returns it to the pool immediately; therefore, it should be used for runtime queries in serverless applications where short-lived instances proliferate rapidly, preventing connection exhaustion. In contrast, session mode (port 5432) or a direct connection holds a backend connection 1:1 until the client disconnects and maintains session-level features (Prepared Statements, SET, Advisory Locks, etc.); therefore, it is separated and used for database schema migration (migrate) tasks.
1-4. The USING clause is evaluated when filtering which existing rows already present in the table can be read (SELECT), targeted for modification (UPDATE), or deleted (DELETE). Conversely, the WITH CHECK clause is evaluated when verifying whether the state of a row newly inserted into or modified within the table satisfies the policy as a result of an INSERT or UPDATE. If an UPDATE policy has USING applied solely to personal ownership while the WITH CHECK condition is loose (e.g., true), a user could select their own row to modify and overwrite the owner id (owner_id), affiliated organization (org_id), or approval status with someone else's values or values outside their permissions.
1-5. The first is the x-vercel-protection-bypass: <SECRET> header, which carries the automation bypass secret issued to the project, and the second is the x-vercel-set-bypass-cookie: true (or samesitenone for cross-site testing) header, which bakes a bypass cookie into the browser so that subsequent page and resource requests following the initial visit also maintain the bypassed state.
1-6. (1) Bucket configuration: Because contracts are sensitive personal documents, they must be created as a private bucket (Private Bucket, public = false) to prevent unauthorized viewing if a URL is leaked. (2) Upload flow: To circumvent the request body size limit of Vercel serverless functions, the server API first verifies the user's login and permissions, issues a signed upload URL (createSignedUploadUrl) with a short expiration time, and has the browser upload the file directly to Supabase Storage via this URL. (3) Viewing flow: Upon a viewing request, the server (or RLS) verifies whether the user is the owner of the contract and issues a signed download URL (createSignedUrl) configured with a short validity period (e.g., 60 seconds), allowing temporary viewing exclusively in their own browser.
Chapter 2
2-1. If two people run terraform apply concurrently without state locking, a race condition occurs where both processes read the state file simultaneously and overwrite each other's results, leading to resources created by one side being lost from the state file, the JSON structure becoming corrupted, and duplicate creation or conflict errors occurring. In the AWS S3 backend, state locking (use_lockfile = true or dynamodb_table) must be enabled to prevent concurrent executions, and S3 bucket versioning (Bucket Versioning, along with server-side encryption encrypt = true) must be enabled to revert to a previous state if the state file is accidentally overwritten or corrupted.
2-2. ~ (Update in-place) means modifying configuration attributes in place via API while preserving and not deleting the existing cloud resource, whereas -/+ (Replace) means completely deleting the existing resource (-) and creating a new resource (+) due to changes such as immutable attributes. If -/+ is executed on a production database, the DB instance and its internal data are deleted; therefore, lifecycle { prevent_destroy = true } must be configured inside the resource block so that if deletion or replace is planned, it is immediately blocked with an error at the plan stage.
2-3. If only the resource identifier in the code is changed from aws_instance.app to aws_instance.api_server and apply is run, Terraform does not know that the name was changed, completely deleting (-) the existing aws_instance.app instance and creating (+) aws_instance.api_server anew, which causes service downtime and data initialization. To migrate only the address mapping in the state file without downtime, one must add a moved { from = aws_instance.app, to = aws_instance.api_server } block to the code.
2-4. This is because sensitive = true merely obscures the value as (sensitive value) on the terminal screen (standard output log) when running terraform plan and apply, while the secret value is still recorded in plaintext inside the terraform.tfstate JSON file that Terraform stores to compare changes. To prevent this, one must (1) fundamentally block Git commits of *.tfstate via .gitignore, (2) store state only in a remote backend (such as S3) with KMS encryption and least-privilege IAM permissions applied, and (3) use Ephemeral variables, write-only attributes (password_wo), or external Secrets Manager references so that no values remain in the state file.
2-5. Because a rule added manually in the console is in a drift state, if left as is and the next deployment (apply) is run, Terraform deletes it, claiming that the rule does not exist in code. Therefore, (1) first write and reflect identically in the security group definition of the .tf code the port rule that was manually added at dawn (use an import block if it is a newly created separate resource), and (2) run terraform plan to confirm that there are no further changes between the actual cloud state and the code (No changes. Your infrastructure matches the configuration.), and then commit and merge into Git.
2-6. When a PR is opened, it has not yet undergone code review and approval; therefore, if a role with production write (apply) permissions is given to the PR workflow, malicious or erroneous PR code could alter actual infrastructure or exfiltrate secrets before review. Therefore, only a read-only (plan) role should be granted to the PR workflow, and the apply role with actual change permissions must be separated so that it operates only after code review when merged into the main branch. In the OIDC trust policy Condition of the apply role, the target service aud (sts.amazonaws.com) along with the sub claim pointing to the exact repository and branch/environment (e.g., repo:organization/repository:ref:refs/heads/main or protected environment:production) must be verified.
Chapter 3
3-1. Under DNS standards (RFC 1034/2181), if a CNAME record exists for a given domain name, no other type of record can coexist for that name. However, the root domain (Zone Apex, example.com) must have SOA and NS records, which are mandatory records that establish a domain zone, so a standard CNAME cannot be placed there. In Route 53, this is resolved by configuring an Alias record at the root domain to internally look up the ALB's current IP addresses (A/AAAA) and return them as a standard response (Cloudflare uses CNAME Flattening).
3-2. This is because telecommunications carriers and public recursive DNS resolvers worldwide store the old server IP obtained from previous queries in their cache for the TTL configured at that time (86,400 seconds = 24 hours), and do not query the authoritative nameservers again until that time expires. Even if the TTL is changed to 60 seconds and the IP is updated on the nameserver on the day of the migration, resolvers that already hold the 24-hour cache will continue to send traffic to the old server IP for up to 24 hours. Therefore, well before at least the existing TTL (24 hours), only the TTL must be lowered to 60–300 seconds in advance, and the IP switch must be made only after waiting for all existing caches to expire.
3-3. In the user's browser, an ERR_TOO_MANY_REDIRECTS (infinite redirect loop) error occurs, preventing the site from opening. While the user connects to Cloudflare via https://, Flexible mode changes the request to plaintext http:// (port 80) when forwarding from Cloudflare to the origin server, and because the origin server received a plaintext HTTP request, it returns a 301/308 redirect instructing the user to connect via https:// again, repeating this process endlessly. Furthermore, because the segment between the edge and the origin is exposed in plaintext, a valid certificate (from a public CA or Cloudflare Origin CA) must be installed on the origin server, and Full (Strict) mode must be used.
3-4. The orange cloud (Proxied) only returns the Cloudflare edge IP for DNS queries. If the origin server's firewall (security group) is open to the entire world (0.0.0.0/0), an attacker who discovers the origin server's real IP address through historical DNS records or scanning can send an HTTP request directly to that IP with a Host: domain header, completely bypassing the Cloudflare edge and WAF. To prevent this, the origin server side must (1) restrict the inbound firewall strictly to Cloudflare public IP ranges, (2) accept only requests sent by our Cloudflare zone using Authenticated Origin Pulls (mTLS client certificate verification), or (3) close all inbound ports and connect exclusively via Cloudflare Tunnel (cloudflared).
3-5. If a personalized API (/api/profile) is cached on a shared CDN, the first user's personal information or Set-Cookie session header is stored at the edge and directly exposed to subsequent users, resulting in a cache poisoning (personal information leak) incident. Furthermore, if LLM streaming (/api/chat/stream, text/event-stream) is cached or response buffering is enabled, tokens will not stream in real time character by character, but will instead be held at the edge until the stream finishes and delivered all at once, or a timeout will occur. Therefore, both paths must be set to Bypass Cache in the CDN cache rules, with Cache-Control: private, no-store specified for the personalized API and Cache-Control: no-cache, no-transform (along with disabling buffering) specified for SSE streaming.
3-6. First, configure automatic retries and multi-provider fallbacks (Universal Endpoint / Fallbacks) so that if a 503 or timeout occurs on the primary model (OpenAI), the gateway automatically routes the request immediately to a backup provider (e.g., Anthropic Claude or Google Gemini) without code deployment, preventing service disruption. Second, set up gateway rate limiting so that if runaway agent loops cause excessive calls exceeding hourly or per-minute thresholds, the gateway blocks them before they reach the external LLM and incur charges. Third, enable unified observability (Analytics/Logging) and deterministic prompt caching to monitor latency, error rates, and costs per model at a glance, while immediately answering repeated identical queries from the cache to reduce costs and load.
Chapter 4
4-1. A traditional perimeter-based VPN incorporates authenticated devices into the internal corporate network (subnet), granting broad network-level trust that by default allows access to multiple servers and ports within the same network. In contrast, ZTNA based on NIST SP 800-207 grants no trust based on network location; it verifies identity and device posture on every session, granting least-privilege access only to individual applications and resources and specific ports authorized for that role. Therefore, when a single endpoint is infected with malware, a traditional VPN suffers from lateral movement, where the infection spreads across the internal network to adjacent servers and databases.
4-2. Standard web servers must wait for inbound connections coming from external clients, requiring inbound firewall ports to be opened. In contrast, with cloudflared (Cloudflare Tunnel), the daemon inside the internal private subnet first establishes an outbound encrypted connection toward Cloudflare edge servers, and once an external employee passes Cloudflare Access authentication, requests are received inward through that already-open outbound tunnel. Therefore, not a single inbound port on the internal firewall needs to be opened.
4-3. 192.168.1.0/24 (and 192.168.0.0/24) are RFC 1918 private IP ranges used by default by the majority of home Wi-Fi routers and cafe routers. If an internal corporate VPC also uses 192.168.1.0/24, the remote worker's local router network and the corporate VPN routing path collide directly (overlapping subnet collision), causing packets to be routed to the wrong destination or breaking communication with local printers and gateways. The solution is to design corporate cloud VPC ranges in ranges that do not overlap with home routers (e.g., 10.240.0.0/16 or granular subnets of 172.28.0.0/16), and to register only the genuinely required corporate CIDRs, CGNAT (100.64.0.0/10), or domains in split tunneling (Include mode).
4-4. Even though private IPs cannot be reached directly from the outside, registering internal server names (such as db.dev and payroll) and internal private IP ranges in external public DNS allows attackers to easily gather internal topology information—such as what critical systems exist within the company and how network ranges are configured—through DNS lookups. To prevent this, corporate domains are removed from external public DNS and registered only in internal private DNS, and split-horizon DNS (conditional forwarding) is configured so that ZTNA/VPN clients forward queries only for the relevant domain suffix (*.internal.corp) to the DNS resolver inside the tunnel.
4-5. NODE_TLS_REJECT_UNAUTHORIZED=0 does not merely allow internal CAs; it turns off TLS certificate verification entirely, leaving the system completely exposed to man-in-the-middle (MITM) attacks carried out by attackers using forged certificates on external networks. The correct method is to register the internal root CA certificate in the trust list while maintaining TLS verification. For Node.js (and Node-based coding agents), set NODE_EXTRA_CA_CERTS="/path/to/internal-root-ca.pem" to add the internal CA to the existing built-in CA list; for Python and OpenSSL tools that replace the default bundle, create a unified PEM file combining the existing public root CA bundle and the internal root CA, and specify it in SSL_CERT_FILE and REQUESTS_CA_BUNDLE.
4-6. (1) RDS connection component: Because a VPN/ZTNA agent cannot be installed directly on AWS RDS, deploy redundant (two or more) subnet routers (Subnet Router) or cloudflared private network connectors in the private subnet of the same VPC. (2) Port and destination restriction method: Apply a least-privilege ACL (default deny) with the contract developer group (group:contractors) as the source and only the staging RDS IP and port 5432 as the destination, blocking lateral movement to SSH (22) or other internal servers. (3) Automatic revocation upon departure: Integrate the internal IdP and ZTNA/VPN via the SCIM protocol so that when a contract ends, the account is immediately and automatically deactivated, and active tunnel sessions and tokens are forcefully terminated.
Chapter 5
5-1. The four steps of dual-key (Dual-Key) zero-downtime rotation are (1) generating a new key (V2) and first deploying server verification code so that it accepts both [V2, V1] keys, (2) switching new token signing and webhook dispatch settings to V2, (3) waiting for the existing token time-to-live (TTL) while checking in logs that V1 usage drops to zero, and (4) removing V1 from the verification list and discarding it. On the other hand, if an external API key is leaked to a public repository, an attacker could exploit that key during a grace period to exfiltrate data or incur massive charges; therefore, the exposed old key must be permanently revoked (Revoke) immediately upon deploying the new key without any grace period.
5-2. Recovery Point Objective (RPO) is the maximum acceptable duration of past data loss in the event of a failure, and Recovery Time Objective (RTO) is the maximum allowable recovery duration from the occurrence of a failure until normal service resumption. In an architecture where snapshots are taken only daily at 4:00 AM, the 10 hours of change history accumulated from 4:00 AM until the incident at 2:00 PM is not in the snapshot, so restoring results in the loss of all 10 hours worth of data. To resolve this, one must use Point-in-Time Recovery (PITR), which continuously archives all change logs (WAL, Write-Ahead Log) on top of a base backup so that the system can be rolled back to right before the execution of the accidental query at 2:00 PM (down to the second).
5-3. During a rolling deployment, old application instances that have not yet terminated and newly launched new application instances simultaneously send queries to the same database. If one executes RENAME COLUMN or DROP COLUMN directly at this point, old instances cannot find the existing column and immediately throw 500 errors, and if an issue occurs in the new version, rolling back to the old version code becomes impossible. The Expand-Contract pattern proceeds in the following sequence: (1) Expand: add a new column as nullable while leaving the existing column in place, (2) Dual-Write & Backfill: deploy the application to write to both the old and new columns and backfill historical data, (3) Cutover: deploy the application to read and write only to the new column, and (4) Contract: delete the old column after old instances have completely disappeared.
5-4. When a vast majority of fast static and cached responses (e.g., 10 ms) are mixed in, severe bottlenecks experienced by a small minority of users (e.g., a 20-second delay) are diluted in the average (Average), making it appear normal; therefore, one must look at p95 and p99 (tail latency), which show the actual experienced latency of the slowest 5% and 1% of requests. When collecting logs and traces, one must scrub (mask): (1) Authorization headers and session cookies (Cookie/Set-Cookie), (2) API secret keys and database connection string passwords, and (3) sensitive personal information such as user passwords, credit card numbers, and resident registration numbers.
5-5. If all server instances simultaneously bombard an overloaded downstream system with retries without waiting, retry traffic compounds on top of original traffic several times over, causing a retry storm (Retry Storm / Thundering Herd) and cascading failures where the downstream system collapses completely into an unrecoverable state. To prevent this, one must apply exponential backoff with jitter (Exponential Backoff with Jitter), which progressively increases retry intervals while mixing in random time variance, and place a circuit breaker (Circuit Breaker) that immediately blocks downstream calls and returns a fallback when consecutive failures exceed a threshold.
5-6. This is because wasting tens of minutes analyzing the cause, writing new code, testing, and deploying while an incident is in progress causes harm to all paying customers during that time (violating the "mitigate first, analyze later" principle). Within the first 10 minutes, instead of debugging, one must first bring the error rate down to 0% by instantly rolling back to the immediately preceding healthy release (Instant Rollback) or turning off the problematic new feature using a feature flag (Kill Switch). After the incident has ended, one writes a blameless postmortem (Blameless Postmortem) that avoids blaming specific individuals and records systemic causes—asking "Why was this error not filtered out during testing or canary stages?"—along with concrete action items to prevent recurrence.