Integration examples

Production patterns for C#, Node.js, and Python: clients, retries, and callbacks.

These examples show complete patterns you can adapt. Each reads the base URL and key from CLUSTERBOT_BASE_URL and CLUSTERBOT_API_KEY.

A reusable client

Wrap the API once and reuse it. Set a timeout, keep one HTTP client per process, and return the parsed result.

using System.Net.Http.Json;

public sealed record ModerationResult(
    string Outcome, string[] Categories, bool Flagged,
    string EvaluatedBy, double LatencyMs, Guid? ReviewId);

public sealed class ClusterbotClient(HttpClient http)
{
    public async Task<ModerationResult> ModerateAsync(
        string content, string? language = null, CancellationToken ct = default)
    {
        using var response = await http.PostAsJsonAsync("/v1/moderations",
            new { content, language }, ct);
        response.EnsureSuccessStatusCode();
        return (await response.Content.ReadFromJsonAsync<ModerationResult>(ct))!;
    }
}

// Program.cs
builder.Services.AddHttpClient<ClusterbotClient>(http =>
{
    http.BaseAddress = new Uri(builder.Configuration["Clusterbot:BaseUrl"]!);
    http.DefaultRequestHeaders.Add("X-Api-Key", builder.Configuration["Clusterbot:ApiKey"]);
    http.Timeout = TimeSpan.FromSeconds(30);
});
const BASE_URL = process.env.CLUSTERBOT_BASE_URL;
const API_KEY = process.env.CLUSTERBOT_API_KEY;

export async function moderate(content, { language, signal } = {}) {
  const response = await fetch(`${BASE_URL}/v1/moderations`, {
    method: "POST",
    headers: { "X-Api-Key": API_KEY, "Content-Type": "application/json" },
    body: JSON.stringify({ content, language }),
    signal: signal ?? AbortSignal.timeout(30_000),
  });
  if (!response.ok) {
    const problem = await response.json().catch(() => ({}));
    const error = new Error(problem.title ?? `HTTP ${response.status}`);
    Object.assign(error, { status: response.status, code: problem.code,
      retryAfter: response.headers.get("Retry-After") });
    throw error;
  }
  return response.json();
}
import os
import requests

session = requests.Session()
session.headers["X-Api-Key"] = os.environ["CLUSTERBOT_API_KEY"]
BASE_URL = os.environ["CLUSTERBOT_BASE_URL"]

def moderate(content: str, language: str | None = None) -> dict:
    response = session.post(
        f"{BASE_URL}/v1/moderations",
        json={"content": content, "language": language},
        timeout=30,
    )
    response.raise_for_status()
    return response.json()

Retries and backoff

Retry rate limits and temporary failures — 429 without a code, 500, and 503 — with exponential backoff and jitter. Don't retry validation, authentication, or quota_exceeded errors.

Each retry is a new, separately charged request. Server-side failures are refunded, so a retry after 503 costs no more than a single success.

const RETRYABLE = new Set([429, 500, 503]);

export async function moderateWithRetry(content, options = {}, attempts = 4) {
  for (let attempt = 1; ; attempt++) {
    try {
      return await moderate(content, options);
    } catch (error) {
      const retryable = RETRYABLE.has(error.status) && error.code !== "quota_exceeded";
      if (!retryable || attempt >= attempts) throw error;
      const backoff = Math.min(8_000, 500 * 2 ** attempt) * (0.5 + Math.random());
      // Retry-After is usually seconds; ignore anything else and never wait longer than a minute.
      const retryAfter = Number.parseInt(error.retryAfter ?? "", 10);
      const wait = Number.isFinite(retryAfter) && retryAfter >= 0 ? Math.min(retryAfter * 1000, 60_000) : backoff;
      await new Promise(resolve => setTimeout(resolve, wait));
    }
  }
}
import random
import time

RETRYABLE = {429, 500, 503}

