Day 4 of 5
⏱ ~60 minutes
Multi-Agent Systems — Day 4

The Pipeline Pattern: Parallel Processing with Multiple Agents

When you need to process many items — documents, data points, or requests — parallel agent pipelines dramatically reduce latency. Day 4 builds a parallel processing system.

Sequential vs Parallel

If you need to analyze 10 documents, sequential processing takes 10x the time of a single document. Parallel processing takes roughly the same time as one — all 10 run simultaneously.

parallel-pipeline.js
import Anthropic from '@anthropic-ai/sdk';
import * as dotenv from 'dotenv';
dotenv.config();

const client = new Anthropic();

async function analyzeItem(item, systemPrompt) {
  const response = await client.messages.create({
    model: 'claude-haiku-3-5', // Use Haiku for high-volume parallel tasks
    max_tokens: 512,
    system: systemPrompt,
    messages: [{ role: 'user', content: item }]
  });
  return response.content[0].text;
}

// Process items in parallel with concurrency limit
async function parallelProcess(items, systemPrompt, concurrency = 5) {
  const results = new Array(items.length);
  
  // Process in batches of `concurrency`
  for (let i = 0; i < items.length; i += concurrency) {
    const batch = items.slice(i, i + concurrency);
    const batchPromises = batch.map((item, idx) => 
      analyzeItem(item, systemPrompt).then(result => ({
        index: i + idx,
        result
      }))
    );
    
    const batchResults = await Promise.all(batchPromises);
    batchResults.forEach(({ index, result }) => {
      results[index] = result;
    });
    
    console.log(`Processed ${Math.min(i + concurrency, items.length)}/${items.length}`);
  }
  
  return results;
}

// Example: sentiment analysis of customer reviews
const reviews = [
  "Amazing product, exceeded my expectations!",
  "Terrible quality, broke after one week.",
  "Decent for the price, nothing special.",
  "Best purchase I've made this year.",
  "Would not recommend to anyone.",
  "Solid product, does what it says.",
];

const SENTIMENT_AGENT = 'Classify this text. Respond with JSON only: {"sentiment": "positive|negative|neutral", "confidence": 0.0-1.0, "key_phrase": "..."}'

console.time('parallel');
const results = await parallelProcess(reviews, SENTIMENT_AGENT, 3);
console.timeEnd('parallel');

reviews.forEach((review, i) => {
  const parsed = JSON.parse(results[i]);
  console.log(`"${review.slice(0, 40)}..." → ${parsed.sentiment} (${parsed.confidence})`);
});
💡
Use Haiku for high-volume parallel tasks: claude-haiku-3-5 is 10-20x cheaper than claude-opus-4-5 and much faster for simple, structured tasks like classification or extraction. Reserve Opus for complex reasoning.
Day 4 Exercise
Build a Batch Document Processor
  1. Run parallel-pipeline.js with the example reviews. Time it.
  2. Increase to 20 items and compare the time to processing them sequentially.
  3. Change the system prompt to extract different information (key topics, action items, etc.).
  4. Add error handling: what happens if one item fails? The current code will fail the whole batch.

Day 4 Summary

  • Promise.all() runs multiple API calls concurrently — add concurrency limits to avoid rate limit errors.
  • Claude Haiku is the right model for high-volume structured tasks: much cheaper and faster.
  • Batch results in the same array order as inputs for easy correlation.
  • Always handle individual item failures so one bad item doesn't kill the batch.
Finished this lesson?