PeaBox Lab › PeaLang › Learn › Chapter 13 › Lesson 4

Part III — Advanced Systems · Chapter 13 · Lesson 4 of 5 · 4 min read

Lesson 4: Task Groups, Structured Gathering, and Failure Handling

Lesson level: Advanced

Purpose: Run many tasks concurrently with guaranteed cleanup, gather their results in a predictable order, bound how many run at once, and handle failure without leaking work.

Release note: task-group API names are illustrative. The reserved keyword parallel (Chapter 2) may provide related syntax in your release; verify exact forms against v0.63.

Learning objectives

By the end of this lesson, you should be able to:

4.1 The problem with loose tasks

Starting a Future and forgetting it creates work with no owner. If it fails, nobody sees the error; if the caller returns, the task may keep running and write results after the request ended. Structured concurrency removes this by tying every task to a scope that waits for it.

4.2 Task groups

async function tiers_for(orders) {
  with std.async.task_group() as group {
    let tasks = []
    for order in orders {
      tasks.append(group.start(host.lookup_tier(order["customer_id"])))
    }
  }
  return [t.result() for t in tasks]
}

The group does not exit until every child has finished. Leaving the block therefore guarantees that no child is still running.

4.3 Structured gathering

let tiers = await std.async.gather([host.lookup_tier(id) for id in ids])

gather is a compact form of a task group that returns results in the order the work was listed, regardless of completion order. Stable ordering keeps output deterministic and comparable across runs and engines.

4.4 Bounded concurrency

Starting 10,000 lookups at once can overload a database. A limit caps how many children run at the same time; others wait for a slot.

with std.async.task_group(limit=20) as group {
  for order in orders { group.start(price_one(order)) }
}

4.5 Failure policies

PolicyBehaviourUse when
Fail fast (default)First error cancels siblings and is raised from the groupAny failure invalidates the whole result
Collect allEvery child finishes; results and errors are returned per itemPartial results are useful, as in batch reports
Retry inside childEach child retries its own transient errorsFailures are likely transient and idempotent

4.6 Fail fast in practice

When one child raises, the group cancels the rest, waits for their cleanup, and then raises the first error. Other errors that occurred during cancellation are attached as secondary information, not lost.

4.7 Collect-all in practice

let results = await std.async.gather(
  [price_one(o) for o in orders],
  return_errors=true
)
for r in results {
  if r.is_ok() { save(r.value()) } else { log_failure(r.error()) }
}

Each item becomes a Result (Chapter 7), so the caller decides per item. This suits nightly batches where one bad order should not discard the other 9,999.

4.8 Groups with deadlines

Place a deadline around a group to bound the whole batch, and inside each child to bound individual calls. When the outer deadline fires, the group cancels all remaining children and raises a timeout.

4.9 Shared state between children

Children can run in any order. Avoid having them append to the same list or update the same counter; let each return a value and combine results after the group exits. This keeps output deterministic and avoids lost updates between awaits.

4.10 Worked example

The nightly order_rules batch prices 10,000 orders with a limit of 20 concurrent tier lookups, collect-all failure handling, a 1-second deadline per lookup with fallback to "standard", and a 15-minute deadline for the whole batch. Results are gathered in input order, saved, and failures are written to a review queue with their order ids.

4.11 Common mistakes

MistakeConsequenceFix
Starting tasks outside any groupLeaked work and lost errorsAlways start tasks in a group
No concurrency limitOverloaded dependenciesSet a limit
Fail fast for batch jobsOne bad item discards all workUse collect-all
Children mutating shared listsNondeterministic outputReturn values and combine after

4.12 Guided practice

4.13 Hands-on lab

Implement the nightly batch for 1,000 synthetic orders with a fake host that fails 2 percent of lookups and occasionally sleeps past the per-call deadline. Run with limits of 1, 10, and 50 and compare total time and failure counts.

Deliverable: the batch script, a results table for each limit, and confirmation that output order matches input order.

4.14 Review questions

4.15 Applied challenge

Design a concurrent workflow that calls three different services per order. Choose limits, deadlines, and a failure policy for each, and justify them.

Lesson summary

Transition to the Chapter 13 Checkpoint

The checkpoint combines the chapter into one bounded concurrent workflow.

Lesson status: Ready for review.

← Previous Next →