Dynamic blocks: choose the boundary before increasing concurrency

Published
Updated

TLDR

Generate downstream work from individual items. Check the initial read, dependencies and collection step before expecting a smaller memory footprint.

A fictional engineer arranges blank violet work cards into separate channels on a quiet studio desk.
Editorial illustration of planning the unit of work. Generated artwork, not a product capture or a customer scene.

Dynamic blocks create downstream work from items emitted by an upstream block. They let you describe a repeated processing path once and create its children at runtime. That is a choice about how work is organized; the reader, executor and dependencies still determine what can run within available resources.

Start with the first whole-input read. A loader that reads an entire file and then slices its dataframe has already needed memory for that read. Adding downstream branches cannot undo it. If the source reader supports incremental input, a bounded input unit can move this boundary earlier.

A whole purple input slab moves into a loading tray and is divided into six pieces afterward.
Whole-file read, then split: the loader has already needed memory for the complete input before later chunks exist. Those chunks cannot remove that earlier requirement. Conceptual operation order, not a runtime measurement.

Keep an in-memory path when the input comfortably fits and that is the simpler design. For larger inputs, check the reader and output requirements before selecting the number of branches. Some operations need information across chunks and require a different algorithm.

Dynamic blocks

A dynamic block will create multiple downstream blocks at runtime.

The number of blocks it creates is equal to the number of items in the output data of the dynamic block multiplied by the number of its downstream blocks.

For example, the following data loader block will output a list of 2 lists. The 1st item in the list contains a list of 3 dictionaries containing user information.

from typing import Dict, List

@data_loader
def load_data(*args, **kwargs) -> List[List[Dict]]:
    users = []
    metadata = []

    for i in range(3):
        i += 1
        users.append(dict(id=i, name=f'user_{i}'))
        metadata.append(dict(block_uuid=f'for_user_{i}'))

    return [
        users,
        metadata,  # optional
    ]

If the above data loader has 2 downstream blocks (e.g. 2 blocks that depend on this data loader), then this dynamic block will create 6 total downstream blocks at runtime (3 users multiplied by 2 downstream blocks).

A dynamic block must return a list of 2 lists of dictionaries (e.g. List[List[Dict]]).

For example, a data loader block returns the following output:

[
  [
    { "id": 1, "name": "user_1" },
    { "id": 2, "name": "user_2" },
    { "id": 3, "name": "user_3" }
  ],
  [
    { "block_uuid": "for_user_1" },
    { "block_uuid": "for_user_2" },
    { "block_uuid": "for_user_3" }
  ]
]

The number of items in this list of dictionaries will correspond to how many downstream blocks get created at runtime.

For example, if this dynamic block has a downstream transformer block with the following code:

from typing import Dict, List

@transformer
def transform(data: Dict, *args, **kwargs) -> List[Dict]:
    data['id'] = int(data['id']) * 100
    return [data]

The return output data of this downstream transformer block will be:

[
  {
    "id": 100,
    "name": "user_1"
  }
]

Every downstream block from a dynamic block is referred to as a dynamically created block.

The number of these blocks created are determined by the return output data of a dynamic block.

For example, if a dynamic block returns the following data:

[
  [
    { "id": 1, "name": "user_1" },
    { "id": 2, "name": "user_2" },
    { "id": 3, "name": "user_3" }
  ],
  [
    { "block_uuid": "for_user_1" },
    { "block_uuid": "for_user_2" },
    { "block_uuid": "for_user_3" }
  ]
]

Then there will be 3 dynamically created blocks for every downstream block of that dynamic block.

If the dynamic block had 1 downstream block, then 3 blocks will be dynamically created.

For example, if the downstream block was a transformer with UUID anonymize_user_data and the following code:

from typing import Dict, List

@transformer
def transform(data: Dict, *args, **kwargs) -> List[Dict]:
    data['id'] = int(data['id']) * 100
    return [data]

There will be 3 dynamically created blocks with the following UUID and return output data:

Dynamic block UUID

Return output data

anonymize_user_data:for_user_1

[{ "id": 100, "name": "user_1" }]

anonymize_user_data:for_user_2

[{ "id": 200, "name": "user_2" }]

anonymize_user_data:for_user_3

[{ "id": 300, "name": "user_3" }]

​Downstream blocks of dynamically created blocks

If a dynamically created block has downstream blocks, those downstream blocks will be created multiple times. The number of times those are created correspond to how many blocks were created dynamically from the dynamic block.

In the current example, 3 blocks were created dynamically (3 users, 1 downstream block from the dynamic block). If the above transformer block has 2 downstream blocks, then 6 more blocks will be created.

