Swarms provides powerful utilities for scaling agent execution horizontally through concurrent and parallel processing. This guide covers the different scaling patterns, performance optimization techniques, and best practices for running agents at scale.
Run multiple agents on the same task concurrently using ThreadPoolExecutor:
from swarms import Agent, run_agents_concurrently# Create multiple agentsagents = [ Agent( agent_name=f"Worker-{i}", model_name="gpt-5.4", max_loops=1, ) for i in range(5)]# Run all agents concurrently on the same taskresults = run_agents_concurrently( agents=agents, task="Analyze the potential impact of AI on healthcare", max_workers=None, # Uses 95% of CPU cores by default)# Results come back in input order, so results[i] belongs to agents[i]for agent, result in zip(agents, results): if isinstance(result, Exception): print(f"{agent.agent_name} failed: {result}") else: print(f"{agent.agent_name} result: {result}")
A failing agent does not stop the others. Its slot in the results holds the exception it raised instead of an output.
Pass distinct Agent instances. Each agent keeps one conversation, so listing the same instance twice makes both runs write to the same history.
from swarms import run_agents_concurrently# Process image across multiple agentsresults = run_agents_concurrently( agents=vision_agents, task="Analyze this medical scan", img="path/to/scan.jpg", max_workers=5,)
swarms does not ship a dedicated uvloop-specific execution function. For maximum async
throughput on Linux/macOS, install uvloop yourself and install it as the event loop
policy before calling the standard async helpers (run_agents_concurrently_async,
run_agent_async):
import asynciofrom swarms import Agent, run_agents_concurrently_asynctry: import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())except ImportError: pass # Falls back to the default asyncio event loopasync def main(): agents = [ Agent(agent_name=f"Async-Agent-{i}", model_name="gpt-5.4") for i in range(10) ] results = await run_agents_concurrently_async( agents=agents, task="High-throughput task processing", ) return resultsresults = asyncio.run(main())
Process agents in batches to avoid resource exhaustion:
from swarms import run_agents_concurrently_multiprocessimport os# Process large number of agents in batchesagents = [Agent(agent_name=f"Agent-{i}") for i in range(100)]results = run_agents_concurrently_multiprocess( agents=agents, task="Process this task", batch_size=os.cpu_count(), # Process in CPU-sized batches)
from swarms import batched_grid_agent_execution# Create specialized agentsagents = [ Agent(agent_name="Researcher", system_prompt="Research expert"), Agent(agent_name="Writer", system_prompt="Content writer"), Agent(agent_name="Analyst", system_prompt="Data analyst"),]# Different task for each agenttasks = [ "Research AI trends", "Write a blog post", "Analyze market data",]# Execute in parallelresults = batched_grid_agent_execution( agents=agents, tasks=tasks, max_workers=None, # Uses 95% of CPU cores)# Results maintain order of input agentsfor i, result in enumerate(results): print(f"{agents[i].agent_name} completed: {tasks[i]}") print(f"Result: {result}")
from swarms import run_agents_with_different_tasks# Create agent-task pairsagent_task_pairs = [ (researcher, "Research quantum computing"), (writer, "Write about AI ethics"), (analyst, "Analyze stock trends"), (editor, "Edit research paper"), # ... hundreds more pairs]# Process in batchesresults = run_agents_with_different_tasks( agent_task_pairs=agent_task_pairs, batch_size=10, # Process 10 at a time max_workers=5, # Use 5 workers per batch)
# Bound the context window and let the agent auto-compress near the limitagent = Agent( agent_name="Memory-Efficient-Agent", model_name="claude-sonnet-4-6", context_length=4000, context_compression=True, # Auto-summarize when nearing the limit (default))# Manual compaction after processing, if neededfor task in large_task_list: result = agent.run(task) agent.short_memory.compact(summary="Summary of processed tasks so far.")
def resilient_concurrent_run(agents, task, max_workers=None): results = run_agents_concurrently( agents=agents, task=task, max_workers=max_workers, ) # Failed agents come back as exceptions; retry those one at a time for i, result in enumerate(results): if isinstance(result, Exception): logger.warning(f"{agents[i].agent_name} failed: {result}; retrying") results[i] = agents[i].run(task) return results
Agent itself does not take a timeout constructor parameter. Enforce timeouts at the
execution layer instead, by bounding a future’s result when running concurrently:
from concurrent.futures import ThreadPoolExecutor, TimeoutErroragent = Agent( agent_name="Timeout-Agent", model_name="claude-sonnet-4-6",)with ThreadPoolExecutor(max_workers=1) as executor: future = executor.submit(agent.run, "Analyze this task") try: result = future.result(timeout=30) # Set based on expected task duration except TimeoutError: logger.error("Agent run exceeded the 30s timeout")