I’m running into some weird behaviour I can’t full...
# troubleshooting
h
I’m running into some weird behaviour I can’t fully place (yet), really hope someone can point me in the right direction here 🙂 We’re using PyFlink together with Kafka. For some parts of our pipeline, we need more low-level control, so we have a KeyedProcessFunction to do the heavy lifting. The function itself is quite simple: it carries the latest state (two strings), and based on the difference with the current state it either generates a new SessionId or returns the current active SessionId. Doing similar operations with the table api is super performant - a single task easily keeps up with a single kafka partition at something like 99% idle. Now for the weird part: when using the KeyedProcessFunction, kafka is suddenly backpressured (50%-90%, so quite significantly). The process is not CPU nor memory constrained (running this on an otherwise idle box with 32 cores and 128GB ram). When I don’t change the logic at all, but I just change the
key_by
from
key_by(lambda x: x['PrimaryKey'])
to
key_by(lambda x: 1)
I get full performance back (no backpressure, 99% idle) so I don’t think it’s the process function itself that is slow. Trying
key_by(lambda x: random.randint(0, n))
where I’ve played with n, I found that for small n (<10) the system works well, but for larger n (100, 1M, etc) performance degrades. Increasing the parallelism helps a little, but I’d like to understand why the system performs the way it does - I feel like I have configured something incorrectly, somewhere. Any pointers? 🙂 Thanks! edit: flink 1.18, java 17, confluent kafka, flink is running on single bare-metal server
y
From what you’re saying, it seems that there’s a problem with shuffling of the data, as when you have a smaller keyBy it means less nodes that need to communicate and potentially more data that gets sent to each node. 1. What is the size of your cluster? 2. Have you tried looking at the Flinks FlameGraph, to see where the keyBy is spending most if it’s time?
h
Yeah that’s what I figured, too. Unfortunately the problem also exists with a parallelism of 1. I’m running this on a single server for now, so the cluster size is 1 :) The flame graph doesn’t really look like a flame graph for me, it’s just a single block, and all time is spent in unsafe.park, I see references to mailbox and the beam python runner further down…. So all in all quite unhelpful
y
Can you capture a screenshot and paste it here?
h
the graph looks like this (although a simple
.print()
shows the same performance):
y
@Huib According to the flame graph it seems to be waiting for element to process (the LinkedBlockingQueue is blocking the execution waiting for elements)
If you have parallelism of 1 with a single taskmanager, and you’re creating 1 million keys, it means that your single TaskManager has to deal with more processor function states
As you lower your key cardinality, less state needs to be opened, created and managed
h
Makes sense so far. I’m using the memory backend so i expected to be able to handle a few thousand keys at least - the performance drop is already clearly visible at hundreds of keys
Basically I’d expect memory to run out before performance becomes an issue, is this not the case?
y
How much memory are you allocating to this node? It could be GC pressure starting to accumulate
h
It has 128gb ram, I’m giving 16 to the task and 16 to the job managers
y
If it’s a bare-metals server, try SSHing to the node and seeing how much memory the taskmanager is consuming
BTW, one more thing to look at is buffering of elements: https://nightlies.apache.org/flink/flink-docs-release-1.18/docs/dev/datastream/overview/#controlling-latency. Since we’re shuffling a lot of keys, could be lots of SerDe going on that’s also slowing you down
h
memory pressure is super low
What kind of changes should I make to test that idea? I dont think there’s a lot of network traffic going on, with everything being on the same node?
y
I think there would still be SerDe during the boundary of the subtasks executing. What happens when you increase parallelism? Allowing more threads to process the keys
h
with more threads things get a little better, but there’s still backpressure
and the difference between this and having 10-ish keys is striking
y
But it make sense: the less keys you have, the less state you need to manage, less initialization work, etc.
h
sure, but we’re not pushing millions of events a second here - this is order of magnitude 10k/s
with thousands of keys it drops to 1k/s
I hope we can serialize strings quicker than that 😉
y
That’s fair. But this isn’t a typical scenario though. You’d usually be reading in parallel from Kafka, processing data with multiple task managers, etc. If this is a test to see how much you can squeeze out of a single TM it doesn’t make sense to cap it at 1 thread?
h
I like to understand what is expensive about this operation, and if there are ways around it. Scaling up is one, but needing a core per 1kr/s is so much less then I’d expect that it feels like something is wrong… Especially considering benchmarks like:
Flink achieves a sustained throughput of 1.5 million elements per second per core for the grep job.
https://www.ververica.com/blog/high-throughput-low-latency-and-exactly-once-stream-processing-with-apache-flink
Also, I really, really, really do appreciate you taking the time to check this stuf with me, thank you!
👍 1
y
Well, that’s a catch-all benchmark with no specific insights 🙂, not sure I would build expectations around it, but I agree 1K/s isn’t great. If you dismiss the keyBy, I assume throughput increases significantly. Have you gave it a test just for plain old reading from Kafka print to STDOUT?
h
Yeah, kafka print to stdout is basically idle, waiting for data to arrive
At roughly 10k/s, but that is purely because I’m reading with a single consumer from a single partition. Adding some complexity to the mix in the form of chained
over window
aggregates - emulating the logic of the processFunction doesn’t really change the dynamic. All operators are idling processing the stream of messages coming from Kafka. No backpressure.
(it’s not a sustainable query, because it runs out of memory quicker than state can be dropped, but still) Based on the amount of state a query like this has to keep, I didn’t expect the difference to be as large as it is
Another example: This join on the right side has to keep state of both the left and the right side, and is expected to key off individual events, not the asset generating the events - and it’s (again) pretty much idle, even though I expect it to hold orders of magnitude more keys…
y
Right, the Join is idle because previous operators are processing in high utilization and backpressuring the Kafka source
h
even if I reduce the bottleneck, it’s still the case
y
Anyway, I don't think it's likely that you'll grep performance with what you're attempting here. I would go for a realistic test in a cluster setup with the expected parallelism
Is your code properly emitting the elements downstream from the keyBy?
h
you mean if the end result is what I’d expect? yes
Could I be doing something incredibly stupid that causes this to be super slow but somehow work, absolutely 😉
Copy code
from uuid import uuid4
from pyflink.common import Row
from pyflink.datastream.functions import KeyedProcessFunction
from pyflink.datastream.state import ValueStateDescriptor
from pyflink.common.typeinfo import Types

