Skip to content

Lesson 6 of 9 · 23m

Concurrency for Fleet Work

ThreadPoolExecutor, worker queues, bounded parallelism, cancellation, rate limits, and why most infrastructure automation is I/O-bound rather than CPU-bound.

Running fleet work serially is safe but slow. Running it with unbounded threads is fast until you overload the network, the API, or your own laptop. The correct design is bounded concurrency: enough workers to hide latency, few enough to control blast radius.

Most ops automation is I/O-bound

SSH commands, HTTP APIs, downloads, and database queries spend most of their time waiting. Python threads are useful despite the global interpreter lock because blocking I/O releases it.

from concurrent.futures import ThreadPoolExecutor, as_completed

with ThreadPoolExecutor(max_workers=8) as pool:
    futures = {pool.submit(probe, host): host for host in hosts}
    for future in as_completed(futures, timeout=300):
        host = futures[future]
        try:
            results.append(future.result())
        except Exception as exc:
            failures[host] = str(exc)

as_completed yields results as they finish, so one slow host does not hide all the fast failures.

Bound in-flight work and downstream load

Do not submit ten thousand tasks at once if each carries memory, sockets, credentials, or buffers. Chunk input or guard work with a semaphore. Fleet concurrency also multiplies downstream load: eight workers each making three API calls per second is twenty-four calls per second. Put a shared limiter at the dependency boundary, not inside each worker where everyone gets their own budget.

Cancellation is a design feature

Ctrl-C should mean "stop starting new work and wind down safely," not "leave seventeen SSH sessions in undefined states." Check a cancellation event before each host:

if stop_event.is_set():
    return {'host': host, 'status': 'skipped'}

You usually cannot make a remote command atomic. You can control whether the next host starts.

Report partial failure honestly

Useful output is not "done." It is a table of success, failure, skipped, timeout, and unknown. Treat timeout as unknown if the remote operation may still be running; operators can reconcile unknowns, but false success destroys trust. Keep canaries outside the main pool so a bad first result can stop the rollout before the fleet sees it.

Field notes

  • Threads share mutable state. Collect results from futures or queues instead of mutating shared dictionaries carelessly.
  • as_completed(timeout=...) applies to the whole iteration, not each future.
  • Do not retry every failure inside every worker; retries multiplied by hosts can become self-inflicted denial of service.
  • Log worker start and completion with host identity, not just count.

Was this lesson helpful?

Sign in to rate