Chapter 3. Global DNS and edge networking (Advanced: Route 53 & Cloudflare)

Learning objectives

  • Distinguish the DNS hierarchical structure and Route 53's core records (A, AAAA, CNAME, Alias, TXT, CAA), explain the reason why a CNAME cannot be used for the root domain (Zone Apex), and explain the solution provided by Alias records.
  • Combine Route 53 routing policies (Simple, Weighted, Latency, Failover) with health checks to design canary deployments and automated failover.
  • Explain the principle of reducing the TTL in advance, at least the existing TTL duration prior to the cutover time, to achieve zero-downtime domain and server migrations.
  • Understand the difference between Cloudflare's DNS-only (gray cloud) and Proxied (orange cloud) modes, and explain why Flexible among the SSL/TLS modes causes redirect loops or plaintext exposure, as well as the Full (Strict) + Origin CA configuration.
  • Configure exceptions and signature verification when designing WAF, Rate Limiting, and Bot control rules so that legitimate payment and authentication webhooks are not blocked.
  • Prevent cache poisoning and buffering incidents in CDN cache rules for personalized API responses (/api/*, Authorization, Set-Cookie) and LLM streaming (text/event-stream).
  • Combine Cloudflare Workers, Queues, and AI Gateway (observability, caching, rate limiting, multi-provider fallback) to design a resilient AI edge architecture.

Introduction

Even when the code is flawless and the database is rock solid, incidents occur where users encounter ERR_TOO_MANY_REDIRECTS (exceeded redirect limit) on their screens, or where after migrating servers to a new cloud, half of the users continue connecting to the old, already decommissioned server for six hours, or even more horrifyingly, where after logging in, another person's account profile and chat history appear directly on the user's screen. No matter how thoroughly one searches through the application code, there is no bug to be found. This is because the culprit lies outside the application code, namely in the configuration of the DNS and the edge network (CDN and reverse proxy).

From the moment a user types https://aidan.agentcat.app into the browser address bar until our application server returns the very first byte, the request must first look up the IP address in an authoritative DNS (Amazon Route 53, Cloudflare DNS), and undergo a TLS handshake, WAF inspection, cache lookup, and Worker execution at the global edge proxy (Cloudflare) before it finally reaches the origin server (Origin). In an AI service, one more component is added to this path. The traffic going out from our server back to external LLM providers (OpenAI, Anthropic, Google) flows through an AI Gateway.

In this chapter, we sequentially cover the core design principles that advanced engineers must thoroughly master, ranging from Route 53, the telephone directory of the Internet, to Cloudflare's proxy, security, caching, serverless computing, and AI Gateway, which serve as both shields and accelerators right on the doorsteps of more than 300 cities worldwide.

Key concepts

DNS resolution path and core records: Why CNAME cannot be used for the root domain

The Domain Name System (DNS) is a hierarchical, distributed database that translates human-readable domain names (aidan.agentcat.app) into IP addresses (192.0.2.1 or 2001:db8::1) that computers can communicate with. When a user's device (stub resolver) queries a telecommunications provider or a public recursive resolver (for example, 1.1.1.1 or 8.8.8.8), the recursive resolver traverses through the root (.) nameservers → top-level domain (.app) nameservers → authoritative nameservers (Authoritative Nameserver, for example, Route 53 or Cloudflare) in order to retrieve the final record, and caches that result for the duration of the TTL (Time To Live, valid duration in seconds) to reuse it.

The most frequently handled DNS record types and their primary purposes are as follows:

Record type Contained value Primary purpose Design considerations
A IPv4 address (203.0.113.10) Directly connects a domain to a fixed IPv4 server Must be updated manually if the target server IP changes
AAAA IPv6 address (2001:db8::10) Connects a domain to an IPv6 endpoint Recommended to configure alongside A for modern mobile and cloud networks
CNAME Another domain name (cname.vercel-dns.com) Aliases a subdomain (www.example.com) to another domain Cannot be used on the root domain (Zone Apex, example.com) according to the standard!
Alias (Route 53) / CNAME Flattening (Cloudflare) AWS resource (ALB, CloudFront, S3) or target domain Connects a root domain to a dynamic IP endpoint Can also be used on root domains because the nameserver resolves and responds with the final A/AAAA IP upon query
TXT Arbitrary text string Domain ownership verification, email sender authentication (SPF, DKIM, DMARC) Pay attention to quotation marks, length limitations, and overwriting existing records
CAA Certificate issuance authorized authorities (letsencrypt.org, etc.) Prevents unauthorized Certificate Authorities (CAs) from erroneously issuing TLS certificates for one's domain Because subdomains inherit the CAA of parent domains, all CAs in use (Vercel, Cloudflare, etc.) must be registered to prevent renewal failures

Here, the most critical rule that appears frequently on exams is the rule prohibiting CNAME on the root domain (Zone Apex, for example, example.com) (RFC 1034 / RFC 2181).

According to the DNS standard, if a CNAME record exists for a given name, no other record can coexist on that name. However, on the root domain (example.com), the SOA (Start of Authority) and NS (Name Server) records, which are mandatory records that define the entire domain zone, must unconditionally exist. Therefore, in standard DNS, one can freely use a CNAME on www.example.com (a subdomain), but the moment a CNAME is inserted into example.com (the root domain), the zone rules are broken.

Cloud load balancers (ALB) or CDNs (CloudFront, Vercel) provide only domain addresses instead of fixed IPs; if a CNAME cannot be used on the root domain, how do we connect them?

  • Amazon Route 53 Alias record: A proprietary extension feature unique to Route 53. The administrator configures an Alias to point to a target ALB, CloudFront distribution, S3 bucket, or a record within the same hosted zone; however, when an external DNS resolver queries for the A record of example.com, Route 53 internally looks up the current IP address of the target and returns it as a standard A/AAAA response. As a result, it can be used on the root domain without violating DNS standards in any way, and Alias queries pointing to AWS resources do not incur Route 53 query charges.
  • Cloudflare CNAME Flattening: When a CNAME is entered on the root domain, Cloudflare nameservers trace the target domain to its terminus in the background, flatten it into the final IP (A/AAAA), and return that in the response.

Route 53 routing policies and zero-downtime traffic control via health checks

Route 53 does not simply map a domain to a single IP; it provides routing policies (Routing Policy) that distribute responses across different endpoints based on traffic ratios, network latency, or server survival status.

Routing policy How it works Representative practical use case
Simple Responds randomly with one or more IPs contained in a single record Single-environment service, when separate traffic control is unnecessary (cannot directly attach health checks)
Weighted Assigns a weight (e.g., 90 to 10) to each record to distribute traffic proportionally Canary deployments, blue-green gradual infrastructure migrations
Latency-based Responds with the AWS region that provides the lowest network round-trip latency from the user's location Global services with active servers located in both Seoul (ap-northeast-2) and Northern Virginia (us-east-1)
Failover Routes traffic only to Primary under normal conditions, and automatically switches to Secondary upon health check failure Active-passive disaster recovery (DR), automated cutover to maintenance notice pages
Geolocation Routes traffic deterministically to designated endpoints based on the requester's country or continent Separation of data sovereignty and regulations by country, providing region-specific payments and content

The core point here is that a routing policy itself does not automatically know whether the target server is alive or dead. To prevent weighted routing or failover routing from sending traffic to a dead server, an administrator must create a Route 53 health check (Health Check) and associate it with the record (by enabling Evaluate Target Health or specifying a health check ID).

At this time, how the health check target endpoint (/api/health) is implemented is equally critical. If /api/health is merely a hollow shell (shallow check) that returns an unconditional 200 OK string without checking the database or external APIs at all, Route 53 assumes the server is healthy and continues routing traffic to it even when database connections are severed and all actual requests are spewing 500 errors. Conversely, if a heavy LLM invocation is executed on every health check, costs explode due to requests sent every few seconds by health checkers across the globe. Therefore, a health check must be designed to lightly verify the local process status and core dependencies (for example, a database connection pool SELECT 1), returning 503 Service Unavailable when an anomaly occurs.

Zero-downtime domain and server migrations and the law of prior TTL (Time To Live) reduction

Let us examine the mistake most frequently committed during server or platform migrations. A certain team was operating an existing server (IP 198.51.100.10) with the DNS A record TTL set as usual to 86,400 seconds (24 hours). They decided to cut over to a new server (IP 203.0.113.50) at 2:00 AM on Sunday, and at precisely 2:00 AM, entered the DNS console, changed the TTL to 60 seconds while simultaneously modifying the IP address to the new server, and then shut down the old server at 2:10 AM.

What was the result? Throughout the entire day on Sunday, more than half of the customers protested that they "cannot access the site." Why was reducing the TTL to 60 seconds at 2:00 AM of no use?

This is because DNS resolvers of telecommunications providers across the world that had already completed queries at 1:50 AM stored the old server IP (198.51.100.10) along with the old TTL instruction: 'Do not query again for the next 24 hours (86,400 seconds); serve this from cache!' Because a resolver does not even revisit the authoritative nameserver until its own cache validity duration expires, the new IP and the new 60-second TTL that we updated on the nameserver at 2:00 AM never even had an opportunity to be delivered to the resolver.

Therefore, the standard timeline for a zero-downtime DNS cutover must strictly follow the five-stage sequence below:

  1. Advance preparation (at least 24 to 48 hours prior to cutover, meaning well before the existing TTL duration): Keep the IP of the existing record as is, and lower only the TTL first to a short value (for example, 60 seconds to 300 seconds).
  2. Wait for existing cache expiration: If it was previously set to 24 hours, wait for at least 24 hours. Once this time elapses, the old cache across all resolvers worldwide will expire, putting every resolver into a state where it queries our nameserver afresh every 60 to 300 seconds.
  3. New environment preparation and parallel operation: Launch the new server and keep both environments open simultaneously so that both the old server and the new server can handle normal requests (such as pointing to the same database).
  4. Record cutover: Change the value of the DNS record to the new server IP (or new target). Because the TTL has already been reduced to 60–300 seconds, traffic across the globe shifts over to the new server within 1 to 5 minutes at most.
  5. Observation, old server shutdown, and TTL restoration: Verify that traffic no longer enters the access logs of the old server, decommission the old server, and restore the TTL to its normal operating value (for example, 3,600 seconds) to reduce DNS query costs and latency.

Cloudflare Proxied (orange cloud) versus DNS-only (gray cloud) and origin IP masking

When a domain is registered in Cloudflare, a cloud-shaped toggle switch appears next to each DNS record. This single switch changes the entire network path.

Mode Display DNS query response value Traffic path Active features
DNS Only Gray cloud Responds directly with the actual IP address of the origin server or the original CNAME target User → Direct connection to origin server Performs pure DNS resolution only (WAF, CDN cache, Workers, and DDoS L7 defense do not operate)
Proxied Orange cloud Responds substituted with Cloudflare Anycast edge IP addresses User → Cloudflare edge → Origin server WAF, Rate Limiting, CDN caching, SSL/TLS termination, Workers, AI Gateway, and origin IP masking all operate

There are two practical pitfalls that one must understand when turning on the orange cloud (Proxied):

  1. There are times when CNAME verification for external services or non-HTTP ports must be left on the gray cloud (DNS Only). For example, when an external email dispatch service (DKIM CNAME) or another platform (Vercel, AWS ACM certificate verification CNAME, etc.) verifies via DNS queries whether "a CNAME is accurately pointed to our side," enabling the orange cloud causes Cloudflare to hide the CNAME and respond with Cloudflare IPs (A/AAAA), resulting in the external platform failing verification with the error "cannot find CNAME configuration." Furthermore, because Cloudflare's default proxy relays only standard HTTP/HTTPS port (80, 443, etc.) traffic, attempting to connect directly to standard SSH (22) or DB (5432) ports through an orange-cloud domain will fail to establish a connection (in such cases, Cloudflare Tunnel or Spectrum from Chapter 4 is used).
  2. Leaving the origin server firewall open to the entire world (0.0.0.0/0) just because the orange cloud is enabled renders the WAF completely useless! If an attacker discovers the real IP address of the origin server via historical DNS lookup sites (SecurityTrails, etc.), accidentally exposed subdomains (direct.example.com), or broad IPv4 range scans, and fires requests directly at the origin IP with a Host: app.example.com header without passing through Cloudflare, they can bypass Cloudflare's WAF and Rate Limiting 100%. To prevent this, the origin server firewall must allow exclusively Cloudflare's public edge IP ranges, or lock down the origin using Authenticated Origin Pulls (mTLS client certificate verification) or Cloudflare Tunnel.

SSL/TLS encryption modes: Why Flexible must never be used and Full (Strict) is the standard

When using Cloudflare proxy (orange cloud), the encryption path is divided into two segments. The first is the [user browser ↔ Cloudflare edge] segment, and the second is the [Cloudflare edge ↔ our origin server (Origin)] segment. Cloudflare's SSL/TLS mode determines specifically how this second segment (edge ↔ origin server) is connected.

SSL/TLS mode Browser ↔ Cloudflare Cloudflare ↔ Origin server Fatal flaw or characteristics
Off Plaintext HTTP Plaintext HTTP No encryption across the entire path (prohibited from use)
Flexible HTTPS encryption Plaintext HTTP (port 80) 1) Exposed to sniffing because the edge-to-origin segment is plaintext<br>2) Causes an infinite redirect loop (ERR_TOO_MANY_REDIRECTS) if HTTPS redirection is enabled on the origin server!
Full HTTPS encryption HTTPS encryption (certificate not verified) Trusts the origin unconditionally even if the certificate is expired or a bogus self-signed certificate, making it vulnerable to man-in-the-middle (MITM) attacks
Full (Strict) HTTPS encryption HTTPS + strict verification of valid CA or Cloudflare Origin CA certificate The sole recommended standard for production. Guarantees end-to-end encryption and origin server identity verification

Here, the most famous incident scenario in both practice and exams is the infinite redirect loop (ERR_TOO_MANY_REDIRECTS) caused by Flexible mode.

Why does this happen?

  1. The user navigates to https://app.example.com in their browser.
  2. Because Cloudflare is in Flexible mode, it modifies and forwards the request to the origin server (Vercel, Nginx, ALB, etc.) over plaintext http://app.example.com (port 80, X-Forwarded-Proto: http).
  3. However, modern origin servers or web frameworks, for security reasons, react with: "Wait, a request came in over plaintext HTTP? Reconnect via https://app.example.com!" and return a 301/308 Redirect to https://app.example.com response.
  4. The browser follows instructions and requests https://app.example.com again, Cloudflare forwards it to the origin over http:// once more, the origin redirects to https:// again, and after spinning in an infinite loop, the browser halts with an ERR_TOO_MANY_REDIRECTS error!

Therefore, the solution is clear. Flexible mode must never be used; Full (Strict) mode must always be used. If automatically renewing a public certificate (such as Let's Encrypt) on the origin server is burdensome, installing a Cloudflare Origin CA certificate (valid for up to 15 years, dedicated exclusively to the segment between the Cloudflare edge and the origin server), which Cloudflare issues free of charge, on the origin server or ALB and enabling Full (Strict) resolves the issue at once.

WAF, Rate Limiting, Bot control, and protecting legitimate webhooks

At the Cloudflare edge, a three-layered defense shield operates to filter out malicious traffic before requests reach the origin server:

  • WAF Managed Rules: Automatically blocks SQL injection, XSS, Log4Shell, and attack patterns from the latest framework CVEs.
  • Rate Limiting Rules: Blocks with 429 Too Many Requests when a specific IP, user session, or API key sends an abnormally large volume of requests within a short window (for example, exceeding 10 requests per minute on /api/auth/login for login brute-force attacks, or exceeding 20 requests per minute on the high-cost AI generation API /api/chat). In NAT environments (corporate offices, universities, telecommunications provider gateways), hundreds of legitimate users share the same public IP; therefore, rate limits on sensitive APIs should take session cookies, authentication tokens, or composite keys into account alongside the IP alone to minimize false positives.
  • Bot control (Bot Fight Mode / Super Bot Fight Mode): Presents JavaScript challenges or Turnstile captchas to automated scrapers and crawlers.

A frequent production incident here occurs when Bot Fight Mode or overly aggressive WAF rules classify legitimate server-to-server webhook requests sent by external payment providers (Toss, Stripe, Lemon Squeezy), GitHub, or Slack as 'bots' and return a JavaScript challenge (HTML page), resulting in lost payment processing! An external webhook server is not a browser, and therefore cannot solve JavaScript challenges or captchas.

Therefore, when protecting webhook endpoints (for example, /api/payments/webhook), design as follows:

  1. Configure WAF custom rules so that interactive challenges targeted at browsers (JS Challenge / Managed Challenge) are not triggered on the /api/payments/webhook path, while avoiding reckless blanket deactivation of all security checks.
  2. Instead, in the application (or edge Worker) code, strictly verify the encrypted HMAC signature header (for example, X-Signature, Stripe-Signature) and timestamp sent by the webhook sender using a secret key to reject forged requests.

CDN cache rules and preventing cache poisoning for dynamic APIs and streaming

CDN caching is the prime contributor to accelerating response speeds for static assets (/static/*, fonts, public images) and reducing origin server load. However, the moment cache rules (Cache Rules) are incorrectly configured to cache dynamic responses, 'cache poisoning (Cache Poisoning / Web Cache Deception)', one of the most disastrous personal information leakage incidents in infrastructure history, occurs.

Imagine an administrator enabling Cache Everything and Ignore Cache-Control (ignoring origin headers) in Cloudflare Cache Rules for URI Path starts with /api/ or the entire site (*) in an attempt to alleviate origin server load:

  1. First, customer Hong Gil-dong calls /api/me (or server-side rendered /dashboard) while logged in.
  2. The origin server responds with Hong Gil-dong's name, email, recent AI consultation history, and even Set-Cookie: session=hong_secret in the response header.
  3. The Cloudflare edge node stores this response as is under the cache key (Cache Key) /api/me!
  4. One second later, when an unrelated user Kim Cheol-soo (or even an unauthenticated user) accesses /api/me, Cloudflare, without even querying the origin server, serves Hong Gil-dong's personal information and Hong Gil-dong's session cookie directly from the cache to Kim Cheol-soo!

Therefore, in the cache design of AI and web services, the following four cardinal rules must be guarded with one's life:

Target traffic Correct cache design (Cloudflare + Origin) Result when misconfigured
User-personalized APIs (/api/*), authentication verification, shopping carts, profile information Cloudflare Cache Rule: Bypass Cache + Origin response header: Cache-Control: private, no-store Account information and session cookies are exposed to others
Pages varying based on the Authorization header or session cookies Bypass cache (Bypass), or if caching is unavoidable, isolate cache keys and strictly apply the Vary header (never share-cache responses containing Set-Cookie) The first visitor's screen is replicated to all subsequent visitors
LLM real-time streaming responses (Content-Type: text/event-stream, SSE) Bypass Cache + disable response buffering (Cache-Control: no-cache, no-transform, X-Accel-Buffering: no) The edge buffers chunks for 30 seconds until the stream ends and flushes them all at once, breaking real-time typing effects and triggering timeouts
Hashed immutable static bundles (/_next/static/*, /assets/*.a1b2c3.js) Long-term caching at the edge and browser using Cache-Control: public, max-age=31536000, immutable Bundles are downloaded from the origin server every time, causing speed degradation and bandwidth waste

Cloudflare Workers and Queues: Edge computing and asynchronous task decoupling

Cloudflare provides Cloudflare Workers, a serverless runtime executing instantly based on lightweight V8 Isolates across worldwide edge nodes, and Cloudflare Queues, an asynchronous message broker:

  • Cloudflare Workers: Instead of launching heavy virtual machines or containers, Workers create isolated execution spaces (Isolates) in the V8 engine within a few milliseconds, resulting in cold starts that are virtually near 0 ms. They are ideal for lightweight gateway tasks such as performing initial JWT signature validation at the edge closest to the user to reject invalid requests before they reach the origin server, routing payment currencies and languages based on country headers (CF-IPCountry), or injecting static response headers (security headers such as Strict-Transport-Security and Content-Security-Policy). However, Workers have strict CPU compute time limits; furthermore, if a single centralized database is located far away (the RTT problem seen in Chapter 1), they should be tailored for edge routing, validation, and caching combinations or Smart Placement rather than heavy, multi-statement database transactions.
  • Cloudflare Queues: In AI services, there are numerous heavy post-processing tasks that cannot produce an answer within a single second when a user sends a request (for example, generating embeddings for a 100-page PDF, dispatching bulk notification emails, or handling complex settlement reconciliation after receiving external webhooks). Processing these synchronously within the user's HTTP request results in timeouts or directly translates external API outages into user-facing errors. Here, the front Worker (Producer) receiving the request places only the task message into Queues and immediately returns 202 Accepted, while a downstream Consumer Worker retrieves and processes messages in batches; decoupling them in this manner buffers against sudden traffic surges. In the event of transient failures, automatic retries with backoff are performed, and messages that ultimately fail are gathered separately into a Dead Letter Queue (DLQ) so that causes can be analyzed and tasks reprocessed without data loss.

Cloudflare AI Gateway: Observability, caching, rate limiting, and fallback for LLM traffic

When our application directly calls external LLM APIs such as OpenAI, Anthropic, and Google Gemini, what are the greatest operational pain points?

  1. Because multiple services and agents invoke APIs independently, it is impossible to see at a glance how many tokens and expenses are consumed by which feature, or what the latency (TTFT) and error rates are.
  2. Even when identical system prompts and identical questions are repeated hundreds of times, LLM costs are paid every single time while waiting multiple seconds.
  3. If a temporary outage (502/503) or rate limit (429) occurs with a specific LLM vendor (for example, OpenAI), our entire service grinds to an immediate halt.

Cloudflare AI Gateway is a dedicated LLM proxy gateway positioned between the application code and the LLM provider APIs. By simply changing the API base address (baseURL) to the AI Gateway address in an existing SDK, five powerful infrastructure controls can be acquired with almost no code modifications:

Core feature of AI Gateway Operating principle and operational impact
Unified observability (Analytics & Logging) Tracks request counts, input/output token counts, estimated costs, latency, and error codes (429/5xx) on a single dashboard regardless of provider
Semantic and exact-match caching (Caching) When an identical prompt and parameter request arrives again, immediately returns the response from the edge cache without invoking the LLM (cost of KRW 0, latency of a few dozen ms). However, requests containing user-specific sensitive data must be configured for cache exclusion
Rate limiting and budget control (Rate Limiting) Blocks traffic at the gateway before it reaches LLM providers if agent loop runaway or anomalous traffic exceeds a predetermined hourly request count
Automatic retries and model/vendor fallback (Dynamic Routing / Fallbacks) If the primary model (for example, Anthropic Claude) encounters a 5xx outage or timeout, automatically retries according to configured policies or immediately reroutes (falls back) to a standby model (for example, OpenAI GPT or Google Gemini) to maintain service continuity
Key management and centralized authentication (BYOK / Authenticated Gateway) Enforces an authentication token (cf-aig-authorization) on gateway access itself, protecting the gateway so that only authorized backends can pass through

Route 53 accelerated recovery: Until records can be modified again

Preparing for DNS failures requires dividing the concern into two distinct tasks: answering queries from resolvers, and administrators modifying records. Route 53 accelerated recovery, announced by AWS on November 26, 2025, targets the latter. Prior to that, there was no documented RTO specifying when DNS modifications could be performed again if the US East (N. Virginia) region went down. When this option is enabled for record management in a public hosted zone, it targets a 60-minute RTO to restore DNS modification capabilities even if that region becomes unavailable. It is an opt-in feature and is provided worldwide, excluding AWS GovCloud and the China regions.

Before including it in a runbook, two points should be noted. Sixty minutes is merely the target until the point at which modifications become possible again; for the modified values to reach users, the TTL of resolver caches must further elapse. Additionally, certain operations are blocked while failover is underway.

Operation during failover Availability
Modifying existing record values Available (the purpose of accelerated recovery)
Creating or deleting hosted zones Unavailable
Enabling or disabling DNSSEC signing Unavailable

Let us take as an example a team that maintained a primary server in Northern Virginia (us-east-1) and a standby server in Seoul. This team had been using a runbook where they set the api record TTL to 3,600 seconds and changed the target IP to Seoul in the console during a regional outage. Even if accelerated recovery regained modification capability in 60 minutes as targeted, it took up to an additional 3,600 seconds for old caches to clear. In the worst case, requests continued going to the stalled region for nearly two hours. The team revised their runbook as follows: they created the Seoul target in advance as a failover record attached to a health check, eliminating the need for manual edits. For records that had to be changed manually, they kept standard TTLs low. Creating new hosted zones and DNSSEC operations were removed from the failure phase and shifted to the routine preparation phase.

Route 53 DNS Firewall: Egress control inspecting domain names only

The resolver that servers or AI agents inside a VPC use when querying external names is now referred to in AWS documentation as the Route 53 VPC Resolver. Its previous name was Route 53 Resolver. DNS Firewall filters queries entering this resolver to block the path toward malicious domains.

Let us clarify the boundaries first. DNS Firewall inspects only domain names and filters only DNS traffic. It does not resolve a name to an IP and block that IP. If code connects directly via IP from the beginning, no query occurs, and the firewall cannot see that request. This is why egress control must not be entrusted to DNS Firewall alone, and a layer inspecting IPs and ports, such as security groups, must be maintained alongside it.

There are also gaps in domain lists. Domain Generation Algorithms (DGA) that churn out new domains daily, Dictionary DGAs that concatenate dictionary words to construct plausible names, and DNS tunneling that transmits data embedded in subdomain strings cannot be kept up with by lists alone. Current DNS Firewall provides Advanced rules to catch these threats in addition to domain lists.

An availability judgment also remains. When VPC Resolver fails to receive a response from DNS Firewall, the default behavior is fail closed, which blocks the query. The exfiltration path is closed, but name resolution halts during that time. For workloads such as orders and payments where downtime directly cuts revenue, the team must decide in advance whether to accept this default behavior as is.

Suppose a team running an internal document summarization agent in a VPC had configured only a blocklist of known malicious domains. When the agent fell prey to prompt injection and connected directly to https://198.51.100.7/upload, DNS Firewall had no opportunity to intervene. This request had to be severed at the security group outbound rules. Attempts to exfiltrate document fragments embedded in subdomains, such as q8x2.files.evil.example, were handled by the DNS tunneling protection of Advanced rules.

Workers secrets: Per-Worker secrets and account-level Secrets Store

Workers that verify webhook HMACs or attach AI Gateway authentication tokens require secret values. In Cloudflare, there are two places to store these values.

A Worker secret is a write-only value configured separately per Worker. Because the value cannot be read back after it has been entered, the original must be stored separately in the team's secrets management tool. The part requiring greater caution is wrangler secret put. This command does not merely change the value; it creates a new version of the Worker and deploys immediately. Because replacing keys on a production Worker is equivalent to a full deployment, change windows and rollback plans must be established using the same standards as a deployment.

Secrets Store aggregates and manages account-level secret values in a single centralized location. A Worker attaches a secrets_store_secrets binding and then retrieves the value with await env.BINDING.get(). Because it is an asynchronous call, omitting await results in a Promise object being placed in the header instead of the key string. As of November 1, 2026, Secrets Store is in open beta. Whether to adopt it immediately on paths like authentication where failure halts the entire service must be decided taking into consideration that it is a beta.

For example, suppose three Workers handling webhook verification, consultation summarization, and admin APIs used the same AI Gateway authentication token. When managed via Worker secrets, every time the token was changed, wrangler secret put had to be executed three times, and with each execution, a Worker was deployed as a new version. If one location was omitted when revoking the old token, that Worker alone was rejected at the gateway. Placing a single token in Secrets Store and having all three Workers read it through bindings reduced the replacement point to a single location.

Going deeper

Differences between DNS weighted routing and edge routing in zero-downtime blue-green infrastructure transitions

When conducting a canary transition where only 5% of traffic is initially directed to the new infrastructure (Green) and 95% remains on the existing infrastructure (Blue) during a large-scale architecture overhaul, should you use Route 53 weighted routing (DNS layer) or Cloudflare Workers / Load Balancing (HTTP edge layer)? The two approaches have critical differences in transition speed and rollback time.

Comparison criteria Route 53 weighted routing (DNS layer) Cloudflare edge routing (HTTP proxy layer)
Distribution unit DNS resolver cache query unit (tens of thousands of users under a single ISP resolver can receive the same IP all at once) Individual HTTP request or individual user cookie/session unit (exactly 5.0% of requests can be distributed)
Emergency rollback speed Even if the weight is changed to 0, some traffic continues to flow in until the DNS TTL and client DNS caches expire (several minutes to tens of minutes) Immediately upon changing edge configurations, 100% of all subsequent HTTP requests worldwide switch to the existing servers within 1–2 seconds
Session stickiness If a resolver receives a different IP upon re-querying, the server to which a user connects may change The same user can always be pinned to the same environment based on a cookie or user ID hash
Suitable scenarios Macro transitions between different cloud/CDN providers, transitions involving non-HTTP protocols Granular canary testing for web/API services, deployments requiring an immediate 1-second rollback

Therefore, there is no need to view the two approaches as mutually exclusive. In everyday operations, using Route 53 and Cloudflare together provides the most robust multi-layered architecture: perform fine-grained canary distribution and immediate circuit breaking between application versions or origin server pools at the edge proxy layer where HTTP headers and cookies can be inspected, while using DNS routing policies (maintaining low TTLs in advance) for macro-level disaster recovery, such as moving entire regions or changing CDN providers themselves.

Origin IP leak paths and complete origin lockdown

Even if you spend several million KRW a month on Cloudflare WAF to set up perfect blocking rules, if an attacker can send requests directly to the origin server's IP or origin platform address (e.g., my-app.vercel.app, or an AWS ALB default *.elb.amazonaws.com address), the WAF is nothing more than a paper tiger.

In practice, the paths through which origin addresses leak are remarkably diverse.

  1. An old IP used prior to adopting Cloudflare remains in historical DNS databases.
  2. A mail server (MX, mail.example.com) or development server (dev.example.com) is hosted on the same server, with only those records left open as gray-clouded (DNS Only).
  3. Application features such as sending password reset emails or downloading images (SSRF) send direct outbound requests to external servers, exposing the origin server's public IP.
  4. Vercel's default deployment domain (aidan-mu.vercel.app) remains open without protection or redirects.

Therefore, true edge security is achieved only when origin lockdown—where "the origin flatly rejects any request that did not pass through Cloudflare (or the designated proxy)"—is fully implemented.

  • Network firewall level: Narrow inbound port 443 on the origin Security Group from 0.0.0.0/0 strictly to the Cloudflare public IPv4/IPv6 list, or close all inbound ports entirely and connect exclusively via Cloudflare Tunnel (Chapter 4).
  • Mutual TLS authentication level (Authenticated Origin Pulls, mTLS): To prevent an attacker from bypassing Cloudflare IP range checks by creating another free Cloudflare account and setting their own domain's origin IP to our server IP, enable Authenticated Origin Pulls via per-zone or custom client certificates so that the origin responds only when presented with a TLS client certificate from 'our Cloudflare account zone'.
  • Platform domain level: When using a managed platform (such as Vercel) as the origin, block bypass access by either issuing a 308 Permanent Redirect for requests arriving on the default .vercel.app address to the official production domain (https://aidan.agentcat.app), or using deployment protection and signed custom header verification.

At work

Star Cluster Commerce: Infinite redirects and cart cache poisoning on the day of Cloudflare adoption

To prepare for Black Friday traffic surges and overseas bot attacks, 'Star Cluster Commerce', an AI-powered personalized gift recommendation shopping mall, decided to place Cloudflare in front of its existing AWS ALB. On a Friday evening, the engineer in charge changed the domain nameservers to Cloudflare and enabled two settings. First, reluctant to reconfigure the origin, the engineer left the SSL/TLS mode set to Flexible. Second, aiming to dramatically reduce server load, the engineer added a Cache Level: Cache Everything rule for all paths (*).

Five minutes after the transition, the entire site was paralyzed. First, half of the visiting customers saw an ERR_TOO_MANY_REDIRECTS error in their browsers and could not even open the initial page. A rule configured on the AWS ALB to "redirect HTTP (80) requests to HTTPS (443)" collided with Cloudflare's Flexible mode (transmitting edge-to-origin over HTTP 80), resulting in an infinite redirect loop.

Hurriedly disabling HTTP redirection on the ALB brought the site back up, but ten minutes later a far worse second incident occurred. Reports flooded customer support stating, "My cart and shipping address book contain a complete stranger's name, phone number, and AI gift consultation history!" Because of the Cache Everything rule, the JSON responses of /api/cart and /api/chat/history called by the first logged-in customer were cached in their entirety on the Cloudflare edge and subsequently served to other visiting customers—a textbook cache poisoning incident. In addition, real-time streaming for AI gift consultations (/api/chat/stream) stopped rendering character by character, stalling for 20 seconds before dumping the entire output all at once.

An infrastructure architect brought in on an emergency basis resolved the crisis in 15 minutes by executing the following actions in order:

  1. Immediate cache purge (Purge Everything) and dynamic path bypass: The architect performed a full purge of the Cloudflare cache, immediately erasing the contaminated personal information responses. Next, the architect overhauled the Cache Rules, locking them at highest priority so that /api/*, /auth/*, /checkout/*, and any requests containing Cookie or Authorization headers unconditionally triggered Bypass Cache. On the origin server, the architect also enforced Cache-Control: private, no-store headers on all personalized responses and explicitly specified Content-Type: text/event-stream along with Cache-Control: no-cache, no-transform on SSE streaming responses.
  2. Switch to Full (Strict) and origin protection: Because a valid ACM certificate was already attached to the ALB, the architect immediately switched the Cloudflare SSL/TLS mode to Full (Strict) and restored the HTTPS redirect on the ALB. The infinite loop vanished, and end-to-end traffic was securely encrypted.
  3. Post-incident measures: By cross-checking the access logs across the entire 12-minute window during which the cache was poisoned, the team identified 18 sessions where third-party shipping address details might have been exposed, and worked alongside the security team and the Personal Information Protection Officer to enforce session expirations and carry out statutory notification procedures.

Wing AI Lab: Uninterrupted AI Gateway fallback during an OpenAI outage and pre-shortened TTL migration

'Wing AI Lab', which operates an enterprise meeting minutes summarization service, faced two major challenges. One was migrating its authoritative nameservers and API endpoints from the existing Gabia DNS to Amazon Route 53 with zero downtime, and the other was eliminating a single point of failure (SPOF) where the entire meeting summarization service stalled whenever an outage hit a single LLM vendor.

To migrate the domain, the team first lowered the TTLs of all records in their existing DNS (previously 36,000 seconds = 10 hours) to 60 seconds on Thursday morning, three days (72 hours) ahead of the scheduled transition date. Early Sunday morning, after a sufficient waiting period during which resolvers worldwide were querying on a 60-second cycle, the team completed the switch by configuring the root domain (narae.ai) as an Alias record and the API subdomain (api.narae.ai) as a Failover record linked to health checks in the Route 53 hosted zone. Thanks to the pre-shortened TTLs, the transition wrapped up in two minutes without losing a single query to the old server, and once stability was confirmed, the TTL was restored to 3,600 seconds.

Next, they introduced Cloudflare AI Gateway and Queues into the LLM request path.

Section issue Existing architecture Improved edge and gateway architecture
Long summarization request after voice transcription completion Synchronously invoked the LLM directly from the webhook, leading to frequent timeouts and lost retries The transcription completion webhook verifies HMAC signatures and merely enqueues the job into Cloudflare Queues (202 Accepted) → Consumers process in batches and store failed jobs in a DLQ
Transient failure with a specific LLM provider (503/429) Entire summarization service failed during an OpenAI outage Configured AI Gateway Dynamic Routing: Call the primary model via an OpenAI-compatible endpoint, but automatically fall back immediately to a secondary alternate provider (Anthropic Claude) if consecutive 5xx/timeouts occur
Repeated calls for standard template classification Consumed paid tokens every time and incurred a 1.5-second latency Enabled AI Gateway caching (1-hour TTL) solely on deterministic prompts free of personal information, such as public template classification, saving 38% on token costs

Two months later, when a global API outage actually struck the primary LLM provider for 40 minutes, Wing AI Lab's summarization pipeline navigated the downtime with zero customer inquiries, thanks to AI Gateway automatically rerouting traffic to the alternate model within two seconds.

Common mistakes

  1. "You can simply configure a standard CNAME record for the root domain (example.com) just like you would for any subdomain." According to the DNS specification standards, the root domain (Zone Apex) must always have an SOA record and authoritative NS records present together at the apex; therefore, a standard CNAME record—which by definition cannot coexist with any other DNS record types for the same name—cannot be used. Instead, you must use Route 53's proprietary Alias record or Cloudflare's CNAME Flattening mechanism.
  2. "If you change the DNS record IP address on the day of server migration and simultaneously reduce the TTL to 60 seconds at that exact time, the update will propagate across the entire world in just 60 seconds." Recursive DNS resolvers that have already completed a previous query will continue to hold onto the old IP address in their local cache for the entire duration of the old TTL prior to the change and will not query authoritative servers again until that cache expires. Therefore, you must proactively lower the TTL well in advance and wait for a period of at least the 'existing TTL duration' prior to the actual cutover point.
  3. "Because installing an SSL certificate on the origin server is cumbersome, setting the Cloudflare SSL mode to Flexible is both secure and convenient." Not only does Flexible mode connect traffic between Cloudflare edge nodes and the origin server over unencrypted, cleartext HTTP (port 80), but if forced HTTPS redirection is enabled on the origin web server, it will also trigger a catastrophic ERR_TOO_MANY_REDIRECTS infinite redirect loop outage. You must without fail install an origin certificate (such as an Origin CA certificate) on the origin server and use Full (Strict) mode.
  4. "Since Cloudflare's orange cloud (Proxied) is turned on, leaving the origin server's security group wide open to 0.0.0.0/0 is fine because no one can access it directly anyway." The orange cloud simply modifies the public DNS query responses to resolve to Cloudflare's anycast IP addresses. If the actual real IP address of the origin server is discovered or exposed, an attacker can bypass the Web Application Firewall (WAF) completely by dispatching requests directly to that origin IP; consequently, you must securely lock down the origin server using methods such as origin firewall access restrictions, Authenticated Origin Pulls (mTLS), or Cloudflare Tunnel.
  5. "To reduce origin server load, it is recommended to enable the CDN Cache Everything rule on /api/* paths as well." If you cache API endpoints whose responses vary per user, or request paths where sensitive Set-Cookie or Authorization headers travel back and forth, on a shared public CDN, the personal information, authentication credentials, and private sessions of the first user will be served verbatim to subsequent users, resulting in a critical security breach. Personalized APIs and Server-Sent Events (SSE) streaming connections must always be configured to bypass the cache (Bypass).
  6. "CNAME records used for external platform domain ownership verification should also have the orange cloud (Proxied) turned on for enhanced security." If you enable the orange cloud, Cloudflare proxies the record and answers DNS queries with its own A and AAAA IP addresses instead of returning the canonical CNAME target; as a result, the external platform will be unable to look up and verify the required CNAME target string, causing domain ownership verification or SSL/TLS certificate issuance to fail. CNAME records used for domain verification must strictly be set to the grey cloud (DNS Only).

Summary at a glance

Key topic Core statement to remember for exams and practice
Zone Apex and Alias Because a standard CNAME cannot be placed on the root domain (example.com), use Route 53 Alias or Cloudflare CNAME Flattening.
Routing policies and health checks For weighted (canary), latency, and failover (disaster recovery / DR) routing to steer clear of unhealthy servers, you must associate health checks that verify actual service dependencies.
Zero-downtime migration and TTL Lower the TTL in advance to 60–300 seconds at least the existing TTL duration before the cutover window to fully clear out existing resolver caches before transitioning the IP address.
Orange cloud vs. grey cloud The orange cloud (Proxied) routes traffic through Cloudflare's edge network (WAF, CDN, Workers), whereas the grey cloud (DNS Only) directly exposes the origin IP address or CNAME target.
SSL/TLS Full (Strict) The Flexible mode leaves an unencrypted cleartext segment and triggers infinite redirect loops. Always install an origin certificate (such as an Origin CA certificate) and use Full (Strict).
Origin lockdown To prevent attackers from bypassing the WAF through direct IP access, enforce Cloudflare IP allowlists, Authenticated Origin Pulls (mTLS), or Cloudflare Tunnel.
Webhooks and WAF/bot control Configure bypass rules so that server-to-server webhook endpoints, such as payment gateways or GitHub, are never blocked by interactive JavaScript challenges, and verify message integrity in application code via HMAC signatures.
Preventing cache poisoning and buffering For personalized /api/* routes (Authorization, Set-Cookie), enforce Bypass Cache along with private, no-store, and disable response buffering and caching entirely for LLM SSE (text/event-stream).
Workers, Queues, and AI Gateway Workers handles edge ultra-low-latency request validation and routing, Queues handles asynchronous load buffering and dead-letter queues (DLQs), and AI Gateway manages unified LLM observability, rate limiting, and multi-vendor automated fallback.

Check the official docs

Self-check

3-1. Explain the technical reason why a CNAME record can be freely assigned to a subdomain (www.example.com) according to the DNS standards while a CNAME cannot be placed on the root domain (Zone Apex, example.com), and describe the specific solution provided in Route 53 when binding a root domain to an AWS Application Load Balancer (ALB).

3-2. When planning a zero-downtime server IP address migration for a domain whose existing TTL is 86,400 seconds (24 hours), explain based on the caching mechanisms and operating principles of recursive DNS resolvers why the administrator must proactively lower the TTL to 60–300 seconds at least 24 hours prior to the migration work rather than lowering it on the day of the cutover itself.

3-3. When an origin web server is configured with the directive "Redirect all unencrypted cleartext HTTP requests to HTTPS via a 301 redirect", explain what browser error is encountered by end users and why this occurs if Cloudflare's SSL/TLS encryption mode is set to Flexible, and designate the correct SSL/TLS mode that should be deployed instead.

3-4. Even when the orange cloud (Proxied) is active for a domain in Cloudflare and Web Application Firewall (WAF) rules are completely configured, explain the precise mechanism by which an attacker can bypass the WAF if they discover the origin server's true IP address, and outline two or more concrete methods to block this vector on the origin server side.

3-5. Regarding the /api/profile endpoint, which returns personalized user profile information, and the /api/chat/stream (text/event-stream) endpoint, which delivers real-time LLM streaming tokens, describe the specific security and operational incidents that transpire when indiscriminate edge caching and response buffering are enabled on a CDN, and present the correct Cache-Control header directives and edge cache rules for each.

3-6. Architecture design task: A customer inquiry summarization service that relies exclusively on a single LLM API (such as OpenAI) experiences frequent service disruptions due to transient upstream 503 service unavailability errors from the provider, as well as call rate limit exhaustion resulting from infinite agent loops. Explain how introducing Cloudflare AI Gateway can resolve these two issues by presenting three core features and architectural mechanisms.

Hands-on tasks

Exercise

Drafting a zero-downtime domain migration timeline and Route 53 / Cloudflare record design specification (45 minutes)

  1. Formulate a chronological, time-slotted operational runbook (covering D-2 days, D-Day 02:30, 03:00, 03:30, and D+1 day) to perform a zero-downtime cutover of an entire service.kr domain—currently managed on a third-party DNS provider with an existing TTL of 43,200 seconds (12 hours)—over to a newly constructed Route 53 and Cloudflare-based edge infrastructure at 03:00 early Sunday morning.
  2. For the following five records, construct a detailed comparison table detailing (a) the DNS record type (A/AAAA/CNAME/Alias/TXT/CAA), and (b) the Cloudflare proxy status (orange cloud vs. grey cloud) along with an explicit justification for each selection:
    • Root web domain service.kr
    • API service domain api.service.kr
    • Outbound email DKIM cryptographic signature verification record s1._domainkey.service.kr (CNAME)
    • Certificate Authority Authorization restriction policy record service.kr (CAA)
    • Internal private SSH bastion gateway ssh.service.kr

Done when: The TTL reduction timing is scheduled at least 12 hours prior to the cutover window, and the architectural rationales for handling the root domain and assigning external CNAME verification records to the grey cloud (DNS Only) are documented accurately.

Exercise

Building an edge security, caching, and AI Gateway architecture audit checklist (50 minutes)

  1. Populate the table rows with the five primary application paths of an AI-powered web application deployed behind Cloudflare (/_next/static/*, /, /api/user/me, /api/payments/webhook, and /api/ai/stream).
  2. For each respective path, fill out (a) the edge caching policy (Cache Everything vs. Bypass Cache), (b) the origin server Cache-Control header directives, (c) the specific enforcement strategy for WAF/Bot management challenges and rate limiting, and (d) supplementary validation mechanisms (such as authenticated session verification, webhook HMAC signature validation, etc.).
  3. For outbound LLM invocations executed internally within /api/ai/stream, draft a pseudocode snippet (or a structured logical flowchart) illustrating the Dynamic Routing fallback configuration in Cloudflare AI Gateway, clearly establishing how requests automatically fail over from a primary model to a secondary model hosted by an alternate provider upon encountering an upstream failure.

Done when: Personalized user APIs, inbound webhooks, and SSE event streams are strictly excluded (Bypass) from the shared CDN cache, webhooks are protected from being obstructed by interactive JavaScript challenges while their integrity is guaranteed via HMAC verification, and automated fallback routing across heterogeneous AI providers via AI Gateway is explicitly formulated.