Edge-First Architecture with Cloudflare
Global iGaming Platform at <20ms Latency
The book's Brazilian betting platform now runs as a greenfield Cloudflare-native stack with isolated dev, staging, and prod environments. Workers handle compute, Durable Objects keep stateful game sessions, D1 stores read models, Queues move events, R2 holds audit artifacts, and Terraform workspaces keep each rollout isolated from the others.
One chapter, one lobby, three live games
The editorial page lives here on thebackendofluck.com/tech/cloudflare.html. The operational proof lives on cfgp.cloud-acmetocasino.com, which acts as the dedicated Cloudflare lobby for the three validated games below.
Request flow from reader to game round
Cloudflare-only path
For the current proof scope, the player-facing core is independent on Cloudflare: auth/session, launch, balance, rng, bet, and session-control enforcement.
Roulette
Single-zero roulette running from the Cloudflare lobby with Cloudflare-native session, balance, RNG, and settlement flow.
Blackjack
Blackjack hand state managed on Durable Objects, launched and enforced entirely from the Cloudflare runtime.
Video Poker
Video poker round lifecycle exposed through the same Cloudflare-authored session and compliance controls as the other two games.
From Single Demo Stack to Environment-Aware Edge Platform
The current Cloudflare implementation is no longer just a chapter demo. It now has repeatable release automation, Pages deployment, end-to-end environment isolation, and an explicit operator runbook for shipping safely on the edge.
Greenfield stack isolated from the legacy domain
The new platform no longer reuses the legacy `new.acmetocasino.com` cutover path. It runs on dedicated Cloudflare-native hostnames under `cloud-acmetocasino.com`, with one Terraform workspace per environment and worker bindings synchronized to the real D1 and mTLS resources after provisioning.
Provision, deploy, and verify in one path
The operator flow is now automated: Terraform apply, D1 id resolution, mTLS certificate creation or reuse, Wrangler binding sync, secret rotation, worker deploy, Pages lobby publish, and live verification against the public hostname plus the API and backoffice routes.
Smoke-tested against live Workers endpoints
Each environment is validated after deploy with a live sequence: public lobby fetch on `cfgp*.cloud-acmetocasino.com`, session creation, `roulette` launch in `BR/BRL`, API health, and backoffice compliance. This catches Pages misconfiguration, binding drift, and propagation issues immediately after rollout instead of after player traffic arrives.
Cloudflare account quotas are deployment dependencies
The rollout exposed two real platform constraints: D1 is capped per account, and Cloudflare Pages custom domains are not fixed by DNS alone. Before `prod` could be provisioned, one unused demo D1 had to be retired to free capacity. Later, the public hostnames returned `522` until the Pages domains were attached and the static lobby was actually deployed. The chapter now has a stronger lesson: on edge platforms, quota management and Pages release discipline are part of release engineering, not afterthoughts.
The Edge Advantage
Gambling platforms demand low latency (players notice 100ms), DDoS resilience (constant target), global reach, and strict compliance. Cloudflare's platform addresses all four simultaneously.
Edge Computing
300+ cities. Workers run at the PoP closest to the player, not in a US-East datacenter. Brazilian players connect to Cloudflare's São Paulo or Fortaleza edge, achieving <5ms network hop.
DDoS Protection
iGaming platforms are attacked during peak betting events (finals, jackpots). Cloudflare absorbs volumetric attacks at the network layer before a single packet reaches the origin.
Workers Serverless
TypeScript Workers handle the API gateway, rate limiting, player routing, and game session management. No cold starts, isolate-based execution — not Node.js containers.
D1 Edge Database
SQLite at the edge. The wallet and player session tables live in D1, replicated globally. Event-sourced transactions ensure the balance is always consistent across replicas.
KV for Sessions
Player JWTs, rate limit counters, and game state are stored in Cloudflare KV. Globally consistent reads with eventual consistency writes — perfect for session data at scale.
WAF & Bot Management
Bot score <30 blocks bet placement. WAF rules enforce IP allowlists for internal APIs. Managed rulesets cover OWASP Top 10 without any origin-side configuration.
Request Flow: Browser to Edge to Origin
Production Workers & Terraform
Casino API Gateway Worker
The entry-point Worker handles rate limiting per player, routes requests to game or wallet services, and falls back to static assets. The rate limiter uses KV as a distributed counter with a 120-second TTL — no Redis, no external service.
// Cloudflare Worker: Casino API Gateway export default { async fetch(request: Request, env: Env): Promise<Response> { const url = new URL(request.url); // Rate limiting per player const playerId = request.headers.get('X-Player-ID'); const rateKey = `rate:${playerId}:${Math.floor(Date.now() / 60000)}`; const count = await env.KV.get(rateKey) || '0'; if (parseInt(count) > 100) { return new Response('Rate limited', { status: 429 }); } await env.KV.put(rateKey, String(parseInt(count) + 1), { expirationTtl: 120 }); // Route to game services if (url.pathname.startsWith('/api/gal/')) { return handleGAL(request, env); } if (url.pathname.startsWith('/api/wallet/')) { return handleWallet(request, env); } return env.ASSETS.fetch(request); } };
D1 Wallet with Event Sourcing
The wallet uses an event-sourced model in D1: deposits, wins, bets, and withdrawals are all immutable events. The current balance is derived by summing events — no mutable balance column that could go out of sync. This satisfies both ACID guarantees and the audit trail requirements of Brazilian gambling regulation.
// D1 Database: Player wallet with event sourcing async function handleWallet(request: Request, env: Env): Promise<Response> { const { player_id, amount, type } = await request.json(); // Event-sourced transaction const result = await env.DB.prepare(` INSERT INTO wallet_events (player_id, event_type, amount, created_at) VALUES (?, ?, ?, datetime('now')) RETURNING ( SELECT COALESCE(SUM( CASE WHEN event_type = 'DEPOSIT' THEN amount WHEN event_type = 'WIN' THEN amount ELSE -amount END ), 0) FROM wallet_events WHERE player_id = ? ) as new_balance `).bind(player_id, type, amount, player_id).first(); return Response.json({ balance: result.new_balance }); }
WAF Rules via Terraform
All Cloudflare configuration is managed through Terraform — including WAF rules. This ensures changes are reviewed in pull requests, rolled back if needed, and logged in the audit trail. The two rules shown block direct API access from non-whitelisted IPs and prevent bot-generated bets (Cloudflare's bot score 0–100).
# Terraform: Cloudflare WAF for gambling compliance resource "cloudflare_ruleset" "casino_waf" { zone_id = var.zone_id name = "Casino WAF Rules" kind = "zone" phase = "http_rq_firewall_managed" rules { action = "block" expression = "(http.request.uri.path contains \"/api/\" and not ip.src in {10.0.0.0/8})" description = "Block direct API access from non-whitelisted IPs" } rules { action = "block" expression = "(cf.bot_score lt 30 and http.request.uri.path contains \"/api/gal/bet\")" description = "Block bot betting attempts" } }
Chapters Covering Cloudflare
Deploying on Cloudflare Workers
Full migration of the casino backend to Workers: TypeScript Worker setup, Wrangler config, D1 schema, KV namespaces, and R2 bucket binding. Includes latency benchmarks vs. origin-only deployment.
Hybrid Runtime Architecture
Not everything belongs at the edge. Chapter 44b covers the decision framework: what stays in Workers (routing, sessions, simple queries) vs. what goes to origin (RNG, HSM operations, complex game logic).
Brazilian Betting Platform
End-to-end deployment of the Brazilian sports betting platform on Cloudflare, including PIX payment integration, SIGAP regulatory reporting from the edge, and geo-restriction rules enforcing Brazilian-only access.
Zone Control & Jurisdiction Management
Gambling is regulated per jurisdiction. Cloudflare's edge network enforces geo-restrictions, content rules, and regulatory requirements before traffic reaches the origin — at the network level, not the application level.
Geo-Restriction
Block or allow traffic by country at the edge. Brazilian platform restricts to BR-only. MGA license serves EU. UKGC serves GB. Cloudflare evaluates ip.geoip.country before the request reaches any backend.
action = "block"
# Brazilian platform: block all non-BR traffic
Multi-Jurisdiction
Different DNS zones serve different regulated markets. Each zone has its own WAF rules, rate limits, and compliance headers. One Cloudflare account manages all jurisdictions.
Compliance Headers
Each jurisdiction requires specific HTTP headers, cookie policies, and content restrictions. Cloudflare Transform Rules inject the right headers per zone — no application code changes needed.
X-Jurisdiction: BR
X-License: SPA-MF/2025
X-RG-Required: true
X-Age-Minimum: 18
X-Currency: BRL
Jurisdiction Matrix — Managed via Cloudflare Zones
| Jurisdiction | Regulator | Geo-Rule | Data Residency | Currency | Status |
|---|---|---|---|---|---|
| Brazil | SPA-MF (Ministério da Fazenda) | BR only | Brazil (LGPD) | BRL | Live |
| Malta / EU | MGA | EU/EEA | EU (GDPR) | EUR | Live |
| United Kingdom | UKGC | GB only | UK | GBP | Planned |
| Curaçao | GCB | Global (excl. blocked) | Caribbean | USD | Planned |
| US — New Jersey | DGE | NJ only (GPS) | US (NJ) | USD | Reference |
| Sweden | Spelinspektionen | SE only | EU (GDPR) | SEK | Planned |
| Denmark | Spillemyndigheden | DK only | EU (GDPR) | DKK | Planned |
Each jurisdiction runs as an independent Cloudflare zone with its own DNS, WAF rules, and compliance configuration. Covered in Chapters 6, 29, and 40.
Running on Cloudflare Right Now
These are real deployments from the book's reference platform, hosted on Cloudflare. Use them to explore what a production iGaming platform looks and behaves like at the edge.
The book's Brazilian betting platform. PIX payments, odds feeds, SIGAP reporting — fully deployed on Cloudflare Workers with D1 as the primary database.
The casino lobby and slot games served entirely from Cloudflare's edge. Game assets from R2, sessions from KV, wallet from D1 — zero origin requests for returning players.
Live sports data engine with cron triggers. Polls API-Football every 15 minutes and stores fixtures, standings, and top scorers in KV. The Brazilian betting frontend reads directly from this Worker — no origin requests for sports data.
All the Workers. All the Terraform. All 48 Chapters.
Every Worker, D1 schema, Terraform module, and Wrangler config from the book's reference platform is included with purchase — ready to deploy to your own Cloudflare account.