Building a real-time streaming task manager with Parallel | Parallel

Introducing Parallel Search Turbo: the fastest and lowest-cost search for AI. Learn more.Learn more.

HumanMachine

October 6, 2025

\# Building a real-time streaming task manager with Parallel

Build a task streaming playground that showcases Parallel's Task API with real-time Server-Sent Events (SSE).

Tags:Developers

Reading time: 4 min

Github Try the App

This guide demonstrates how to build a complete task streaming playground that showcases Parallel's Task APIParallel's Task API with real-time Server-Sent Events (SSE). By the end, you'll have a full-featured application that creates tasks, streams their execution progress, and displays results as they arrive. This can be helpful for developers building with the Task API, demonstrating how to recreate the user interfaces in our PlaygroundPlayground.

Complete demo available at: https://oss.parallel.ai/tasks-sse/https://oss.parallel.ai/tasks-sse/

\## Key Features

\## The Architecture

The task streaming playground we're building includes:

\## Our technology stack

\## Why this architecture

\### Stateless Streaming Design

The key insight behind this implementation is that you don't need to maintain any backend state during streaming. The Parallel Task API's SSE endpoint provides the complete current state every time you connect, including:

This stateless design means your backend can be incredibly simple - just a CORS proxy. All the complexity lives in the well-tested Parallel infrastructure.

\### OAuth2 with PKCE Security

For production-ready authentication, we implement the complete OAuth2 flow with PKCE (Proof Key for Code Exchange):

  1. Dynamic Client Registration: Register OAuth client on-demand
  2. PKCE Challenge: Generate cryptographically secure code challenge
  3. Authorization Redirect: Send user to Parallel's OAuth server
  4. Token Exchange: Securely exchange authorization code for access token
  5. Persistent Storage: Store token in localStorage for session management

This provides enterprise-grade security without requiring pre-registration of OAuth clients.

Architecture diagram

\## Implementation

\### Real-Time Event Streaming

Server-Sent Events (SSE) provide the real-time updates for this Task manager that helps end-users understand the progress of the Parallel Task API. This is especially helpful for longer-running processors, like Pro and above. Unlike traditional polling approaches that repeatedly ask "are you done yet?", SSE creates a persistent connection that streams updates as they happen. However, implementing SSE correctly in the browser requires handling several complex challenges.

\#### Why Manual SSE Implementation?

While browsers provide a built-in `EventSource` API for SSE, it has a critical limitation: **you cannot set custom headers**. Since Parallel's API requires authentication via the `x-api-key` header, we must implement SSE manually using the Fetch API and ReadableStreams.

SSE data arrives as a continuous stream of bytes, not discrete messages. Network packets can split messages in unpredictable ways:

Our implementation handles this with a streaming buffer pattern:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';

while (true) {
  const { done, value } = await reader.read();
  if (done) break;

// Add new data to buffer
  buffer += decoder.decode(value, { stream: true });

// Split into complete lines
  const lines = buffer.split('\n');
  buffer = lines.pop(); // Keep incomplete line in buffer

// Process complete lines
  for (const line of lines) {
    if (line.startsWith('data: ')) {
      const data = JSON.parse(line.substring(6));
      handleEvent(data);
    }
  }
}``` const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';

while (true) {
  const { done, value } = await reader.read();
  if (done) break;

// Add new data to buffer
  buffer += decoder.decode(value, { stream: true });

// Split into complete lines
  const lines = buffer.split('\n');
  buffer = lines.pop(); // Keep incomplete line in buffer

// Process complete lines
  for (const line of lines) {
    if (line.startsWith('data: ')) {
      const data = JSON.parse(line.substring(6));
      handleEvent(data);
    }
  }
}
```

This pattern ensures we never lose data or attempt to parse incomplete JSON, regardless of how network packets arrive.

\#### Resilient Connection Management

Task execution can take anywhere from seconds to 30+ minutes. Network connections inevitably drop during long operations, so robust reconnection logic is essential:

1
2
3
4
5
6
7
8

if (streamReconnectAttempts < MAX_RECONNECT_ATTEMPTS &&
    currentTaskRun && ['queued', 'running'].includes(currentTaskRun.status)) {
streamReconnectAttempts++;
setTimeout(() => {
    console.log(`Reconnecting attempt ${streamReconnectAttempts}...`);
    startStream();
}, 2000);
}``` if (streamReconnectAttempts < MAX_RECONNECT_ATTEMPTS &&
    currentTaskRun && ['queued', 'running'].includes(currentTaskRun.status)) {
streamReconnectAttempts++;
setTimeout(() => {
    console.log(`Reconnecting attempt ${streamReconnectAttempts}...`);
    startStream();
}, 2000);
}
```

**Key resilience features:**

\#### Understanding the Event Stream Format

Parallel's SSE stream follows the standard Server-Sent Events specification. Each event is prefixed with `data: ` and terminated with double newlines. The implementation strips the prefix and parses the JSON payload:

1
2
3
4
5
6
7
8
9
10
11

for (const line of lines) {
  if (line.startsWith('data: ')) {
    try {
      const data = JSON.parse(line.substring(6)); // Remove 'data: ' prefix
      handleEvent(data);
    } catch (error) {
      console.error('Error parsing event data:', error, line);
    }
  }
}``` for (const line of lines) {
  if (line.startsWith('data: ')) {
    try {
      const data = JSON.parse(line.substring(6)); // Remove 'data: ' prefix
      handleEvent(data);
    } catch (error) {
      console.error('Error parsing event data:', error, line);
    }
  }
}

```

\#### Event Type Taxonomy

The stream delivers several categories of events, each serving a different purpose:

This rich event taxonomy enables granular UI updates - progress bars for stats, reasoning displays for AI thinking, and error handling for failures.

\#### Event Visualization and UI

The frontend renders different event types with appropriate styling:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

function handleEvent(data) {
console.log(`event [${data.type}]`, data);

let eventHtml = '';
let eventClass = '';

switch (data.type) {
    case 'task_run.state':
      eventClass = 'state';
      eventHtml = `
        <div class="event-type">TASK STATE</div>
        <div class="event-message">
          Status: <span class="status ${data.run.status}">${data.run.status}</span>
          ${data.run.error ? `<br><span class="error">Error: ${data.run.error.message}</span>` : ''}
        </div>
      `;

// Display final output
      if (data.output) {
        const outputHtml = formatOutput(data.output);
        eventHtml += `<div class="output-section">
          <strong>Final Output:</strong>
          ${outputHtml}
        </div>`;
      }
      break;

case 'task_run.progress_stats':
      eventClass = 'progress-stats';
      const stats = data.source_stats;
      eventHtml = `
        <div class="event-type">PROGRESS STATS</div>
        <div class="progress-stats">
          <div class="stat">Sources Considered: ${stats.num_sources_considered || 'N/A'}</div>
          <div class="stat">Sources Read: ${stats.num_sources_read || 'N/A'}</div>
        </div>
        ${stats.sources_read_sample ? `
          <div style="margin-top: 10px;">
            <strong>Sample Sources:</strong>
            <ul style="margin-top: 5px; margin-left: 20px;">
              ${stats.sources_read_sample.slice(0, 3).map(url => ``` function handleEvent(data) {
console.log(`event [${data.type}]`, data);

let eventHtml = '';
let eventClass = '';

### \\#\#\# CORS Proxy Worker

A simple worker solves a fundamental web security challenge. Modern browsers implement the Same-Origin Policy, which prevents JavaScript running on \`yourdomain.com\` from making direct API calls to \`api.parallel.ai\`. This security feature protects users from malicious websites, but it also blocks legitimate applications from accessing external APIs.

Traditional solutions involve building a full backend API server that handles authentication, request validation, and response transformation. Instead, we use a much simpler proxy pattern that acts as a transparent middleman:

- \- Path Rewriting: \`/tasks-sse/api/v1/tasks/runs\` becomes \`https://api.parallel.ai/v1/tasks/runs\`
- \- Header Preservation: All original headers (including \`x-api-key\`) are forwarded
- \- CORS Headers: Added to all responses to enable browser access
- \- Static Serving: The same worker serves the HTML frontend

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63

// @ts-ignore import indexHtml from "./index.html";

export default { async fetch(request, env, ctx) { const url = new URL(request.url);

// Serve the frontend if (url.pathname === "/tasks-sse/") { return new Response(indexHtml, { headers: { "Content-Type": "text/html;charset=utf8" }, }); }

// Proxy Parallel API requests if (url.pathname.startsWith("/tasks-sse/api/")) { // Remove /api prefix and forward to api.parallel.ai const targetPath = url.pathname.replace("/tasks-sse/api", ""); const targetUrl = https://api.parallel.ai${targetPath}${url.search};

// Clone the request but change the URL const modifiedRequest = new Request(targetUrl, { method: request.method, headers: request.headers, body: request.body, });

// Forward the request const response = await fetch(modifiedRequest);

// Clone the response to modify headers const modifiedResponse = new Response(response.body, { status: response.status, statusText: response.statusText, headers: { ...Object.fromEntries(response.headers), // Add CORS headers "Access-Control-Allow-Origin": "", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS", "Access-Control-Allow-Headers": "", }, });

return modifiedResponse; }

// Handle preflight requests if (request.method === "OPTIONS") { return new Response(null, { headers: { "Access-Control-Allow-Origin": "", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS", "Access-Control-Allow-Headers": "", }, }); }

return new Response(null, { status: 302, headers: { Location: "/tasks-sse/" }, }); }, };``` // @ts-ignore import indexHtml from "./index.html";

export default { async fetch(request, env, ctx) { const url = new URL(request.url);

// Serve the frontend if (url.pathname === "/tasks-sse/") { return new Response(indexHtml, { headers: { "Content-Type": "text/html;charset=utf8" }, }); }

// Forward the request const response = await fetch(modifiedRequest);

return modifiedResponse; }

return new Response(null, { status: 302, headers: { Location: "/tasks-sse/" }, }); }, };


\### OAuth Authentication

The OAuth flow implementation handles dynamic client registration, as well as the complete PKCE security protocol:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

async function startOAuth() {
try {
    // Register client dynamically
    const reg = await fetch("https://platform.parallel.ai/getKeys/register", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        redirect_uris: [window.location.origin + window.location.pathname]
      }),
    });

const { client_id } = await reg.json();

// Generate PKCE challenge
    const cv = btoa(crypto.getRandomValues(new Uint8Array(32))).replace(
      /[+/=]/g, (m) => ({ "+": "-", "/": "_", "=": "" }[m])
    );
    localStorage.setItem('code_verifier', cv);

const cc = btoa(
      String.fromCharCode(
        ...new Uint8Array(
          await crypto.subtle.digest(
            "SHA-256",
            new TextEncoder().encode(cv)
          )
        )
      )
    ).replace(/[+/=]/g, (m) => ({ "+": "-", "/": "_", "=": "" }[m]));

// Redirect to OAuth server
    const url = new URL("https://platform.parallel.ai/getKeys/authorize");
    Object.entries({
      client_id,
      redirect_uri: window.location.origin + window.location.pathname,
      response_type: "code",
      scope: "api",
      code_challenge: cc,
      code_challenge_method: "S256",
      state: Math.random().toString(36).substring(7)
    }).forEach(([k, v]) => url.searchParams.set(k, v));

window.location.href = url;
} catch (error) {
    alert('OAuth error: ' + error.message);
}
}``` async function startOAuth() {
try {
    // Register client dynamically
    const reg = await fetch("https://platform.parallel.ai/getKeys/register", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        redirect_uris: [window.location.origin + window.location.pathname]
      }),
    });

const { client_id } = await reg.json();

window.location.href = url;
} catch (error) {
    alert('OAuth error: ' + error.message);
}
}
```

