This page is meant as a template for writing a FLIP. To create a FLIP choose Tools->Copy on this page and modify with your content and replace the heading with the next FLIP number and a description of your issue. Replace anything in italics with your own description.

Document the state by adding a label to the FLIP page with one of "discussion", "accepted", "released", "rejected".

Motivation

Flink has grown into a powerful data engine with multi-layer APIs including SQL, Table, DataStream, and provides event time, windowing, stateful operators, backpressure, checkpointing and end-to-end consistency semantics. It is suitable for long-running real-time feature engineering, complex event processing, streaming ETL and stateful computation, yet its native runtime has limited capabilities in scheduling heterogeneous resources such as GPUs, supporting the Python AI ecosystem, and accommodating model inference/training workloads.

Ray is a Python-native distributed runtime with flexible resource scheduling capabilities, which natively supports CPU, GPU, and other heterogeneous resources. Components such as Ray Train, Tune, Serve, and Data cover different AI scenarios, from training, inference, data processing, to hyperparameter search, but Ray Core and Ray Data are not full-fledged stream processing engines, lacking the necessary streaming semantics that Flink provides.

A common setup for real-time AI workflow is to use two separate clusters: a Flink cluster for real-time data ingestion, cleaning, and feature engineering; another Ray cluster taking charge of model inference and training. The two clusters are interconnected via RPC, Kafka or object storage, which leads to fragmented resource pools, dual-cluster maintenance overhead, and extra I/O serialization cost.

We propose Flink on Ray to allow seamless interopearability between Flink and Ray in a series of two FLIPs and this flip will focus on part-one:

  1. Support Flink on Ray, which allows Flink application jobs to run directly on a Ray cluster. Flink remains responsible for the job graph, scheduling tasks, state & checkpoints, and shuffle. Ray is responsible for the lifecycle of JobManager / TaskManager Actors, CPU / GPU resource allocation and node selection.

  2. Support interoperability with Ray ecosystem, allowing conversion from Flink dataframe/datatream/table to/from Ray Dataset.

Goals

  • Support running Flink jobs (of any API) on Ray in Application/Session mode.

  • Implement RayResourceManagerDriver to translate Flink ResourceManager worker requests into Ray Actor creation, release, and status queries.

  • Support TaskManager-level CPU, memory, and GPU resource declarations, and propagate GPU visibility to Python UDF.

  • Preserve Flink RPC, Netty Shuffle, checkpointing, failover, and slot management mechanisms to minimize intrusion into Flink's execution kernel.

Non-Goals

  • This FLIP does not rewrite the Flink Scheduler, TaskExecutor, CheckpointCoordinator, or Netty Shuffle.

  • This FLIP does not require Ray to be responsible for Flink's event time, watermarks, state backend, or exactly-once semantics.

  • This FLIP does not define a data fusion API between Flink and Ray Data; that part will be covered by the next “PyFlink with Ray” FLIP.

  • This FLIP does not require all Flink operators to use GPUs at fine granularity. The first phase focuses on TaskManager-level resource boundaries.

Proposed Changes

The core design follows the path used by RayDP (Spark on Ray): integrating Ray through the native framework's ClusterManager SPI, mapping the framework master / executor to Ray Actors while preserving the framework's internal communication protocol. Flink on Ray will implement RayResourceManagerDriver and map the Flink JobManager and TaskManager to Ray Actors. Ray is responsible only for process-level resource scheduling and Actor lifecycle management.

Flink Component

Ray Mapping

Responsibility Boundary

JobManager

RayJobManager Actor

Preserves the responsibilities of Flink Jobmanager.

TaskManager

RayTaskManager Actor

Starts the TaskExecutor JVM inside the Actor and registers it with the JobManager.

Task Slot

Flink internal slot

Ray is unaware of slots; the number of slots is determined by taskmanager.numberOfTaskSlots.

Shuffle

Flink Netty Shuffle

Data exchange between TaskManagers does not go through the Ray Object Store.

Flink jobs can be submitted to an existing Ray cluster, or directly launch a ray job cluster that is torn down when the flink job is terminated.

  1. Start a ray cluster, then submit the flink job to it.

  2. Ray GCS Actor Manager starts JobManager actor in worker node when it receives a flink job submittion.

  3. The RayResourceManagerDriver in the JobManager calculates the number and resource profile of TaskManagers and requests them from the GCS.

  4. Ray GCS Actor Manager starts the TaskManagers, which register themselves with the JobManager after being started.

  5. Task deployment, checkpointing, state recovery, and shuffle still follow Flink's native execution path.

The Ray Java API is still experimental and requires the Java-side version to strictly match the Ray Python version. To avoid requiring Flink to publish a separate Maven artifact for each Ray Python version, we'll operate the Ray cluster through the Ray Python API and reusing the Py4J communication mechanism already used by PyFlink.

