Skip to content

airflow.providers.apache.kafka ConsumeFromTopicOperator cannot be used for pipelining because it returns None. #56494

Closed

Description

Description

As of Airflow 3.0.6, the ConsumeFromTopicOperator takes the name+path to a function and applies it to all messages in a batch, but the results of this function call are discarded and the method returns None. Rather than dropping the result of the apply_function, the results of the apply_function could be accumulated and returned so that other tasks could use the results.

Use case/motivation

It would be nice to be able to pipeline operators and functions like we can with other Python tasks and other Operators. An example:

def my_service_prefilter(message):
    # This will get messages from my-topic-1 and my-topic-2.  We will extract and return some dicts.
    if message and message.value():
        decoded = json.loads(message.value().decode("utf-8")
        if decoded['some_value']:
            return decoded
    return None

@task.python
def handle_batch(decoded_items: list[dict]):
    for item in decoded_items:
        if item:
            do_something_with_item(item)

message_batch = ConsumeFromTopicOperator(
    task_id="consume_pending_kafka_messages",
    topics=["my-topic-1", "my-topic-2", ],
    apply_function="my_service.prefilter_function",
)

message_batch >> handle_batch

Written differently:

Kafka message stream -> ConsumeFromTopicOperator -> [message returned by the apply_function * batch size] -> whatever downstream task.

I initially wrote this as a bug report after spending a while with a colleague who had treated the ConsumeFromTopicOperator like other operators, but realized that returning None is the intended behavior.

I recognize that the Airflow documentation explicitly states that Airflow is not made to be used in the streaming data sense, but in this case if we need to transform some data and distribute it to other tasks we need to build our own operators instead of just reusing the existing Operators. The Operator documentation seems to suggest that Operators be composable.

Related issues

No response

Are you willing to submit a PR?

  • Yes I am willing to submit a PR!

Code of Conduct

Activity

  1. added
    kind:feature
    needs-triage
    on Oct 9, 2025
  2. boring-cyborg commented on Oct 9, 2025

    @boring-cyborg

    Thanks for opening your first issue here! Be sure to follow the issue template! If you are willing to raise PR to address this issue please do so, no need to wait for approval.

  3. jroachgolf84 commented on Oct 9, 2025

    @jroachgolf84
    Collaborator

    @JosephCatrambone-Gridware, thanks for opening this issue. Can you tell me a little bit more about the use-case? This might be a perfect scenario for event-driven scheduling using Assets and AssetWatchers!

  4. JosephCatrambone-Gridware commented on Oct 9, 2025

    @JosephCatrambone-Gridware
    Author

    Certainly. We had a ConsumeFromTopicOperator which was gathering messages from a bunch of Kafka topics, dropping some irrelevant ones, then processing them en-masse to take advantage of bulk-parallel processing, and pushing the resultant list of N elements to the next task downstream.

    The structure looked very similar to the elements in the first message:

    message_batch = ConsumeFromTopicOperator(
        task_id=config.KAFKA_FILTER_ACCUMULATE_TID,
        topics=[config.LISTENER_TOPIC,],
        apply_function="filter_accumulate_process",
    )
    
    message_batch >> postprocess_batch
    

    We were trying to hack our way around this with

    def filter_accumulate_process(message, ti):
        ...
        ti.xcom_push(key='results', value=[... filtered and accumulated messages ...])
    
    message_batch = ConsumeFromTopicOperator(
        task_id=config.KAFKA_FILTER_ACCUMULATE_TID,
        topics=[config.LISTENER_TOPIC,],
        apply_function="filter_accumulate_process",
        apply_function_kwargs={'ti': '{{ti}}'},
    )
    

    but it seems like it would be a straightforward change to the ConsumerFromTopicOperator to just do a gather of the resulting values and return that list or empty.

    Looking at the AssetWatchers and Asset it feels like those might possibly be a good fit, though I'd need to investigate more. I think I remember trying them early-on but had an issue with things not triggering when items were added to the Kafka queue. Perhaps it's worth revisiting.

  5. JosephCatrambone-Gridware commented on Oct 14, 2025

    @JosephCatrambone-Gridware
    Author

    Another use case that is not possible with the ConsumeFromTopicOperator:

       pending_events = ConsumeFromTopicOperator(task_id='gather_pending_events', ...) # Listens to KafkaTopic and schedules future events.
    
        ops = TriggerDagRunOperator.partial(
            task_id=JOB_CREATION_TASK_ID,
            trigger_dag_id=JOB_CREATION_DAG_ID
        ).expand(conf=pending_events)
    
  6. jroachgolf84 commented on Oct 15, 2025

    @jroachgolf84
    Collaborator

    I think that this is the perfect use-case for event driven scheduling. We have some basic support for this functionality with Kafka (https://airflow.apache.org/docs/apache-airflow-providers-apache-kafka/stable/message-queues/index.html). If this doesn't meet your needs, this is a great opportunity for a significant contribution to the project.

  7. added
    AIP-82
    and removed
    needs-triage
    on Oct 15, 2025
  8. JosephCatrambone-Gridware commented on Oct 23, 2025

    @JosephCatrambone-Gridware
    Author

    Thanks for the reply. On a similar note, it appears as though the ProduceToTopicOperator doesn't have a way to take any input from other tasks in the graph. One can provide a function to the method, but if we have, say, an existing batch of tasks which produce a list of dicts then the following isn't possible:

    with DAG(...) as dag:
        @task.python
        def my_sample_producer():
            return [{"key": "foo", "value":"..."}, {"key": "..."}, ...]
    
        prod = ProduceToTopicOperator(
            topic=OUTPUT_TOPIC,
            producer_function=this_method_will_be_called_but_we_cant_read_from_other_tasks,
        )
    
        my_sample_producers() >> prod  # This will not work because the prod operator can't access any context or input.

    I feel like it still makes sense from an admittedly fuzzy aesthetics/composability perspective for Operators to be able to accept and/or produce data from tasks, but I can respect not wanting to have two ways to accomplish this.

    A small code change which injects the context into the function before it's called looks like it would resolve this.

    class ProduceToTopicOperator(BaseOperator):
        ...
        def execute(self, context) -> None:
            self.kwargs['context'] = context  # New line.  Obviously with more nuance, like checking if context is present, etc.
            ...

    I don't trust myself enough to understand all the repercussions of these kinds of changes, but if it's as simple as it looks (it probably isn't) then it would add a lot of functionality for a small number of code changes.

    Update: I forgot that get_current_context() is an option and might do precisely what's needed in this context. Will look into it and report back.

    Update 2: get_current_context() allows us to write a wrapper function that works quite nicely and makes ProduceToTopicOperator usable!

    def my_generator():
        return [ ["foo", "bar"], ["baz", "bum"], ["my kafka key", "my kafka value"] ]
    
    def map_to_kafka_producer():
        ctx = get_current_context()
        data = ctx['task_instance'].xcom_pull(task_ids=["my_producer",], key="return_value")[0]
        for row in data:
            yield row[0], row[1:]
    
    with DAG(
        dag_id="my_dag",
        schedule="@daily",
    ) as fetch_annotations:
        generate_data = PythonOperator(
            task_id="my_producer", # Don't update without changing the map_to_kafka producer.
            python_callable=my_generator
        )
    
        kafka_out = ProduceToTopicOperator(
            topic=OUTPUT_TOPIC,
            producer_function=map_to_kafka_producer
        )
    
        generate_data >> kafka_out

    I feel like there are some ergonomic tweaks that could make get_current_context or, better yet, the entire map_to_kafka_producer function, unnecessary, but as it is I'm satisfied.

  9. added a commit that references this issue on Aug 12, 2026
    cf23900
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    AIP-82area:providerskind:bugkind:featureprovider:apache-kafka

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions