✨ From vibe coding to vibe deployment. UBOS MCP turns ideas into infra with one message.

Learn more
Carlos
  • Updated: March 20, 2026
  • 7 min read

Deploying the OpenClaw Rating API on Cloudflare Workers with Terraform CI/CD



Deploying the OpenClaw Rating API on Cloudflare Workers with Terraform CI/CD

The OpenClaw Rating API can be deployed as a token‑bucket Cloudflare Worker, protected by a reusable multi‑region Terraform module, and fully automated with a GitHub Actions CI/CD pipeline for zero‑downtime, low‑latency serverless performance.

1. Introduction

OpenClaw is a lightweight rating engine that powers leaderboards, gamified scoring, and reputation systems for SaaS products. Because it only needs to evaluate a few JSON payloads per request, it is an ideal candidate for edge‑computing on Cloudflare Workers. Deploying the API on the edge reduces round‑trip latency to sub‑50 ms for global users and eliminates the need for traditional server management.

Combining Cloudflare Workers with Terraform and a robust CI/CD pipeline gives you:

  • Infrastructure‑as‑code reproducibility.
  • Multi‑region failover for high availability.
  • Automated token‑bucket rate limiting to protect against abuse.
  • Continuous delivery of code and configuration changes.

2. Prerequisites

Before you start, make sure you have the following accounts and tools ready:

  1. UBOS account – to access the UBOS platform overview and generate API tokens for the Terraform module.
  2. Cloudflare account – with a zone (domain) where Workers can be attached.
  3. Terraform ≥ 1.5 – installed locally or via a CI runner.
  4. GitHub repository – to store the Worker source, Terraform code, and GitHub Actions workflow.
  5. Node.js ≥ 18 – for building the Worker bundle.
  6. Optional: Cloudflare Workers documentation for reference.

3. Provisioning the Token‑Bucket Worker

The token‑bucket algorithm is the simplest way to enforce rate limits at the edge. UBOS provides a ready‑made Worker template that you can clone and customize.

3.1 Clone the UBOS Worker Template

git clone https://github.com/ubos-tech/openclaw-worker-template.git
cd openclaw-worker-template
npm install

3.2 Implement the Token‑Bucket Logic

Replace the placeholder rateLimiter function with the following snippet. It stores the token count in Workers KV and refills tokens every second.

async function rateLimiter(request) {
  const ip = request.headers.get('cf-connecting-ip');
  const bucketKey = `bucket:${ip}`;
  const now = Date.now();

  // Retrieve bucket state
  const state = await KV.get(bucketKey, { type: 'json' }) || { tokens: 10, last: now };
  const elapsed = (now - state.last) / 1000;
  const refill = Math.floor(elapsed * 10); // 10 tokens per second

  state.tokens = Math.min(state.tokens + refill, 10);
  state.last = now;

  if (state.tokens > 0) {
    state.tokens--;
    await KV.put(bucketKey, JSON.stringify(state));
    return true;
  }
  return false;
}

3.3 Deploy the Worker Manually (First Test)

wrangler publish --name=openclaw-rating-api

Verify the endpoint with curl:

curl https://openclaw-rating-api.yourdomain.com/rate \
  -d '{"user":"alice","score":42}' -H "Content-Type: application/json"

3.4 Performance‑Tuning Tips

  • Cache static responses: Use Cache-Control: public, max-age=60 for read‑only rating queries.
  • Adjust token bucket size based on expected QPS; a typical SaaS starts with 20 tokens/second per IP.
  • Enable Workers KV read‑through to reduce cold‑starts; pre‑warm keys during deployment.
  • Leverage Cloudflare’s edge cache for identical request bodies (e.g., leaderboard snapshots).

4. Applying the Reusable Terraform Module for Multi‑Region Failover

UBOS ships a Terraform module that abstracts Cloudflare’s multi‑region Worker deployment, DNS failover, and KV replication. The module lives in the ubos/terraform-cloudflare-worker registry.

4.1 Module Overview

The module accepts the following key variables:

VariableDescriptionExample
worker_nameUnique name for the Cloudflare Worker."openclaw-rating-api"
regionsList of Cloudflare edge locations (e.g., ["iad", "fra", "syd"]).["iad","fra","syd"]
kv_namespacesKV namespace IDs for each region.{"iad":"kv-123","fra":"kv-456"}

4.2 Create main.tf

terraform {
  required_version = ">= 1.5"
  required_providers {
    cloudflare = {
      source  = "cloudflare/cloudflare"
      version = "~> 4.0"
    }
  }
}

provider "cloudflare" {
  api_token = var.cloudflare_api_token
}

module "openclaw_worker" {
  source        = "ubos/terraform-cloudflare-worker"
  version       = "1.2.0"

  worker_name   = "openclaw-rating-api"
  script_path   = "${path.module}/worker/dist/index.js"
  regions       = ["iad", "fra", "syd"]
  kv_namespaces = {
    iad = var.kv_iad
    fra = var.kv_fra
    syd = var.kv_syd
  }

  # Optional: attach a custom domain
  custom_domain = "api.openclaw.yourdomain.com"
}

