Python
subprocess
scalability
performance optimization
programming tips

Python subprocess is not scalable by default, any simple solution you can recommend to make it scalable?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

Python's subprocess module is fine for launching one command at a time, but it does not become scalable automatically when you start many child processes. The main issues are unbounded concurrency, blocking waits, and pipe management. A simple way to make it scale better is to control concurrency explicitly with a worker pool or with asyncio.create_subprocess_exec.

Why Naive subprocess Code Stops Scaling

A straightforward subprocess.run call blocks until the command finishes.

python
1import subprocess
2
3result = subprocess.run(["echo", "hello"], capture_output=True, text=True)
4print(result.stdout)

That is perfectly fine for small scripts. It becomes a problem when you need to run many commands because each call waits synchronously, and launching too many processes at once can exhaust CPU, memory, file descriptors, or downstream system capacity.

So the first scalability rule is simple: do not start unlimited subprocesses at once.

Use a Thread Pool Around Blocking Subprocess Calls

If the work is mostly waiting for external processes to finish, a ThreadPoolExecutor is a practical first improvement.

python
1import subprocess
2from concurrent.futures import ThreadPoolExecutor
3
4commands = [
5    ["python3", "-c", "print('job1')"],
6    ["python3", "-c", "print('job2')"],
7    ["python3", "-c", "print('job3')"],
8]
9
10
11def run_command(cmd):
12    result = subprocess.run(cmd, capture_output=True, text=True, check=True)
13    return result.stdout.strip()
14
15with ThreadPoolExecutor(max_workers=4) as pool:
16    for output in pool.map(run_command, commands):
17        print(output)

This does not change how subprocess.run works internally, but it lets multiple external commands progress concurrently while keeping the concurrency cap explicit.

Use asyncio for Large Numbers of Child Processes

If you are already in async code or need finer control over many subprocesses, asyncio.create_subprocess_exec is a cleaner scaling path.

python
1import asyncio
2
3async def run_command(cmd):
4    proc = await asyncio.create_subprocess_exec(
5        *cmd,
6        stdout=asyncio.subprocess.PIPE,
7        stderr=asyncio.subprocess.PIPE,
8    )
9    stdout, stderr = await proc.communicate()
10    return proc.returncode, stdout.decode().strip(), stderr.decode().strip()
11
12async def main():
13    cmds = [
14        ["python3", "-c", "print('job1')"],
15        ["python3", "-c", "print('job2')"],
16    ]
17    results = await asyncio.gather(*(run_command(cmd) for cmd in cmds))
18    print(results)
19
20asyncio.run(main())

This model scales better when subprocess execution is part of a larger asynchronous workflow.

Concurrency Limits Matter More Than API Choice

The most important design decision is the concurrency limit. Whether you use threads or asyncio, unbounded fan-out is still a problem.

A semaphore is a simple way to cap async concurrency:

python
1import asyncio
2
3sem = asyncio.Semaphore(4)
4
5async def limited_run(cmd):
6    async with sem:
7        return await run_command(cmd)

That protects the machine and the external programs you are driving.

Watch Stdout and Stderr Volume

Scalability problems often come from output handling as much as process count. If child processes emit a lot of stdout or stderr and the parent does not read those streams correctly, the subprocesses can stall. Decide whether you need captured output, streaming logs, or fully redirected output before increasing concurrency.

Common Pitfalls

  • Launching hundreds of subprocesses at once with no concurrency limit.
  • Blocking on each child process sequentially when moderate parallelism would be safe.
  • Reading large stdout or stderr streams incorrectly and deadlocking on pipes.
  • Assuming subprocess scalability is mostly a Python GIL issue when the real bottleneck is process management and I O.
  • Treating thread pools and async subprocesses as equivalent without considering the surrounding application model.

Summary

  • 'subprocess is fine for small tasks, but naive usage does not scale automatically.'
  • The first improvement is explicit concurrency control.
  • 'ThreadPoolExecutor is a simple way to parallelize blocking subprocess calls.'
  • 'asyncio.create_subprocess_exec is better when subprocesses are part of async orchestration.'
  • The real scaling lever is bounded concurrency, not launching more child processes blindly.

Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design