The RayJobManager Actor starts the Flink ClusterEntrypoint JVM, and the JVM embeds a Py4J GatewayServer. The Python Driver obtains a FlinkClusterJavaBridge reference through Py4J to submit jobs, query status, and adjust resources. When RayResourceManagerDriver needs to call the Python-side Ray API, it completes Actor creation, release, and status queries through this bridge layer.

1. Lifecycle binding between Actors and Flink JobManager and TaskManager JVM processes

  • When the JobManager/TaskManager Process exits, its associated JobManager/TaskManager Actor also exits directly
  • When the JobManager/TaskManager Actor exits, its associated JobManager/TaskManager Process also exits

2. Automatic restart of the JobManager Actor and JobManager process. 

  • If the JobManager Actor exits due to abnormal conditions or other reasons, Ray automatically restarts it;
  • Then the JobManager Actor launches the JobManager process and executes the Flink leader election flow.

 3. TaskManager Actor and TaskManager process provisioning

  • After the TaskManager Actor and its process exit, the Flink ResourceManager requests a new TaskManager Actor from the Ray cluster
  • Once the new TaskManager Actor starts, it launches the TaskManager Process and re-registers it with the JobManager Process

4. Actor naming and cluster terimination

  • A unique cluster ID is required, and all actors are created under the "flink-{cluster-id}" namespace and named in the format of "flink-{cluster-id}-jobmanager/taskmanager-{worker-id}"
  • On cluster termination, all actors under the "flink-{cluster-id}" namespace will be cleaned

Flink Request / Configuration

Ray Operation

Description

Worker ResourceProfile

ActorClass.options(num_cpus=N, memory=M, num_gpus=G).remote()

CPU, memory, and extended resources like GPU in the ResourceProfile are mapped to Ray Actor options.

Release Worker

ray.kill(actor)

Releases the TaskManager Actor and reclaims the corresponding placement group bundle.

Worker Status Query

Ray Actor heartbeat and GCS status

RayResourceManagerDriver must reconcile the result with Flink heartbeat status.

taskmanager.numberOfTaskSlots

No direct mapping

Ray only manages TaskManager process resources; slots are still partitioned inside the Flink JVM.

GPU extended resource

num_gpus=G

Ray sets CUDA_VISIBLE_DEVICES, and the TaskManager then propagates it to the Python worker. In the initial version, GPU allocation and visibility are defined at the TaskManager actor level and that no additional slot- or UDF-level isolation is provided.

Flink checkpointing and Ray Actor failure are two independent layers. The boundary principle is that Ray is responsible for whether Actors exist, while Flink is responsible for semantic recovery of jobs.

Fault Scenarios

Detector

Recovery Operations

JobManager Process failure

