|
| 1 | +--- |
| 2 | +title: Batching tasks |
| 3 | +order: 6 |
| 4 | +--- |
| 5 | + |
| 6 | +# Batching tasks |
| 7 | + |
| 8 | +Some tasks have a high fixed cost per call but become much cheaper when processed |
| 9 | +together. Think of database writes, calls to an external API, ML inference, |
| 10 | +event publishing or search indexing — running them one by one wastes most of the |
| 11 | +time on overhead. If a single call takes ~1 second, then 10 separate calls take |
| 12 | +~10 seconds, but processing all 10 at once might take only ~3 seconds. |
| 13 | + |
| 14 | +Taskiq can collect many task invocations into a single batched call. Instead of |
| 15 | +running every message on its own, the worker buffers messages of the same task |
| 16 | +and executes the function once with the whole list. |
| 17 | + |
| 18 | +## Defining a batched task |
| 19 | + |
| 20 | +Pass `batch=True` to the `task` decorator and declare the function with a single |
| 21 | +parameter that receives the list of items. |
| 22 | + |
| 23 | +```python |
| 24 | +@broker.task(batch=True, batch_size=100, batch_timeout=3) |
| 25 | +async def process_items(items: list[int]) -> int: |
| 26 | + return sum(items) |
| 27 | +``` |
| 28 | + |
| 29 | +Each `.kiq` call sends a single item, exactly like a normal task: |
| 30 | + |
| 31 | +```python |
| 32 | +await process_items.kiq(1) |
| 33 | +await process_items.kiq(2) |
| 34 | +``` |
| 35 | + |
| 36 | +The worker accumulates these items and calls `process_items` once with the |
| 37 | +collected list (e.g. `[1, 2, ...]`). |
| 38 | + |
| 39 | +::: tip Typed by design |
| 40 | + |
| 41 | +`.kiq` accepts a single element, while the function body receives `list[item]`. |
| 42 | +Both sides are correctly typed: `process_items.kiq(1)` type-checks, but |
| 43 | +`process_items.kiq([1, 2])` is reported as a type error. |
| 44 | + |
| 45 | +::: |
| 46 | + |
| 47 | +## When a batch is flushed |
| 48 | + |
| 49 | +A batch is sent for execution as soon as **either** condition is met: |
| 50 | + |
| 51 | +- **`batch_size`** — the buffer reaches this number of items, or |
| 52 | +- **`batch_timeout`** — this many seconds pass since the first item entered the |
| 53 | + buffer. |
| 54 | + |
| 55 | +Whichever happens first wins. You must set at least one of the two; you can set |
| 56 | +both. The timer starts with the first item of a fresh buffer and resets after |
| 57 | +each flush. When a worker shuts down gracefully, any buffered items are flushed |
| 58 | +so nothing is lost. |
| 59 | + |
| 60 | +Each worker buffers independently and keeps a separate buffer per task name. |
| 61 | + |
| 62 | +## Results and acknowledgement |
| 63 | + |
| 64 | +A batch produces a single result. That same return value (or error) is stored |
| 65 | +for **every** task in the batch, so each `.kiq` call can still await its own |
| 66 | +result. If the batched function raises, every task in the batch receives that |
| 67 | +error. Every message is acknowledged according to the configured |
| 68 | +[acknowledgement type](./cli.md). |
| 69 | + |
| 70 | +::: caution Per-item granularity |
| 71 | + |
| 72 | +Batching trades per-item isolation for throughput. The whole batch shares one |
| 73 | +result and one fate — there are no per-item results or per-item error handling. |
| 74 | +A batched task must take exactly one positional argument (the list); keyword |
| 75 | +arguments are not part of the batched call. |
| 76 | + |
| 77 | +::: |
| 78 | + |
| 79 | +## Trying it locally |
| 80 | + |
| 81 | +Batching is a worker-side feature, but the `InMemoryBroker` supports it too, so |
| 82 | +you can try it without setting up a real broker. Call `wait_all` to flush any |
| 83 | +pending batches and wait for them to finish before reading results. |
| 84 | + |
| 85 | +@[code python](../examples/batching/inmemory_batch.py) |
| 86 | + |
| 87 | +Running this prints a single batch execution and the shared result: |
| 88 | + |
| 89 | +```bash:no-line-numbers |
| 90 | +$ python broker.py |
| 91 | +Processing a batch of 10 items. |
| 92 | +Returned value: 45 |
| 93 | +... (10 times) |
| 94 | +``` |
| 95 | + |
| 96 | +::: warning InMemoryBroker behavior |
| 97 | + |
| 98 | +The `InMemoryBroker` executes tasks inplace, so batches are flushed by |
| 99 | +`batch_size`, by `wait_all`, or — with `await_inplace=True` — immediately as |
| 100 | +one-item batches. This is convenient for tests, but to see real batching across |
| 101 | +processes you need a distributed broker and a worker. |
| 102 | + |
| 103 | +::: |
| 104 | + |
| 105 | +## Running with a worker |
| 106 | + |
| 107 | +In production, batching happens inside the worker. Using |
| 108 | +[taskiq-redis](https://pypi.org/project/taskiq-redis/) as an example: |
| 109 | + |
| 110 | +@[code python](../examples/batching/redis_batch.py) |
| 111 | + |
| 112 | +Start one or more workers: |
| 113 | + |
| 114 | +```bash:no-line-numbers |
| 115 | +taskiq worker broker:broker |
| 116 | +``` |
| 117 | + |
| 118 | +Then run the script to send items. The worker collects them and runs |
| 119 | +`process_items` once per batch. With several workers, each one batches the |
| 120 | +messages it receives independently, so the load is spread across all of them. |
0 commit comments