Edge-First Architecture
Dev, Staging, and Prod Validated

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.

Cloudflare Workers D1 SQLite KV Storage R2 Object Store Durable Objects Queues mTLS WAF Terraform
Cloudflare Proof Surface

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.

How It Works

Request flow from reader to game round

1. Reader opens the Cloudflare lobby. Pages serves the static lobby and each game shell directly from the edge on `cfgp.cloud-acmetocasino.com`.
2. The browser creates a Cloudflare-native session. The frontend calls the Worker auth endpoint, which creates a player session and returns the token used by launch, balance, RNG, and betting flows.
3. Stateful gameplay stays at the edge. Durable Objects hold per-game session state for roulette, blackjack, and video poker while Workers expose the HTTP API used by the game clients.
4. Read models and compliance remain on-platform. D1, KV, and the backoffice Worker expose balances, session control, reality-check state, and operational views without routing the player flow back to the legacy stack.
5. This page explains the system. The book chapter gives the architecture and release model; the Cloudflare lobby is the live proof surface for the three games.
Runtime Map

Cloudflare-only path

browser Cloudflare Pages lobby API Worker Durable Object game session D1 / KV / Queues / R2 backoffice read models

For the current proof scope, the player-facing core is independent on Cloudflare: auth/session, launch, balance, rng, bet, and session-control enforcement.

What Changed

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.

Architecture Delta

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.

dev → `cfgp-dev.cloud-acmetocasino.com`
staging → `cfgp-staging.cloud-acmetocasino.com`
prod → `cfgp.cloud-acmetocasino.com`
Release Pipeline

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.

pnpm release:dev
pnpm release:staging
pnpm release:prod
End-to-End Tests

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.

Operational Lesson

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.

Why Cloudflare for iGaming

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.

bolt

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.

shield

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.

terminal

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.

storage

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.

key

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.

security

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.

Architecture

Request Flow: Browser to Edge to Origin

Player
Browser
Brazil / Global
Edge
Cloudflare
300+ PoPs · DDoS · WAF
Compute
Workers
TypeScript · No cold start
→ D1 → KV → R2
D1 Wallet DB
KV Sessions
R2 Game Assets
Origin
AcmeToCasino
Backend API
Cache HIT: <5ms Worker compute: <10ms Origin fallback: <80ms
Real Examples from the Book

Production Workers & Terraform

01

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.

workers/casino-gateway/src/index.ts
// 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);
  }
};
02

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.

workers/casino-gateway/src/wallet.ts
// 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 });
}
03

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.tf
# 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"
  }
}
In the Book

Chapters Covering Cloudflare

Ch. 44
Cloudflare Workers

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.

Workers Wrangler D1
Ch. 44b
Hybrid Runtime

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).

Hybrid Origin Architecture
Ch. 46
Brazil Platform

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.

Brazil PIX SIGAP
Compliance at the Edge

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.

public

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.

expression = "ip.geoip.country ne \"BR\""
action = "block"
# Brazilian platform: block all non-BR traffic
gavel

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.

Brazil — bet-brazil.cloud-acmetocasino.com — SIGAP, Lei 14.790
Malta/EU — casino.cloud-acmetocasino.com — MGA, GDPR
UK — Separate zone — UKGC, GamStop
Curaçao — Separate zone — GCB license
US (regulated states) — Per-state zones — NJ, MI, PA, WV
shield

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.

# Brazil zone headers
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
BrazilSPA-MF (Ministério da Fazenda)BR onlyBrazil (LGPD)BRLLive
Malta / EUMGAEU/EEAEU (GDPR)EURLive
United KingdomUKGCGB onlyUKGBPPlanned
CuraçaoGCBGlobal (excl. blocked)CaribbeanUSDPlanned
US — New JerseyDGENJ only (GPS)US (NJ)USDReference
SwedenSpelinspektionenSE onlyEU (GDPR)SEKPlanned
DenmarkSpillemyndighedenDK onlyEU (GDPR)DKKPlanned

Each jurisdiction runs as an independent Cloudflare zone with its own DNS, WAF rules, and compliance configuration. Covered in Chapters 6, 29, and 40.

Full Source Included

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.