def moderate_with_retry(content: str, attempts: int = 4) -> dict:
    for attempt in range(1, attempts + 1):
        response = session.post(f"{BASE_URL}/v1/moderations",
                                json={"content": content}, timeout=30)
        if response.ok:
            return response.json()
        try:
            code = response.json().get("code")
        except ValueError:
            code = None
        if response.status_code not in RETRYABLE or code == "quota_exceeded" or attempt == attempts:
            response.raise_for_status()
        retry_after = response.headers.get("Retry-After", "")
        backoff = min(8, 0.5 * 2 ** attempt) * (0.5 + random.random())
        # Retry-After is usually seconds; ignore anything else and never wait longer than a minute.
        delay = min(int(retry_after), 60) if retry_after.isdigit() else backoff
        time.sleep(delay)
// With Microsoft.Extensions.Http.Resilience: retries 429, 5xx, and timeouts
// with exponential backoff and jitter, honoring Retry-After.
builder.Services.AddHttpClient<ClusterbotClient>(/* … */)
    .AddStandardResilienceHandler(options =>
    {
        options.Retry.MaxRetryAttempts = 3;
        options.Retry.UseJitter = true;
        options.TotalRequestTimeout.Timeout = TimeSpan.FromSeconds(90);
    });

Moderating at volume

Each workspace can have two moderation requests in flight. Process queues with a small, fixed pool of workers rather than sending everything at once:

async function moderateAll(messages, concurrency = 2) {
  const results = new Array(messages.length);
  let next = 0;
  async function worker() {
    while (next < messages.length) {
      const index = next++;
      results[index] = await moderateWithRetry(messages[index]);
    }
  }
  await Promise.all(Array.from({ length: concurrency }, worker));
  return results;
}

Check GET /v1/usage before large batches to make sure you have enough credits.

Holding content for review

Store the reviewId with the message, then apply the final decision when it arrives:

const result = await moderateWithRetry(message.text);

switch (result.outcome) {
  case "Pass":
    await db.messages.update(message.id, { state: "published" });
    break;
  case "FlaggedForReview":
    await db.messages.update(message.id, { state: "pending", reviewId: result.reviewId });
    break;
  default:
    await db.messages.update(message.id, { state: "rejected", categories: result.categories });
}

Receiving callbacks

A minimal Node.js receiver using Express. It limits the body size, verifies the signature against the raw body before parsing, deduplicates by event ID, and acknowledges quickly. The verify function is shown in Review callbacks.

import express from "express";
import { verify } from "./verify.js";

const app = express();

app.post("/webhooks/clusterbot", express.raw({ type: "application/json", limit: "64kb" }), async (req, res) => {
  const rawBody = req.body.toString("utf8");
  if (!verify(req.get("Clusterbot-Signature"), rawBody, process.env.CLUSTERBOT_CALLBACK_SECRET))
    return res.sendStatus(401);

  const event = JSON.parse(rawBody);
  if (event.id !== req.get("Clusterbot-Event-Id")) return res.sendStatus(400);

  await db.transaction(async tx => {
    if (await tx.processedEvents.exists(event.id)) return;  // duplicate delivery
    await tx.processedEvents.insert(event.id);
    if (!["Pass", "Rejected"].includes(event.data.outcome)) throw new Error("Unexpected outcome");
    const state = event.data.outcome === "Pass" ? "published" : "rejected";
    await tx.messages.updateWhere({ reviewId: event.data.reviewId }, { state });
  });

  res.sendStatus(204);
});

Polling for a decision

If you don't use callbacks, poll the status endpoint until the review is decided:

def wait_for_decision(review_id: str, interval: float = 15) -> dict:
    while True:
        response = session.get(f"{BASE_URL}/v1/moderations/{review_id}", timeout=30)
        if response.status_code == 404:
            raise LookupError("Review not found or expired - do not treat as approved")
        if response.status_code in (429, 503):
            time.sleep(interval * 2)
            continue
        response.raise_for_status()
        status = response.json()
        if status["status"] != "Pending":
            return status
        time.sleep(interval)

In production, run polling in a background job rather than blocking a request thread.

Questions about this guide? Contact us or try requests in the playground.