Swarms Logo

Production: Scale, Cost, and Operations

The gap between a working demo and a production system is operational: processing thousands of tasks, surviving rate limits, controlling spend, and knowing what your agents did last night. This part covers the endpoints and habits that close the gap.

90 min · 7 lessons · checkpoint · 7-question quiz

Part 4 progress · 0/7 lessons0 pts · Recruit

You will learn to

  • Process thousands of tasks with the batch completion endpoints
  • Apply reasoning agents to problems standard completions get wrong
  • Handle rate limits with headers, backoff, and retries
  • Cut spend with model tiering and overnight batch scheduling
  • Monitor cost, errors, and usage with logs and metrics endpoints
  • Understand regions, priority processing, and key hygiene
  • Ship against a production readiness checklist

Lesson 4.1

Batch processing at scale

Looping over ten thousand rows with sequential HTTP calls is slow and fragile. The batch endpoints accept a list of complete requests and execute them concurrently on the platform's thread pool. There is one for single agents and one for full swarms:

POST/v1/agent/batch/completions
POST/v1/swarm/batch/completions
batch_agents.py
triage_agent = {
    "agent_name": "Ticket Triage",
    "system_prompt": (
        "Classify the support ticket by urgency (low/medium/high) "
        "and category. Respond as JSON."
    ),
    "model_name": "gpt-4.1",
    "max_loops": 1,
}

payload = [
    {"agent_config": triage_agent, "task": ticket}
    for ticket in tickets  # e.g. thousands of ticket strings
]

response = requests.post(
    f"{BASE_URL}/v1/agent/batch/completions",
    headers=headers,
    json=payload,
)
results = response.json()

The swarm batch endpoint works the same way with SwarmSpec objects: fifty due-diligence swarms submitted as one overnight job is the canonical enterprise pattern. Batch endpoints are premium features available on Pro and Ultra plans.

Lesson 4.2

Reasoning agents

Some problems (multi-step quantitative analysis, competition-grade logic, careful legal reading) fail on a standard completion because the model commits to an early wrong step. Reasoning agents run architectures designed for deliberate, self-checking thought:

POST/v1/reasoning-agent/completions
reasoning_agent.py
payload = {
    "agent_name": "Quant Reasoner",
    "description": "Careful multi-step analytical reasoning",
    "system_prompt": "Work step by step and verify before answering.",
    "model_name": "claude-sonnet-4-20250514",
    "swarm_type": "reasoning-duo",
    "task": (
        "A company recognizes revenue over 24 months but bills "
        "quarterly in advance. Compute deferred revenue after month 7 "
        "on a $1.2M contract."
    ),
}

response = requests.post(
    f"{BASE_URL}/v1/reasoning-agent/completions",
    headers=headers,
    json=payload,
)

List the available reasoning architectures (duos, self-consistency, iterative reflection, and more) before choosing:

GET/v1/reasoning-agent/types

Note · Also available per-agent

Standard agents accept reasoning_enabled, reasoning_effort (low/medium/high), and thinking_tokens for models with native reasoning support. The dedicated endpoint adds full reasoning architectures on top.

Lesson 4.3

Rate limits, retries, and error handling

Production code assumes requests will sometimes fail. The API enforces limits across multiple time windows; check your current standing at any time:

GET/v1/rate/limits
Try it liveGET/v1/rate/limits
Your live limits and current usage across time windows.

Every rate-limited response also carries live X-RateLimit-* headers (limit, remaining, reset) so you can throttle without extra API calls. The status codes to handle:

StatusMeaningYour move
400Malformed request bodyFix the payload; do not retry as-is
401Missing or invalid API keyCheck the x-api-key header
402Insufficient creditsTop up, then retry
429Rate limit exceededBack off and retry after the reset
500Server errorRetry with exponential backoff
resilient_client.py
import time

def call_with_retries(url, payload, max_retries=3):
    for attempt in range(max_retries + 1):
        response = requests.post(url, headers=headers, json=payload)
        if response.status_code == 200:
            return response.json()
        if response.status_code in (429, 500) and attempt < max_retries:
            wait = 2 ** attempt  # 1s, 2s, 4s
            remaining = response.headers.get("X-RateLimit-Remaining")
            print(f"Retry {attempt + 1} in {wait}s (remaining: {remaining})")
            time.sleep(wait)
            continue
        response.raise_for_status()

Warning · Only retry what is safe

Retry 429s and 500s. A 400 or 402 will fail identically on every attempt, and blind retries on those just burn quota and time.

Lesson 4.4

Cost management

Spend on the Swarms API is a function of tokens, models, and agent count, which means it is controllable. The endpoints that give you visibility:

  • GET /v1/account/credits: current balance, including free and referral credits
  • GET /v1/usage/costs: the per-operation pricing used to compute your bill
  • GET /v1/usage/report: daily breakdowns of tokens, requests, and cost