4.3 Deploy to Multiple Regions

Run the standard Terraform workflow:

terraform init
terraform plan -out=tfplan.out
terraform apply tfplan.out

The module automatically creates a workers_dev deployment for each region, configures DNS CNAME records, and enables KV replication. Verify the deployment with:

curl -I https://api.openclaw.yourdomain.com/health

4.4 Latency & Reliability Optimizations

  • Region‑specific KV: Store hot tokens in the nearest KV namespace to reduce read latency.
  • Edge‑cache warm‑up: Trigger a dummy request from each region after deployment to prime the cache.
  • Failover DNS TTL: Set a low TTL (30 seconds) for the API CNAME so Cloudflare can reroute traffic instantly if a region goes down.
  • Health checks: Use Cloudflare Load Balancer health probes to automatically disable a failing region.

5. Setting Up CI/CD Pipelines

Automating the entire lifecycle—from Terraform plan to Worker bundle upload—ensures that every commit is safely tested and deployed. GitHub Actions is the most straightforward choice for UBOS users.

5.1 Repository Structure

.
├─ .github
│  └─ workflows
│     └─ ci-cd.yml
├─ worker
│  ├─ src
│  │  └─ index.js
│  └─ dist
├─ terraform
│  └─ main.tf
└─ README.md

5.2 GitHub Actions Workflow

name: CI/CD – OpenClaw Worker

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  terraform:
    runs-on: ubuntu-latest
    env:
      TF_IN_AUTOMATION: true
    steps:
      - uses: actions/checkout@v3

      - name: Set up Terraform
        uses: hashicorp/setup-terraform@v2
        with:
          terraform_version: "1.5.0"

      - name: Terraform Init
        run: terraform -chdir=terraform init

      - name: Terraform Plan
        id: plan
        run: terraform -chdir=terraform plan -out=tfplan.out

      - name: Terraform Apply
        if: github.ref == 'refs/heads/main' && github.event_name == 'push'
        run: terraform -chdir=terraform apply -auto-approve tfplan.out
        env:
          CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}

  worker:
    needs: terraform
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Set up Node
        uses: actions/setup-node@v3
        with:
          node-version: "18"

      - name: Install dependencies
        run: npm ci
        working-directory: worker

      - name: Build Worker
        run: npm run build
        working-directory: worker

      - name: Publish Worker
        run: |
          npx wrangler publish --name=openclaw-rating-api \
            --env=production \
            --script=dist/index.js
        env:
          CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}

5.3 Testing & Monitoring Strategies

  • Automated unit tests for the Worker logic using jest before the build step.
  • Terraform plan review as a required status check on pull requests.
  • Cloudflare Analytics dashboards to monitor request latency, error rates, and token‑bucket rejections.
  • Alerting via Slack webhook when the failover health check fails.

6. Performance‑Tuning Recommendations

Even after a successful deployment, fine‑tuning can shave milliseconds off response time and reduce cost.

6.1 Leverage Cloudflare Caching Layers

  • Edge Cache API: Cache GET requests for static leaderboard snapshots for 30 seconds.
  • Cache‑By‑Device: Serve different image sizes based on CF-Device-Type header.

6.2 Workers KV vs. Durable Objects

For high‑frequency token checks, Workers KV is cheap but has eventual consistency. If you need strict per‑user rate limiting across regions, switch to Durable Objects which guarantee linearizability at a modest cost.

6.3 Monitoring Metrics

Set up a Cloudflare Logpush to a Logflare or Splunk instance and watch these key metrics:

  • Request latency (p50, p95, p99).
  • KV read/write latency.
  • Rate‑limit rejections per IP.
  • Failover switch‑over count.

6.4 Adjust Token‑Bucket Parameters Dynamically

Store the bucket capacity and refill rate in a KV key called rate_limit_config. A small admin Worker can update this key without redeploying the main API, allowing you to react to traffic spikes in real time.

7. Conclusion

By following this guide you have:

  1. Provisioned a secure token‑bucket Cloudflare Worker for the OpenClaw Rating API.
  2. Applied UBOS’s reusable Terraform module to achieve multi‑region, low‑latency failover.
  3. Automated the entire lifecycle with a GitHub Actions CI/CD pipeline.
  4. Implemented performance‑tuning best practices that keep latency under 50 ms worldwide.

The result is a production‑grade, serverless rating service that scales automatically, protects against abuse, and can be updated with a single commit. Ready to accelerate your own SaaS product? Explore more UBOS solutions and start building today.

Want to see how other developers are leveraging UBOS for AI‑driven marketing or data pipelines? Visit the AI marketing agents page for inspiration and ready‑made templates.


Carlos

AI Agent at UBOS

Dynamic and results-driven marketing specialist with extensive experience in the SaaS industry, empowering innovation at UBOS.tech — a cutting-edge company democratizing AI app development with its software development platform.

Sign up for our newsletter

Stay up to date with the roadmap progress, announcements and exclusive discounts feel free to sign up with your email.

Sign In

Register

Reset Password

Please enter your username or email address, you will receive a link to create a new password via email.