Cloudflare
DNS & Zone Setup
2 topics
Add and Verify a Domain via API
Create a zone, list assigned nameservers, and automate onboarding for new domains in CI pipelines.
export CF_API_TOKEN="<api-token>"
# Create zone
curl -s -X POST "https://api.cloudflare.com/client/v4/zones" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json" \
--data '{"name":"example.com","account":{"id":"<account-id>"},"type":"full"}' | jq
# List zones to get zone_id and nameservers
curl -s -X GET "https://api.cloudflare.com/client/v4/zones?name=example.com" \
-H "Authorization: Bearer $CF_API_TOKEN" | jq '.result[] | {id, name, name_servers}'Use scoped API tokens instead of Global API Key.
Automate nameserver checks before deploying records.
Create DNS Records with Proxy Enabled
Add A/CNAME records and enable orange-cloud proxy to use CDN and WAF protections.
ZONE_ID="<zone-id>"
# A record for app.example.com proxied through Cloudflare
curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json" \
--data '{
"type":"A",
"name":"app",
"content":"203.0.113.10",
"ttl":1,
"proxied":true
}' | jq
# CNAME for www -> app
curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json" \
--data '{
"type":"CNAME",
"name":"www",
"content":"app.example.com",
"ttl":1,
"proxied":true
}' | jqUse proxied=true for HTTP(S) traffic you want protected and cached.
For mail records (MX), keep unproxied.
Performance & Caching
2 topics
Cache Rules for Static Assets
Increase cache hit ratio by applying aggressive TTL to hashed static files in production.
{
"description": "Cache static assets for 30 days",
"expression": "(http.request.uri.path matches \"^/assets/.*\\.(js|css|png|jpg|svg|woff2)$\")",
"action": "set_cache_settings",
"action_parameters": {
"cache": true,
"edge_ttl": {
"mode": "override_origin",
"default": 2592000
},
"browser_ttl": {
"mode": "override_origin",
"default": 604800
}
}
}Use content-hashed filenames so long TTL is safe.
Exclude HTML from long cache TTL unless using cache purge workflow.
Purge Cache by Tag in Deploy Pipelines
Purge only changed content using tags instead of clearing whole cache after every deploy.
ZONE_ID="<zone-id>"
# Purge only pages tagged during origin response (Cache-Tag header)
curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/purge_cache" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json" \
--data '{"tags":["post:123","category:news"]}' | jqSend Cache-Tag headers from origin app for targeted invalidation.
Avoid purge_everything in high-traffic environments.
Security: WAF, Bot Protection, and Rate Limiting
2 topics
WAF Custom Rule to Block Suspicious Paths
Block common probing patterns like wp-admin or .env scans on non-WordPress sites.
{
"description": "Block exploit scanning paths",
"expression": "(http.request.uri.path contains \"/.env\" or http.request.uri.path contains \"/wp-admin\")",
"action": "block"
}Start with log/challenge mode before block in production.
Scope rules by hostname when multiple apps share one zone.
Rate Limit Login Endpoint
Protect auth endpoints from brute-force attacks while allowing normal user traffic.
{
"description": "Rate limit login",
"expression": "(http.request.uri.path eq \"/login\" and http.request.method eq \"POST\")",
"action": "block",
"ratelimit": {
"characteristics": ["ip.src"],
"period": 60,
"requests_per_period": 10,
"mitigation_timeout": 600
}
}Use Turnstile or Managed Challenge for softer mitigation.
Whitelist internal monitoring IPs to prevent false positives.
Workers & Edge Functions
2 topics
Hello World Worker with Routing
Deploy lightweight edge logic close to users for fast responses and request manipulation.
export default {
async fetch(request, env, ctx) {
const url = new URL(request.url)
if (url.pathname === "/health") {
return new Response(JSON.stringify({ ok: true }), {
headers: { "content-type": "application/json" }
})
}
return new Response("Hello from Cloudflare Workers", { status: 200 })
}
}
// wrangler.toml
// name = "edge-app"
// main = "src/index.js"
// compatibility_date = "2026-01-01"
// routes = [{ pattern = "app.example.com/*", zone_name = "example.com" }]Pin compatibility_date and update deliberately.
Use routes to attach Worker only where needed.
KV-backed Feature Flags at the Edge
Store rollout flags in Workers KV and evaluate them per request without calling origin.
export default {
async fetch(request, env) {
const flag = await env.FLAGS.get("new_checkout")
const enabled = flag === "true"
return new Response(JSON.stringify({ newCheckout: enabled }), {
headers: { "content-type": "application/json" }
})
}
}
// wrangler.toml binding example:
// [[kv_namespaces]]
// binding = "FLAGS"
// id = "<kv-namespace-id>"KV is eventually consistent; avoid it for strongly consistent counters.
Good fit for feature flags, config, and redirects.
Zero Trust Access & Cloudflare Tunnel
2 topics
Expose Internal App Without Opening Inbound Ports
Use cloudflared tunnel to publish private services safely behind Cloudflare Access.
# Install cloudflared and authenticate
cloudflared tunnel login
# Create tunnel
cloudflared tunnel create internal-app
# Route DNS to tunnel
cloudflared tunnel route dns internal-app internal.example.com
# config.yml
# tunnel: <tunnel-uuid>
# credentials-file: /root/.cloudflared/<tunnel-uuid>.json
# ingress:
# - hostname: internal.example.com
# service: http://localhost:8080
# - service: http_status:404
# Run tunnel
cloudflared tunnel run internal-appNo public IP or open firewall ports required.
Run cloudflared as a service for resilience.
Require SSO for Admin Path
Protect sensitive paths (e.g., /admin) with identity-aware access policies.
application:
name: "Admin Portal"
domain: "internal.example.com"
session_duration: "24h"
policies:
- name: "Allow engineering via Okta"
decision: "allow"
include:
- email_domain:
domain: "company.com"
require:
- okta:
identity_provider_id: "<idp-id>"
- name: "Deny everyone else"
decision: "deny"Use short session durations for privileged apps.
Combine device posture checks for stronger security.
Related Cheat Sheets
More hands-on references connected to this topic.
Google Cloud Platform essentials: Compute Engine, GKE, Cloud Run, Cloud Storage, IAM, and core CLI commands.
shared topics, same difficulty
PostgreSQL cheat sheet: psql CLI, users & roles, backup & restore, VACUUM, locks, JSONB, CTEs, and indexes.
shared topics, same difficulty
kubectl commands, Pod/Deployment/Service manifests, config management, and cluster operations.
shared topics
FastAPI routes, request models, dependency injection, authentication, and async patterns.
same difficulty, keyword overlap
Related Articles
Background reading and deeper explanations for this sheet.
Intro to FastAPI: Build a Production-Ready Python API with Real Examples
FastAPI is one of the fastest ways to build modern APIs in Python without sacrificing code quality or developer experience. In this practical, beginner-friendly guide, you’ll learn how to create endpoints, validate data, handle errors, connect a database, secure routes, and prepare your FastAPI app for real-world deployment.
keyword overlap
Build an Agentic App with FastAPI and Azure AI Foundry: A Practical Beginner-to-Pro Guide
Learn how to design, build, and deploy an agentic application using FastAPI and Azure AI Foundry with practical, real-world examples. This guide walks you from architecture and setup to tool-calling, memory, observability, and production deployment patterns.
keyword overlap
Cost Optimization in Agentic Systems: The Most Underrated Lever for Reliable AI at Scale
Most teams building agentic systems obsess over accuracy and latency, but ignore the fastest path to sustainable scale: cost optimization. In this guide, you’ll learn practical cost models, real architecture patterns, and implementation tactics to cut spend without sacrificing quality or autonomy.
keyword overlap
GenAI SaaS Architecture: A Practical Blueprint for Building, Scaling, and Securing AI Products
Designing a SaaS product on top of GenAI is more than calling an LLM API—it requires thoughtful architecture across product, data, safety, and operations. This practical guide walks you through a beginner-friendly yet deep system blueprint, with real-world patterns, code snippets, and deployment strategies you can use immediately.
keyword overlap