\## Resources

\## Ready to get started?

Sign up for free. No credit card required.

Try ParallelTry Parallel Contact salesContact sales

Are you an agent? Read this to onboard ParallelAre you an agent? Read this to onboard Parallel

By Parallel

October 6, 2025

\## Related Posts80

Jul 30, 2026\ - Building an always-on background agent to proactively support customers

Tags: Developers

Author: By Khushi Shelat

Jul 21, 2026\ - Introducing the Parallel Responses API

Tags: Product

Author: By Parallel

Jul 20, 2026\ - Building a vendor intelligence system with Parallel

Tags: Developers

Author: By Sahith Jagarlamudi

Jul 16, 2026\ - Parallel and Google Cloud Announce Partnership for Agentic Web Search on Gemini Enterprise Agent Platform

Tags: Product

Author: By Parallel

Jul 15, 2026\ - $5 in free Parallel credits, every month

Tags: Product

Author: By Parallel

\ \ Jul 13, 2026\ \ - [Introducing Parallel Search Turbo](/content/blog/parallel-search-turbo/index.html) \ \ Author: By Parallel](/content/blog/parallel-search-turbo/index.html)

Jul 12, 2026\ - Building a realtime voice agent with GPT-Realtime-2.1 and Parallel Search Turbo

Tags: Developers

Author: By George Pickett

Jul 10, 2026\ - How Nooks cut web search costs 70.5% by switching to Parallel

Tags: Customers

Author: By Parallel

Jul 8, 2026\ - How Build created live geofenced alerts powered by Parallel for institutional real estate

Tags: Customers

Author: By Parallel