For example, if the transformer block anonymize_user_data has 2 downstream blocks with UUIDs clean_column_names and compute_engagement_score, the following blocks will also be dynamically created:

  • anonymize_user_data:for_user_1 → clean_column_names:for_user_1 → compute_engagement_score:for_user_1 → clean_column_names:for_user_1 → compute_engagement_score:for_user_1
  • anonymize_user_data:for_user_2 → clean_column_names:for_user_2 → compute_engagement_score:for_user_2 → clean_column_names:for_user_2 → compute_engagement_score:for_user_2
  • anonymize_user_data:for_user_3 → clean_column_names:for_user_3 → compute_engagement_score:for_user_3 → clean_column_names:for_user_3 → compute_engagement_score:for_user_3

The data that is passed into each of these downstream blocks (e.g. clean_column_names, compute_engagement_score) will come from its upstream block (e.g. anonymize_user_data:for_user_1, anonymize_user_data:for_user_2, anonymize_user_data:for_user_3).

For example, the blocks clean_column_names:for_user_1 and compute_engagement_score:for_user_1 will have input data with the following shape and value:

{
  "id": 100,
  "name": "user_1"
}

Reduce output

By default, dynamically created blocks will create more dynamically created blocks from their own downstream blocks. A dynamically created block will pass its return output data to its downstream blocks and so on.

However, a dynamically created block can be configured to reduce all the outputs across each dynamically created block and combine them into a single list of items.

If we configure the above transformer block anonymize_user_data to reduce its output, then there will only be 2 downstream blocks instead of 6.

The 2 downstream blocks will be clean_column_names and compute_engagement_score. The input data to each of these 2 downstream blocks will be:

[
  { "id": 100, "name": "user_1" },
  { "id": 200, "name": "user_2" },
  { "id": 300, "name": "user_3" }
]

SQL blocks can be dynamic or be a child of a dynamic block.

Here is an example pipeline with code:

   [data_loader]
         ↓
[dynamic_sql_loader]
         ↓
   [transformer]

data_loader.py: dynamic block

@data_loader
def load_data(*args, **kwargs):
    return [[dict(uuid=1), dict(uuid=2)]]

dynamic_sql_loader: dynamic block, dynamic child

SELECT * FROM {{ df_1 }}
UNION ALL
SELECT 2 AS uuid

transformer: dynamic child

@transformer
def transform(data, *args, **kwargs):
    return data

When this pipeline is triggered, the following block runs will be created:

                              [data_loader]
                                    ↓         ↓
                [dynamic_sql_loader:0]     [dynamic_sql_loader:1]
                  ↓                ↓         ↓                ↓
[transformer:0:0]  [transformer:0:1]   [transformer:1:0]  [transformer:1:1]

How it works

Check three separate boundaries: input reading, downstream dependencies and final collection.

Dynamic Blocks v2 documents generator outputs. A generator can emit items over time, but yielding after a whole-file read cannot remove the memory already needed by that read. Incremental input depends on the actual reader and file format; dynamic blocks alone do not establish it.

Dynamic Blocks v2 documents optional Stream mode for progression between stages. A child still has to satisfy its normal/static and generated-child dependency requirements. Enabling Stream mode is not a guarantee that any child can start immediately.

Two prerequisite positions feed a joined step; one holds a violet piece and the other is empty.
In this two-prerequisite sketch, one input is ready and the other is not. Optional Stream mode still respects the child’s required dependencies; one ready item alone does not make the child runnable.

Reduce combines outputs from dynamically created blocks. If the collection holds every result together, it can create another large memory boundary. Choose the output shape deliberately rather than assuming fan-out removes the final collection cost.

Three separate violet output pieces converge into one ivory collection frame that holds all three intact.
Reduce can gather child outputs into one result. If the collector holds those outputs together, that step can create another memory boundary; fan-out alone does not establish bounded end-to-end memory.

Concurrency also depends on executor resources and available capacity. More generated tasks do not by themselves establish lower infrastructure cost, lower peak memory or a faster delivery deadline.

Before scaling, run a small test with two work items of deliberately unequal duration. Declare the dependencies and collection step, then inspect downstream start order and the completeness of both individual and combined outputs. Treat this as an evaluation to run in your environment; no measured result is established here.

The retained tutorial describes dynamic SQL and Python children. Use the version-specific documentation when choosing generator and progression behavior.

Why it matters

Choose the boundary that matches the constraint you can observe:

  • First read does not fit: inspect whether the reader can produce bounded input before dataframe construction.
  • One work item should move forward before another finishes: inspect Stream mode and all downstream dependencies.
  • Many children fit but their combined result does not: inspect the reduce or collection step.
  • The complete input fits and processing is simple: retaining the in-memory path may be the better tradeoff.

The October 31, 2024 Azure transfer article illustrates the first case: it downloads a complete blob, constructs a dataframe, then splits it later. That inspected example does not establish the behavior of every current Mage connector.

Use the documented mechanism to choose a representative evaluation. Measured memory, throughput and cost depend on your workload and environment; this page does not establish a universal improvement.

Further reading

AuthorsMage Team