Skip to content

Latest commit

 

History

History
90 lines (62 loc) · 2.48 KB

parallelization.md

File metadata and controls

90 lines (62 loc) · 2.48 KB

Run calls in parallel

The problem

A cafe adds a dish to the menu. It needs six short texts: a menu line, a social post, a window sign and more.

The first try writes them one after another. Each call waits for the one before it. No text needs any other text, so the waiting is wasted.

How it works

Run separate writing jobs at once.

These are parallel calls. This is also called fan out.

  1. Code starts one call for each text at the same time.
  2. Code waits for all of them and keeps each under its name.
  3. A gate in code checks that no text is empty. An empty one is written again.

For example, the window sign does not wait for the menu line to be done.

The flow

sequenceDiagram
    participant Cafe as Your code
    participant Model
    par menu line
        Cafe->>Model: write the menu line
    and window sign
        Cafe->>Model: write the sign
    and email
        Cafe->>Model: write the email
    end
    Model-->>Cafe: the texts
    alt one text is empty
        Cafe->>Model: write that one again
    end
Loading

Concepts

Run it

uv run lab parallelization naive
uv run lab parallelization

Add --case 2 or --case 3 to try the other cases.

Prove it

The cafe has three new dishes. Code times each one with a clock. A missing text adds a large charge.

Version Seconds spent waiting
One after another 21.0
At the same time 6.5

Now break it. Open the pattern file and find empty_parts. Make it return an empty list. Then run the test:

uv run pytest tests/promises/test_parallelization.py

The test fails, because a dish with a missing text is now published.

Stuck points

  • A "no key found" message means the key file is missing. Copy the example file and paste your key.
  • If you see a rate limit error, your key allows fewer calls at once. Wait and run it again.

What to watch for

You pay for the same number of calls. You only save time. Your times will differ from ours, because the network changes.

Use this only when no call needs the result of another.

Where to go next

Go to Review your own draft. It checks one draft before you send it.