JobManager Actor

  1. JobManager Actor exits automatically
  2. Ray restarts JobManager Actor
  3. JobManager Actor launches JobManager JVM
  4. Wait for existing TaskManager to reconnect and then recover from last completed checkpoint (requiring JM HA to be setup, it's not part of the goal of this FLIP to implement a native Ray HA mode)

JobManager Actor failure

Ray GCS and JobManager JVM

  1. JobManager JVM exits automatically
  2. JobManager Actor will exit when JobManager JVM exits
  3. Ray restarts JobManager Actor
  4. JobManager Actor launches JobManager JVM
  5. Wait for existing TaskManager to reconnect and then recover from last completed checkpoint (requiring JM HA to be setup, it's not part of the goal of this FLIP to implement a native Ray HA mode)

TaskManager Process failure

TaskManager Actor & Flink heartbeat

  1. TaskManager Actor exits automatically
  2. JobManager detects that a TaskManager has exited, it requests a new TaskManager Actor
  3. TaskManager Actor starts the TaskManager, which re-registers with the JobManager
  4. JobManager wait for the TaskManager then recover.

TaskManager Actor failure

Flink heartbeat

  1. TaskManager JVM exits automatically
  2. JobManager detects that a TaskManager has exited, it requests a new TaskManager Actor
  3. TaskManager Actor then starts the TaskManager, which re-registers with the JobManager
  4. JobManager wait for the TaskManager then recover

Python Worker failure

TaskManager JVM

  1. The Beam Runner or PyFlink runtime rebuilds the Python subprocess;
  2. The TaskManager Actor is not automatically restarted due to this failure.

Ray GCS failure

Ray cluster

Preferentially rely on Ray GCS fault tolerance; when recovery is not possible, Flink resubmits the job via savepoint or checkpoint.

  1. The Ray cluster starts and forms one Head node and N Worker nodes.

  2. A Python Driver or submission entry point calls flink_on_ray.init() to create a RayJobManager Actor.

  3. The RayJobManager Actor starts the Flink ClusterEntrypoint JVM, which initializes the Dispatcher, JobMaster, RayResourceManagerDriver, and RPC endpoint.

  4. Each RayTaskManager Actor starts the TaskExecutor JVM on its node and registers with the JobManager.

  5. Task deployment, checkpointing, state recovery, and shuffle still follow Flink's native execution path.

For the initial implementation, two options will be supported: JARs pre-provisioned in the execution environment, referenced through local:///..., and JARs already available through a configured Flink filesystem. The Ray application entrypoint would reuse Flink’s artifact-fetching infrastructure to resolve the application JAR and additional JARs specified through user.artifacts.artifact-list before loading the application.

Additional JARs would be made available to the application classloader and explicitly registered as job dependencies for distribution to TaskManagers through Flink’s existing Blob services. Dependencies required in Flink’s lib/ or plugins/ directories, including filesystem plugins needed for artifact fetching, would remain prerequisites of the execution environment.

To keep the initial scope bounded, client-local artifacts would need to be uploaded or pre-provisioned by the user. Automatic client-side upload and a dedicated integration with Ray’s runtime_env.working_dir would be deferred.

These interfaces are internal contracts between the Python driver, Ray Actors, and Flink ResourceManager. The Java-side ResourceManager integration follows Flink's ResourceManagerDriver shape; the Ray Actor methods in pyflink.ray keep Python snake_case naming and do not duplicate Flink slot, heartbeat, or checkpoint semantics.

RayJobManagerActor is created by flink_on_ray.init(...). CPU and memory are passed through Ray Actor options, not through the Actor constructor.

@ray.remote
class RayJobManagerActor:
    def __init__(
        self,
        app_name: str,
        flink_conf: dict[str, str],
    ):
        ...

    def start(self) -> dict[str, str]:
        """Start ClusterEntrypoint JVM and return RPC, REST, and Py4J endpoints."""
        ...

    def get_cluster_info(self) -> dict[str, str]:
        """Return JobManager RPC address, REST endpoint, and Py4J gateway endpoint."""
        ...

    def stop(self) -> None:
        """Stop the JobManager JVM and exit the Actor."""
        ...

RayTaskManagerActor wraps one TaskExecutor JVM.

@ray.remote
class RayTaskManagerActor:
    def __init__(
        self,
        app_name: str,
        flink_conf: dict[str, str],
    ):
        ...

    def start(self) -> dict[str, str]:
        """Start TaskExecutor JVM and return ResourceID / TaskManager metadata."""
        ...

    def get_status(self) -> dict[str, str]:
        """Return process liveness and Ray-visible resource assignment."""
        ...

    def stop(self) -> None:
        """Stop the TaskExecutor JVM and exit the Actor."""
        ...

RayResourceManagerDriver lives inside the JobManager JVM and follows Flink's active ResourceManagerDriver contract.

final class RayResourceManagerDriver
        extends AbstractResourceManagerDriver<RayWorkerNode> {

    RayResourceManagerDriver(
            Configuration flinkConfig,
            Configuration flinkClientConfig) {
        super(flinkConfig, flinkClientConfig);
        ...
    }

    @Override
    protected void initializeInternal() throws Exception;

    @Override
    public CompletableFuture<RayWorkerNode> requestResource(
            TaskExecutorProcessSpec taskExecutorProcessSpec);

    @Override
    public void releaseResource(RayWorkerNode worker);

    @Override
    public void deregisterApplication(
            ApplicationStatus finalStatus,
            @Nullable String optionalDiagnostics) throws Exception;

    @Override
    public void terminate() throws Exception;
}

RayWorkerNode is the Flink-side handle for one RayTaskManagerActor and implements ResourceIDRetrievable so the active resource manager can track it in the same way as YarnWorkerNode or KubernetesWorkerNode.

public class RayWorkerNode implements ResourceIDRetrievable {
    private final ResourceID resourceId;

    @Override
    public ResourceID getResourceID();
}

Public Interfaces

A new Python subpackage under PyFlink, named "pyflink.ray" will be introduced to bootstrap Flink clusters on Ray. Users can directly write their PyFlink jobs and deploy them on Ray without any change.

import os
import json
import ray
import pyflink.ray as flinkray
import onnxruntime as ort

from pyflink.common import Configuration
from pyflink.common.typeinfo import Types
from pyflink.datastream import StreamExecutionEnvironment
from pyflink.datastream.functions import MapFunction

class GpuInferenceMap(MapFunction):
    def open(self, runtime_context):
        # There are 2 ways to get gpu binding to python worker, the specific approach depends on implementation in PyFlink.
        # 1. Ray will set CUDA_VISIBLE_DEVICES to TaskManagerActor, then it convert to external resource to TaskManager JVM
        gpu_infos = runtime_context.get_external_resource_infos("gpu")
        gpu_indices = [
            info.get_property("index")
            for info in gpu_infos
            if info.get_property("index") is not None
        ]
        # 2. Ray expose the GPU assigned to the TaskManager Actor, then actor can set them to TaskManager JVM and Python worker.
        # cuda_devices = os.environ.get("CUDA_VISIBLE_DEVICES", "")

        providers = ort.get_available_providers()
        self.session = ort.InferenceSession(
            "/data/model.onnx",
            providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
        )

    def map(self, value: str):
        # Replace this part with real preprocessing and inference input.
        result = self.session.run(None, {"input": value})
        return json.dumps({"input": value, "result": str(result)})

@serve.deployment(num_replicas=2, ray_actor_options={"num_cpus": 0.2, "num_gpus": 1.0})
class ClipEmbeddedingServe:
    def __init__(self):
    
    def tranform(self, video_uris: pyarrow.Array) -> pyarrow.Array:
        return embedding


class RayServeInferenceMap(MapFunction):
    def open(self, runtime_context):
        ray.init()
        self._handle = serve.get_deployment_handle("ClipEmbeddedingModel", app_name="CLIP_embeddeding")

    def map(self, value: str):
        return json.dumps({"input": value, "result": str(result)})


def run_pyflink_job():
    env = StreamExecutionEnvironment.get_execution_environment()

    config = Configuration()
    config.set_string("python.execution-mode", "thread")
    env.configure(config)
    env.set_parallelism(4)

    ds = env.from_collection([......], type_info=Types.STRING(),)
    ds.map(GpuInferenceMap(), output_type=Types.STRING()).print()
    env.execute("simple-pyflink-ray-gpu")


if __name__ == "__main__":
    # Init conenction to Ray
    ray.init(address="auto")
    
    # Init a Ray Serve for model serving
    serve.run(ClipEmbeddedingServe, name="CLIP_embeddeding")

    # Init a Flink cluster, reuse an existing Ray context. If none exists, it would connect to an existing cluster using the supplied address, defaulting to address="auto" 
    flink = flinkray.init_flink(
        app_name="simple-pyflink-ray-gpu",
        jm_cores=1,
        jm_mem="4g",
        tm_cores=4,
        tm_mem="16g",
        tm_gpus=1,     # Ray will set CUDA_VISIBLE_DEVICES to TaskManagerActor, then it convert to external-resource.gpu.amount for TaskManager JVM
        tm_slots=1,
        flink_conf={ "env.PYTHONUNBUFFERED": "1" },
    )

    # Submit a Flink job
    flink.submit(run_pyflink_job)
    
    # Shutdown the Flink cluster inside Ray
    flink.stop()

    # Shutdown Ray
    ray.shutdown()

SQL & DataStream jobs are packaged into a Jar, they can be submitted directly from the command line as Flink jobs and run on Ray cluster.

./bin/flink run -t ray-application -Dray.address=<flink-cluster-address> flink-streaming-job.jar

Compatibility, Deprecation, and Migration Plan

This capability is provided as a new deployment target and a new ResourceManagerDriver. It does not change existing Kubernetes, YARN, Standalone, or local deployment modes. Existing Flink jobs do not need to migrate; only jobs that choose ray-application or the corresponding Python bootstrap API enter the Ray backend.

The existing SlotSharingGroup and external resource mechanisms in the DataStream API can continue to be used. SQL / Table API expression of operator-level GPU resources is still limited by current Flink capabilities. In the first phase, coarse-grained heterogeneous resources can be supported through TaskManager-level GPU configuration; later phases can extend fine-grained resource requirements in combination with the Python DataFrame API or UDF decorators.

Test Plan

  • Unit tests cover the mapping from ResourceProfile to Ray Actor options, including CPU, memory, GPU, and custom resources.

  • Integration tests submit SQL, DataStream, and PyFlink jobs in local Ray and KubeRay environments to validate JobManager / TaskManager registration and task execution.

  • Fault injection tests cover TaskManager Actor kill, Python worker kill, JobManager restart, and temporary Ray GCS unavailability.

  • Consistency tests use checkpoints and exactly-once sinks to verify that state and offsets can recover correctly after a TaskManager Actor failure.

Rejected Alternatives

This option preserves a single runtime and has a simpler architecture. However, Kubernetes only provides container-level GPU scheduling and lacks interoperability with Ray's AI ecosystem: Ray Serve / Train / Data. For scenarios that need to run real-time stream processing and GPU inference at the same time, a separate Ray or MaaS cluster still needs to be maintained.

This option avoids introducing the Flink runtime, but it would require reimplementing watermarks, windows, stateful operators, checkpointing, backpressure, and exactly-once on Ray. In the short term, it would be difficult to reach Flink's maturity in production stream processing scenarios.

This option avoids running the jobmanager on Ray and deal with various HA issues while still benefits from Ray's ecosystem, but it would still involve a dual cluster setting and users need to manage two separate resource pools.