class ChargeSessionProcessFunction(KeyedProcessFunction):
    def __init__(self):
        self.chargeState = ""
        self.sessionIdState = ""

    def open(self, runtime_context):
        # Define and initialize state for chargeState and sessionId
        self.chargeState = runtime_context.get_state(ValueStateDescriptor("chargeState", Types.STRING()))
        self.sessionIdState = runtime_context.get_state(ValueStateDescriptor("sessionId", Types.STRING()))

    def process_element(self, value, ctx):
        # Access the state for the current vehicle
        charge_state = self.chargeState.value()
        session_id = self.sessionIdState.value()

        # Check for state transition
        if value.ChargeStateString != charge_state:
            if charge_state == 'Disconnected' or not charge_state:
                # Generate new sessionId
                session_id = str(uuid4())
                self.sessionIdState.update(session_id)
                self.chargeState.update(value.ChargeStateString)
            elif value.ChargeStateString == 'Disconnected':
                # End the session after this record
                self.sessionIdState.clear()
                self.chargeState.clear()

        return [Row(
            telemetry_id=value.TelemetryId,
            SessionId=session_id or None
        )]
and then:
Copy code
telemetry_with_sessionid = (
    telemetry_stream
    .key_by(lambda x: x['VehicleId'])
    .process(
        ChargeSessionProcessFunction(),
        output_type=RowTypeInfo([Types.STRING(), Types.STRING()], ['telemetry_id', 'SessionId'])
    )
    .set_parallelism(10)
)
It’s not a pipeline where we expect millions of events per second, tbh, so testing with only a few parallel threads is a realistic production scenario here 😉
y
Could it be that your records are not sending a Disconnected event which should trigger writing the state downstream?
h
Copy code
jobmanager_1   | | +I |                   Disconnected |
jobmanager_1   | | +I |                   Disconnected |
jobmanager_1   | | +I |                   Disconnected |
jobmanager_1   | | +I |                   Disconnected |
jobmanager_1   | | +I |                   Disconnected |
jobmanager_1   | | +I |                   Disconnected |
jobmanager_1   | | +I |                   Disconnected |
jobmanager_1   | | +I |                   Disconnected |
jobmanager_1   | | +I |                   Disconnected |
jobmanager_1   | | +I |                   Disconnected |
jobmanager_1   | | +I |                   Disconnected |
jobmanager_1   | | +I |                   Disconnected |
jobmanager_1   | | +I |                   Disconnected |
jobmanager_1   | | +I |                   Disconnected |
jobmanager_1   | | +I |                       Complete |
jobmanager_1   | | +I |                   Disconnected |
jobmanager_1   | | +I |                   Disconnected |
jobmanager_1   | | +I |                   Disconnected |
jobmanager_1   | | +I |                   Disconnected |
jobmanager_1   | | +I |                   Disconnected |
jobmanager_1   | | +I |                   Disconnected |
jobmanager_1   | | +I |                   Disconnected |
jobmanager_1   | | +I |                   Disconnected |
jobmanager_1   | | +I |                   Disconnected |
jobmanager_1   | | +I |                   Disconnected |
jobmanager_1   | | +I |                   Disconnected |
jobmanager_1   | | +I |                   Disconnected |
But let me double check by pushing the return into the if statement
Yup, when I only emit an event after clearing the state, I am still emitting
so there’s no rogue spaces (” Disconnected”) or anything like that
y
What happens if you always emit? Does it change what you're seeing? Just for the test
h
always emit or always clear the state?
the original code would always emit, so yeah, that doesn;t change much… If I clear the state after every message, nothing changes either - still heavy backpressure
👍🏻 1