Jun 9, 2026\ - OpenClaw now has free, LLM-optimized web search by default powered by Parallel

Tags: Company

Author: By Parallel

Jun 5, 2026\ - Introducing real-time Entity Search

Tags: Product

Author: By Parallel

Jun 3, 2026\ - How we enrich & triage inbound leads using the Parallel Task API

Tags: Developers

Author: By Khushi Shelat

May 20, 2026\ - How AirOps creates citation-worthy content at scale, powered by Parallel

Tags: Customers

Author: By Parallel

May 18, 2026\ - Introducing Index by Parallel

Tags: Product

Author: By Parallel

May 7, 2026\ - Parallel Monitor API: New processor tiers, snapshots and event streams, and Basis on every event

Tags: Product

Author: By Parallel

May 4, 2026\ - How we built parallelmpp.dev

Tags: Developers

Author: By Son Do

Apr 29, 2026\ - How Actively's Per Account Agents use Parallel to turn the entire web into a proactive sales intelligence layer

Tags: Customers

Author: By Parallel

Apr 28, 2026\ - Parallel Raises at $2 Billion Valuation to Scale Web Infrastructure for Agents

Tags: Company

Author: By Parallel

Apr 24, 2026\ - Building a free CLI agent with Pi, Ollama, Gemma 4, and Parallel

Tags: Developers

Author: By Matt Harris

Apr 23, 2026\ - Parallel Search is now free for agents via MCP

Tags: Product

Author: By Parallel

Apr 21, 2026\ - Upgrades to the Parallel Search & Extract APIs

Tags: Benchmarks

Author: By Parallel

Apr 20, 2026\ - How Finch is scaling plaintiff law with AI agents that research like associates

Tags: Customers

Author: By Parallel

Apr 8, 2026\ - Genpact and Parallel Web Systems Partner to Drive Tangible Efficiency from AI Systems

Tags: Company

Author: By Parallel

Apr 8, 2026\ - How Genpact helps top US insurers cut contents claims processing times in half with Parallel

Tags: Customers

Author: By Parallel

Apr 7, 2026\ - A new deep research frontier on DeepSearchQA with the Task API Harness

Tags: Benchmarks

Author: By Parallel

Mar 30, 2026\ - How Modal saves tens of thousands annually by building in-house GTM pipelines with Parallel

Tags: Customers

Author: By Parallel

Mar 25, 2026\ - How Opendoor uses Parallel as the enterprise grade web research layer powering its AI-native real estate operations

Tags: Customers

Author: By Parallel

Mar 19, 2026\ - Introducing stateful web research agents with multi-turn conversations

Tags: Product

Author: By Parallel

Mar 18, 2026\ - Parallel is live on Tempo, now available natively to agents with the Machine Payments Protocol

Tags: Company

Author: By Parallel

Mar 17, 2026\ - How Parallel helped Kepler build AI that finance professionals can actually trust

Tags: Customers

Author: By Parallel

Mar 10, 2026\ - Introducing the Parallel CLI

Tags: Product

Author: By Parallel

Mar 4, 2026\ - How Profound helps brands win AI Search with high-quality web research and content creation powered by Parallel

Tags: Customers

Author: By Parallel

Mar 2, 2026\ - How Harvey is expanding legal AI internationally with Parallel

Tags: Customers

Author: By Parallel

Feb 23, 2026\ - How Tabstack by Mozilla enables agents to navigate the web with Parallel’s best-in-class web search

Tags: Customers

Author: By Parallel

Feb 4, 2026\ - Parallel Web Tools and Agents now available across Vercel AI Gateway, AI SDK, and Marketplace

Tags: Product

Author: By Parallel

Jan 28, 2026\ - Authenticated page access for the Parallel Task API

Tags: Product

Author: By Parallel

Jan 21, 2026\ - Introducing structured outputs for the Monitor API

Tags: Product

Author: By Parallel

Jan 15, 2026\ - Introducing research models with Basis for the Parallel Chat API

Tags: Product

Author: By Parallel

Jan 8, 2026\ - Build a real-time fact checker with Parallel and Cerebras

Tags: Developers

Author: By Parallel

Dec 17, 2025\ - Parallel Task API achieves state-of-the-art accuracy on DeepSearchQA

Tags: Benchmarks

Author: By Parallel

Dec 16, 2025\ - Introducing Granular Basis for the Task API

Tags: Product

Author: By Parallel

Dec 11, 2025\ - How Amp’s coding agents build better software with Parallel Search

Tags: Customers

Author: By Parallel

Dec 10, 2025\ - Latency improvements on the Parallel Task API

Tags: Product

Author: By Parallel

Nov 20, 2025\ - Introducing Parallel Extract

Tags: Product

Author: By Parallel

Nov 18, 2025\ - Introducing Parallel FindAll

Tags: Product,Benchmarks

Author: By Parallel

Nov 13, 2025\ - Introducing Parallel Monitor

Tags: Product

Author: By Parallel

Nov 12, 2025\ - Parallel raises $100M Series A to build web infrastructure for agents

Tags: Company

Author: By Parallel

Nov 11, 2025\ - How Macroscope reduced code review false positives with Parallel

Tags: Customers

Author: By Parallel

Nov 6, 2025\ - Introducing Parallel Search

Tags: Benchmarks

Author: By Parallel

Nov 3, 2025\ - Parallel processors set new price-performance standard on SealQA benchmark

Tags: Benchmarks

Author: By Parallel

Oct 30, 2025\ - Introducing LLMTEXT, an open source toolkit for the llms.txt standard

Tags: Product

Author: By Parallel

Oct 23, 2025\ - How Starbridge powers public sector GTM with state-of-the-art web research

Tags: Customers

Author: By Parallel

Oct 22, 2025\ - Building a market research platform with Parallel Deep Research

Tags: Developers

Author: By Parallel

Oct 17, 2025\ - How Lindy brings state-of-the-art web research to automation flows

Tags: Customers

Author: By Parallel

Oct 16, 2025\ - Introducing the Parallel Task MCP Server

Tags: Product

Author: By Parallel

Oct 9, 2025\ - Introducing the Core2x Processor for improved compute control on the Task API

Tags: Product

Author: By Parallel

Oct 8, 2025\ - How Day AI merges private and public data for business intelligence

Tags: Customers

Author: By Parallel

Oct 7, 2025\ - Full Basis framework for all Task API Processors

Tags: Product

Author: By Parallel

Sep 30, 2025\ - How Gumloop built a new AI automation framework with web intelligence as a core node

Tags: Customers

Author: By Parallel

Sep 16, 2025\ - Introducing the TypeScript SDK

Tags: Product

Author: By Parallel

Sep 12, 2025\ - Building a serverless competitive intelligence platform with MCP + Task API

Tags: Developers

Author: By Parallel

Sep 11, 2025\ - Introducing Parallel Deep Research reports

Tags: Product

Author: By Parallel

Sep 9, 2025\ - A new pareto-frontier for Deep Research price-performance

Tags: Benchmarks

Author: By Parallel

Sep 5, 2025\ - Building a Full-Stack Search Agent with Parallel and Cerebras

Tags: Developers

Author: By Parallel

Aug 21, 2025\ - Webhooks for the Parallel Task API

Tags: Product

Author: By Parallel

Aug 14, 2025\ - Introducing Parallel: Web Search Infrastructure for AIs

Tags: Benchmarks,Product

Author: By Parallel

Aug 7, 2025\ - Introducing SSE for Task Runs

Tags: Product

Author: By Parallel

Aug 5, 2025\ - A new line of advanced Processors: Ultra2x, Ultra4x, and Ultra8x

Tags: Product

Author: By Parallel

Aug 4, 2025\ - Introducing Auto Mode for the Parallel Task API

Tags: Product

Author: By Parallel

Jul 31, 2025\ - A state-of-the-art search API purpose-built for agents

Tags: Benchmarks

Author: By Parallel

Jul 31, 2025\ - Parallel Search MCP Server in Devin

Tags: Product

Author: By Parallel

Jul 28, 2025\ - Introducing Tool Calling via MCP Servers

Tags: Product

Author: By Parallel

Jul 14, 2025\ - Introducing the Parallel Search MCP Server

Tags: Product

Author: By Parallel

Jul 8, 2025\ - Introducing Source Policy

Tags: Product

Author: By Parallel

Jul 2, 2025\ - The Parallel Task Group API

Tags: Product

Author: By Parallel

Jun 17, 2025\ - State of the Art Deep Research APIs

Tags: Benchmarks

Author: By Parallel

Jun 10, 2025\ - Parallel Search API is now available in alpha

Tags: Product

Author: By Parallel

May 29, 2025\ - Introducing the Parallel Chat API

Tags: Product

Author: By Parallel

May 16, 2025\ - Introducing Basis with Calibrated Confidences

Tags: Product

Author: By Parallel

Apr 24, 2025\ - Introducing the Parallel Task API

Tags: Product,Benchmarks

Author: By Parallel