The three levers that actually move the bill, in order of impact:

  1. Tier your models. Use frontier models only where the cognitive work is hardest (directors, synthesizers, judges) and cheaper models for extraction, classification, and formatting. This alone commonly cuts costs 2-5x.
  2. Batch overnight. Swarm completions submitted in the night-mode window (8 PM to 6 AM Pacific) get a 50% discount on token costs. Move every non-urgent pipeline there with a cron job.
  3. Cap max_tokens and max_loops. These are the only two settings that let costs run away. Set both deliberately on every agent.

Tip · Estimate before you scale

Run one representative task, read its usage field, multiply by your volume, and check the result against /v1/usage/costs. Do this before launching any batch job, every time.

Lesson 4.5

Observability: logs and metrics

When a pipeline ran overnight, you need to know what happened without re-running it. Two endpoints cover most operational questions:

GET/v1/swarm/logs

Returns the request history for all API keys on your account: what ran, when, with what configuration and outcome. Use it to audit failures and reconstruct what a swarm actually did.

GET/v1/metrics/summary
Try it liveGET/v1/metrics/summary
Your lifetime and recent completion counts.
Try it liveGET/v1/swarm/logs
Request history for your API keys; response can be large.
ops_dashboard.py
logs = requests.get(
    f"{BASE_URL}/v1/swarm/logs", headers=headers
).json()

metrics = requests.get(
    f"{BASE_URL}/v1/metrics/summary", headers=headers
).json()

credits = requests.get(
    f"{BASE_URL}/v1/account/credits", headers=headers
).json()

print("Recent completions:", metrics)
print("Credit balance:", credits)

Wiring these three calls plus the X-RateLimit-* headers into one dashboard gives an operator cost, error, and quota visibility on a single screen. That is the whole production observability story for most teams.

Lesson 4.6

Regions, priority, and security

Three platform properties matter once real users depend on your agents:

  • Global availability. The platform runs across four regions, and requests are served from the nearest one for lower latency and higher resilience. You do not configure anything; the same base URL routes globally.
  • Priority processing. During high-demand periods, requests from Premium subscribers are processed ahead of the free tier. If your workload is latency-sensitive at peak hours, this is the operational reason to upgrade, separate from the premium-only endpoints.
  • Security posture. Transport is encrypted, API keys are scoped and revocable, and the platform maintains security certifications and compliance standards (documented at docs.swarms.ai under Security). Your side of the contract: keep keys in a secrets manager, rotate them on any suspicion, and give each application its own key so revocation is surgical.

Tip · One key per application

Separate keys per app also makes /v1/swarm/logs and usage reports attributable: when spend spikes, you know which system did it in one glance.

Lesson 4.7

The production readiness checklist

Before pointing real traffic at your agents, walk this list:

  • API keys live in environment variables or a secrets manager, never in code
  • Every call path handles 400, 401, 402, 429, and 500 distinctly
  • 429 and 500 retries use exponential backoff with a retry cap
  • max_tokens and max_loops are explicitly set on every agent
  • High-volume workloads use batch endpoints instead of request loops
  • Non-urgent batches are scheduled into the overnight discount window
  • A daily job reads /v1/usage/report and alerts on cost anomalies
  • Failures are diagnosed from /v1/swarm/logs rather than re-runs
  • One representative task's cost was measured before scaling to N

Teams that adopt this list before launch spend their first production week tuning prompts. Teams that skip it spend that week writing this list from incident reports.

Checkpoint · Part 4

Checkpoint project: an overnight batch pipeline

The capstone for the course. Build a small but genuinely production-shaped system:

  1. Pick a repetitive task (score leads, triage tickets, summarize filings) and define one agent for it with explicit max_tokens and max_loops
  2. Measure the cost of one run from its usage field and estimate the cost of 500
  3. Submit 20+ tasks through /v1/agent/batch/completions wrapped in your retry function from lesson 4.3
  4. The next morning, verify the run from /v1/swarm/logs and /v1/usage/report without re-executing anything

If the numbers you estimated match the numbers you observed, you are operating the Swarms API the way production teams do, and you have finished the course. The examples library at docs.swarms.ai goes deeper on every pattern you have learned.

Knowledge check · Part 4

Test what you remember

7 questions. Answer from memory before checking; look back at the lessons only after you see your score.

  1. 1.You need to score 10,000 support tickets with one agent. What is the right approach?

  2. 2.Which status codes should your client retry?

  3. 3.What does the night-mode pricing window offer?

  4. 4.What is the highest-impact lever for cutting a swarm's cost?

  5. 5.An overnight batch behaved strangely. Where do you look first, without re-running anything?

  6. 6.How can your client track remaining quota without extra API calls?

  7. 7.Why give each application its own API key?

0 of 7 answered