DUE TO SPAM, SIGN-UP IS DISABLED. Goto Selfserve wiki signup and request an account.
Current state: Under Discussion
Discussion thread: https://lists.apache.org/thread/jd9thjoc0nztb6gzsqtcoxj94kvb3m43
JIRA: here (<- link to https://issues.apache.org/jira/browse/FLINK-XXXX)
Released: <Flink Version>
Please keep the discussion on the mailing list rather than commenting on the wiki (wiki discussions get unwieldy fast).
Motivation
Background
As noted in FLIP-577: AI-Native Flink, AI-oriented data processing workloads — such as multimodal data processing, model inference, and feature engineering — are growing rapidly in production. Compared to traditional stream processing tasks, these workloads exhibit significant differences:
Expensive Resources: They rely on expensive resources such as GPUs, which must be fully utilized to control costs.
High Initialization Cost: Loading resources like models takes seconds to minutes, making restart costs far higher than for ordinary operators.
These operators need to avoid the downtime and restart overhead caused by failures and rescaling. Current approaches fall short of addressing these needs.
Limitations of Existing Approaches
Taking GPU-based model inference as an example, we illustrate the limitations of two current approaches.
Approach 1: Embedding Inference in a UDF (e.g., ProcessFunction)
Source ──→ [ProcessFunction + GPU Model] ──→ Sink
Chained with upstream/downstream by default, same Pipelined RegionProblems:
Parallelism Coupling: The inference operator is chained with data-plane operators by default, sharing the same parallelism. Even when forcibly split into a separate JobVertex, they still belong to the same Pipelined Region, making independent scaling difficult.
Resource Waste: Although separate resources can be allocated to the inference operator, each data-plane subtask corresponds to one inference subtask, leading to low GPU utilization or excessive data-plane expansion.
Expensive Failover: Any operator failure within the same Pipelined Region triggers model reloading (typically on the order of minutes).
No Sharing: Multiple pipeline branches must each hold their own copy of the model.
Approach 2: Deploying an External Inference Service (e.g., K8s Deployment + AsyncIO Calls)
Source ──→ [AsyncIO] ──→ Sink
↕
[External Model Service] ← Independently deployed and operatedProblems:
Lifecycle Disconnect: The service is independent from the job and requires additional deployment, monitoring, and scaling infrastructure.
Operational Burden: Users must coordinate capacity planning, elastic scaling, and failure recovery across two systems (Flink + inference service).
Low Resource Efficiency: The external service requires always-on resources that cannot be released in sync with the job lifecycle.
Fragmented Development Experience: A single logical pipeline is split across two technology stacks.
RPC Operator Service: A Flink Deployment Primitive
This FLIP proposes introducing RpcOperator Service (ROS) — a deployment primitive that decouples compute units from the data-plane topology, running them as independently scheduled, independently scaled, and independently recovered RPC services.
┌─────────────────────────────┐
Source ──→ [ProcessFunction] ──→ Sink │
↕ RPC │
[RpcOperator Service] │ Same Flink framework
Independent Pipelined Region │ Unified lifecycle
Independent parallelism & resources │ Unified resource management
└─────────────────────────────┘RpcOperator is a new operator type parallel to StreamOperator — it defines the methods a service provides. This differs from client-side invocation patterns such as AsyncIO Operator; the two are complementary: data-plane operators can invoke the service provided by RpcOperator through AsyncIO or similar mechanisms.
RpcOperator runs as a standard Flink Task within an independent Pipelined Region, directly reusing Flink's existing resource scheduling and failure recovery mechanisms. Key benefits include:
Fault Isolation: An RPC service subtask failure triggers recovery only within its own Region, without affecting the data plane, and vice versa. When a single service instance fails, other instances remain unaffected and continue serving data processing.
Independent Scaling: The service and data plane can be scaled independently without disrupting each other's normal operation. When a single service instance goes online or offline, the remaining instances continue providing service with no data processing interruption.
Resource Isolation: The data plane and RPC service use separate SlotSharingGroups, enabling native scheduling of heterogeneous resources.
Flexible Load Balancing: Service instances are decoupled from data-plane operators, with requests dispatched at runtime based on actual load.
Framework-level Flow Control: Flink can obtain service status to implement smarter and more accurate flow control and load balancing.
Coordinated Auto-scaling: Resources can be scaled more intelligently based on job execution status.
Simplified Operations: The Flink framework provides unified deployment and lifecycle management, eliminating the need for cross-system coordination.
Limitations and Usage Guide
Limitations
RpcOperator currently does not provide:
State Management: No keyed state, no operator state, no checkpoint participation. In-memory instance variables can be used across requests but are not persisted — all state is lost on failure and restart.
Temporal Operations: RpcOperator does not support watermarks, timers, or windowing (neither event-time nor processing-time).
Exactly-Once Semantics: RpcOperator itself provides no deduplication or fault-tolerance guarantees.
Data plane + ROS job: At-least-once is achieved — on restore, the data plane replays in-flight requests from the last checkpoint. If idempotency is required, users must implement it themselves in the RpcOperator.
ROS-only job: No fault-tolerance guarantees — without a data plane there is no checkpoint and no input replay. Reliability depends entirely on the external caller's (typically another pipeline job) retry logic.
When to Use
ROS is only applicable to workloads that are compatible with the limitations above (no fault-tolerant state, no temporal operations, no exactly-once). Even among compatible workloads, ROS introduces RPC overhead (serialization + network round-trip) — it is recommended only when the isolation benefits clearly outweigh this cost:
High initialization cost: Resource loading (model weights, large lookup tables, connection pools) takes seconds to minutes, making restart costs unacceptable.
Heterogeneous or expensive resources: The operator requires GPU, large memory, or other resources that should be independently managed and fully utilized.
Fault isolation is critical: A failure in this operator would otherwise trigger a costly restart of the entire data pipeline, and the RPC overhead is acceptable compared to the recovery cost.
When Not to Use
ROS is a deployment primitive for decoupling expensive compute units from the data plane — it is not a general-purpose RPC framework or a replacement for any existing API (e.g. DataStream).
As a new and purposefully scoped interface, ROS currently does not support state management, temporal operations, or exactly-once semantics (see Limitations above). Any workload that requires these capabilities should use StreamOperators.
Beyond these fundamental limitations, ROS is also not recommended for Lightweight stateless operations: Simple logic with low initialization cost (e.g., map/filter/flatMap, format conversion, simple ETL transformations) — the RPC overhead may outweigh any isolation benefit.
Public Interfaces
All new interfaces are initially annotated with @Experimental and will be upgraded to @PublicEvolving once stable.
End-to-End Examples
Basic Usage
The following example demonstrates the complete usage pattern — defining an RPC service, registering it, and calling it from the data-plane pipeline:
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); // 1. Define an RPC service: extend AbstractRpcOperator, // and every public method automatically becomes an RPC method. class ModelService extends AbstractRpcOperator { private transient Model model; @Override public void open(Context ctx) throws Exception { super.open(ctx); model = Model.load("/models/bert-base"); } public String predict(String text) { return model.predict(text); } } // 2. Register the service with a RosDescriptor that specifies // parallelism and resource requirements. env.addRpcOperatorService( RosDescriptor.builder("model-svc", new ModelService()) .parallelism(4) .cpuCores(2.0) .taskHeapMemoryMB(4096) .build()); // 3. In the data-plane pipeline, obtain a RosClient by service name // and invoke RPC methods. env.fromSource(source, WatermarkStrategy.noWatermarks(), "input") .process(new ProcessFunction<String, String>() { private transient RosClient client; @Override public void open(Configuration params) { client = getRuntimeContext().getRosClient("model-svc"); } @Override public void processElement(String value, Context ctx, Collector<String> out) { String result = client.<String>request("predict", value).get(); out.collect(result); } }) .sinkTo(sink); env.execute("My Inference Job");
Asynchronous Invocation with AsyncDataStream
The following example demonstrates the recommended asynchronous pattern using Flink's AsyncDataStream, which allows multiple in-flight requests and improves throughput:
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// Register the same model service as above
env.addRpcOperatorService(
RosDescriptor.builder("model-svc", new ModelService())
.parallelism(4)
.cpuCores(2.0)
.taskHeapMemoryMB(4096)
.build());
// Use AsyncDataStream for non-blocking RPC invocation
DataStream<String> input = env.fromSource(source, WatermarkStrategy.noWatermarks(), "input");
DataStream<String> result = AsyncDataStream.unorderedWait(
input,
new RichAsyncFunction<String, String>() {
private transient RosClient client;
@Override
public void open(Configuration params) {
client = getRuntimeContext().getRosClient("model-svc");
}
@Override
public void asyncInvoke(String value, ResultFuture<String> resultFuture) {
client.<String>request("predict", value)
.thenAccept(res -> resultFuture.complete(Collections.singleton(res)))
.exceptionally(t -> {
resultFuture.completeExceptionally(t);
return null;
});
}
},
30, TimeUnit.SECONDS, // timeout per request
100 // max concurrent requests
);
result.sinkTo(sink);
env.execute("Async Inference Job");Batch and Asynchronous Processing
The following example demonstrates how to define a service that combines multiple processing modes — synchronous single, asynchronous single, synchronous batch, and asynchronous batch — and how the client invokes them uniformly:
// 1. Define a service with mixed processing modes
class MlService extends AbstractRpcOperator {
private transient Model model;
@Override
public void open(Context ctx) throws Exception {
super.open(ctx);
model = Model.load("/models/bert-base");
}
// Synchronous single: lightweight, returns immediately
public String getModelVersion() {
return model.version();
}
// Asynchronous single: returns a Future, invoke thread is not blocked
public CompletableFuture<float[]> predict(float[] input) {
return CompletableFuture.supplyAsync(() -> model.predict(input));
}
// Synchronous batch: framework accumulates individual requests into a batch
@Batch(maxSize = 32, maxWaitMs = 50)
public List<String> classify(List<String> texts) {
return model.batchClassify(texts);
}
// Asynchronous batch: maximum throughput mode
@Batch(maxSize = 64, maxWaitMs = 100)
public CompletableFuture<List<float[]>> embed(List<float[]> vectors) {
return CompletableFuture.supplyAsync(() -> model.batchEmbed(vectors));
}
}
// 2. Register the service
env.addRpcOperatorService(
RosDescriptor.builder("ml-service", new MlService())
.parallelism(4)
.queueCapacity(1024)
.inFlightCapacity(256)
.cpuCores(2.0)
.taskHeapMemoryMB(4096)
.build());
// 3. Client invocation — uniform across all modes
env.fromSource(source, WatermarkStrategy.noWatermarks(), "input")
.process(new ProcessFunction<Request, Response>() {
private transient RosClient client;
@Override
public void open(Configuration params) {
client = getRuntimeContext().getRosClient("ml-service");
}
@Override
public void processElement(Request req, Context ctx, Collector<Response> out)
throws Exception {
// Client does not need to know whether the method is sync/async/batch
String label = client.<String>request("classify", req.getText())
.get(5, TimeUnit.SECONDS);
out.collect(Response.of(label));
}
})
.sinkTo(sink);Note: The client always calls request(method, args) with a single set of arguments. Batching is transparent — the framework accumulates individual requests on the service side and dispatches them as a batch when the batch is full or the wait time expires.
Chaining RpcOperators
An RpcOperator can invoke another RpcOperator via Context.getRosClient(). This enables multi-stage pipelines within the service layer — for example, preprocessing before inference:
// Preprocessing service
class PreprocessService extends AbstractRpcOperator {
public float[] tokenize(String text) {
return Tokenizer.encode(text);
}
}
// Inference service that chains to PreprocessService
class InferenceService extends AbstractRpcOperator {
private transient Model model;
private transient RosClient preprocessClient;
@Override
public void open(Context ctx) throws Exception {
super.open(ctx);
model = Model.load("/models/bert-base");
preprocessClient = ctx.getRosClient("preprocess-svc");
}
public CompletableFuture<String> predict(String text) {
return preprocessClient.<float[]>request("tokenize", text)
.thenApply(tokens -> model.predict(tokens));
}
}
// Register both services
env.addRpcOperatorService(
RosDescriptor.builder("preprocess-svc", new PreprocessService())
.parallelism(2).build());
env.addRpcOperatorService(
RosDescriptor.builder("inference-svc", new InferenceService())
.parallelism(4).build());Note: See Design Notes in §1 for guidance on when to prefer chaining over calling services independently from the data plane.
Shared Service Across Jobs
An RPC service can be deployed as an independent job and shared by multiple consumer jobs within the same Application. Consumer jobs discover and invoke the shared service using the same getRosClient() API — no code change is needed on the client side.
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// ==================== Step 1: Deploy the shared service ====================
// This submits a ROS-only job to the cluster
env.startSharedRpcOperatorService(
RosDescriptor.builder("shared-model-svc", new ModelService())
.parallelism(4)
.cpuCores(2.0)
.taskHeapMemoryMB(4096)
.build());
// ==================== Step 2: Submit multiple consumer jobs ====================
// Both jobs share the same service — no redundant model loading
env.fromSource(sourceA, WatermarkStrategy.noWatermarks(), "input-A")
.process(new ModelCallingFunction("shared-model-svc"))
.sinkTo(sinkA);
JobClient job1 = env.executeAsync("Consumer Job A");
env.fromSource(sourceB, WatermarkStrategy.noWatermarks(), "input-B")
.process(new ModelCallingFunction("shared-model-svc"))
.sinkTo(sinkB);
JobClient job2 = env.executeAsync("Consumer Job B");Note: The shared service runs as an independent job with full fault isolation from consumers. It can be explicitly stopped via stopSharedRpcOperatorService(), or is automatically stopped when all non-ROS jobs in the Application have finished.
The key interfaces involved — RpcOperator, AbstractRpcOperator, BatchConfig, @Batch, RosDescriptor, and RosClient — are detailed in the sections that follow.
1. RpcOperator — Service Logic Interface
@Experimental
public interface RpcOperator extends Serializable {
/** Called at service startup to initialize shared resources (models, connections, etc.) */
void open(Context context) throws Exception;
/**
* Processes a single RPC request.
*
* <p><b>Threading guarantee:</b> This method is always invoked serially
* on a single thread. However, if the return value is a
* {@link CompletableFuture}, the framework will not block — it registers
* a callback and immediately proceeds to the next request.
*
* @param method method name (used for routing)
* @param args method arguments
* @return response result — may be a plain object (synchronous) or a
* {@link CompletableFuture} (asynchronous)
*/
Object processRequest(String method, Object... args) throws Exception;
/**
* Processes a batch of requests for a given method.
*
* <p>Called by the framework after accumulating requests for methods
* declared as batch-capable via {@link #getBatchConfig()}.
*
* <p>The return value must be one of the following:
* <ul>
* <li>a {@link List} of results, meaning the batch completed synchronously; or</li>
* <li>a {@link CompletableFuture} that completes with such a {@link List},
* meaning the batch completes asynchronously.</li>
* </ul>
*
* <p>In both cases, the result list must have the same size as {@code argsBatch}.
* The element at index {@code i} corresponds to the request at
* {@code argsBatch.get(i)}.
*
* <p>If the returned future completes exceptionally, or if the completed result
* list size does not match {@code argsBatch.size()}, the framework fails all
* requests in the batch with the same error.
*
* @param method method name
* @param argsBatch list of argument arrays, one per request
* @return either a result list or a CompletableFuture that completes with a result list
*/
Object processBatchRequest(String method, List<Object[]> argsBatch) throws Exception;
/**
* Declares which methods support batch processing and their configuration.
*
* <p>The framework calls this method once during initialization to set up
* per-method accumulators. Methods not present in the returned map are
* processed individually via {@link #processRequest}.
*
* @return a map from method name to its {@link BatchConfig}, or an empty map
*/
Map<String, BatchConfig> getBatchConfig();
/** Called at service shutdown to release resources */
void close() throws Exception;
interface Context {
int getSubtaskIndex();
int getNumberOfParallelSubtasks();
String getServiceName();
MetricGroup getMetricGroup();
RosClient getRosClient(String serviceName);
}
}Design Notes:
- Important — Serial Execution Guarantee:
processRequestandprocessBatchRequestare always invoked serially on a single thread. User code inside these methods can safely access instance state without synchronization. If the return value is aCompletableFuture, the framework does not block — the invoke thread immediately proceeds to the next request while the future completes asynchronously on a separate thread. A single RPC service can expose multiple methods, routed via
String method;Object... argssupports arbitrary parameter signatures.RpcOperatorsupports two low-level invocation paths: `processRequest` for single requests and `processBatchRequest` for batch requests.Context.getRosClient()enables chaining — one RpcOperator can invoke another. Compared to calling both services independently from the data plane, chaining saves one round of serialization/deserialization for intermediate data (it crosses 1 RPC boundary instead of 2) — this matters when intermediate results are large. It also encapsulates multi-step logic as an internal implementation detail, simplifying the data-plane code. However, chaining introduces service coupling and cascading failure risk — prefer calling services independently from the data plane when neither benefit applies.
2. BatchConfig — Batch Processing Configuration
@Experimental
public class BatchConfig implements Serializable {
private final int maxBatchSize; // Max requests per batch before flush
private final long maxWaitMs; // Max wait time (ms) before flush even if batch is not full
public static BatchConfig of(int maxBatchSize, long maxWaitMs);
}3. AbstractRpcOperator — Convenience Base Class
@Experimental
public abstract class AbstractRpcOperator implements RpcOperator {
// During open(), scans all public methods of the subclass and builds a MethodHandle cache.
// Also scans @Batch annotations and auto-generates getBatchConfig().
// processRequest() dispatches to individual methods.
// processBatchRequest() dispatches to @Batch-annotated methods with List-wrapped parameters.
// A batch-capable method may return either List<T> or CompletableFuture<List<T>>;
// AbstractRpcOperator forwards that value as the top-level return value of
// processBatchRequest().
// Method overloading is not supported (method name serves as the unique routing key).
}Since AbstractRpcOperator inherits the serial execution guarantee from RpcOperator, user-defined business methods (e.g., predict, classify) are never called concurrently.
For a batch-capable method, user code should return either List<T> (synchronous batch) or CompletableFuture<List<T>> (asynchronous batch). Users do not need to return List<CompletableFuture<T>>; the asynchronous marker is the top-level return value of processBatchRequest().
Users only need to define their business methods. The four processing modes — synchronous/asynchronous × single/batch — are expressed naturally through return type and @Batch annotation:
public class ModelService extends AbstractRpcOperator {
private transient Model model;
@Override
public void open(Context ctx) throws Exception {
super.open(ctx); // Must be called
model = Model.load("/models/bert-base");
}
// Synchronous single: lightweight query, returns immediately
public String getModelVersion() {
return model.version();
}
// Asynchronous single: returns a Future, invoke thread is not blocked
public CompletableFuture<float[]> predict(float[] input) {
return CompletableFuture.supplyAsync(() -> model.predict(input));
}
// Synchronous batch: framework accumulates requests, calls with a list
@Batch(maxSize = 32, maxWaitMs = 50)
public List<String> classify(List<String> texts) {
return model.batchClassify(texts);
}
// Asynchronous batch: maximum throughput mode
@Batch(maxSize = 64, maxWaitMs = 100)
public CompletableFuture<List<float[]>> embed(List<float[]> vectors) {
return CompletableFuture.supplyAsync(() -> model.batchEmbed(vectors));
}
}
Note: Client invocation is uniform across all four modes — always client.request(method, args). The client does not need to know whether the server method is synchronous, asynchronous, or batch-capable. Batching is entirely transparent and handled by the framework on the service side.
@Batch Annotation
AbstractRpcOperator provides the @Batch annotation as a convenience for declaring batch-capable methods. During open(), the framework scans methods annotated with @Batch and automatically builds the getBatchConfig() return value. For a batch-capable method, each original parameter type is lifted to a List-wrapped parameter at batch invocation time. The method may return List<R> (synchronous batch) or CompletableFuture<List<R>> (asynchronous batch). In both cases, the returned list must have the same size as the number of requests in the batch, and the element at index i corresponds to request i.
For methods with multiple parameters, the framework groups requests by index: the element at index i across all lifted parameter lists belongs to the same request.
@Experimental
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Batch {
/** Max requests per batch (default: 32). */
int maxSize() default 32;
/** Max wait time in milliseconds before flushing an incomplete batch (default: 100). */
long maxWaitMs() default 100;
}Users who implement RpcOperator directly (without extending AbstractRpcOperator) should provide batch configuration by implementing getBatchConfig() manually — the @Batch annotation has no effect in that case.
4. RosDescriptor — Service Declaration
@Experimental
public class RosDescriptor implements Serializable {
public static Builder builder(String serviceName, RpcOperator operator);
public static class Builder {
public Builder parallelism(int parallelism); // Default: 1
public Builder queueCapacity(int capacity); // Default: 1024
public Builder inFlightCapacity(int capacity); // Default: 256
public Builder cpuCores(double cores); // Optional
public Builder taskHeapMemoryMB(int mb); // Optional
public Builder taskOffHeapMemoryMB(int mb); // Optional
public RosDescriptor build();
}
}
Design Note: - The current
RosDescriptorsupports standard Flink resource dimensions (CPU, heap/off-heap memory). Resource declaration for heterogeneous devices such as GPU will be introduced in a dedicated follow-up FLIP that promotes GPU to a first-class resource with native scheduling support. The Builder interface is designed to be extended without breaking changes. queueCapacity: Maximum number of pending requests (in the queue and accumulators combined). When full, new requests are rejected with anOVERLOADEDerror.inFlightCapacity: Maximum number of requests that have been dispatched but not yet completed. This controls memory usage for asynchronous and batch processing. When full, the invoke thread blocks until an in-flight request completes.
5. RosClient — Async RPC Client
@Experimental
public interface RosClient {
/** Asynchronously invokes a service method */
<T> CompletableFuture<T> request(String method, Object... args);
/** Number of currently available service instances */
int getAvailableInstances();
void close();
}
RosClient.request() returns a CompletableFuture and supports two usage patterns:
Synchronous — call
request(...).get()to block until the result is available.Asynchronous — use
AsyncDataStreamwithRichAsyncFunctionfor non-blocking invocation with higher throughput. This is recommended over manually managingCompletableFutureresults, asAsyncDataStreamhandles pending requests and checkpoint recovery automatically.
6. Exceptions
The Future returned by RosClient.request() completes exceptionally on invocation failure. The framework uses a unified exception class + failure type enum design:
@Experimental
public class RosInvocationException extends FlinkRuntimeException {
private final String serviceName;
private final RosFailureType failureType;
public String getServiceName() { return serviceName; }
public RosFailureType getFailureType() { return failureType; }
}@Experimental
public enum RosFailureType {
/** No available service instances (service not started or all instances failed); request was not sent */
UNAVAILABLE,
/** Serialization failure for request parameters or response results */
SERIALIZATION_ERROR,
/** Request was sent but timed out waiting for a response */
TIMEOUT,
/** Request reached the server but was rejected: request queue is full */
OVERLOADED,
/** Request reached the server; RpcOperator.processRequest() threw an exception */
EXECUTION_ERROR,
/** Request reached the server but was rejected: service instance is shutting down */
SHUTTING_DOWN
}
7. API Extensions to Existing Classes
// New additions to StreamExecutionEnvironment
public void addRpcOperatorService(RosDescriptor descriptor);
public void startSharedRpcOperatorService(RosDescriptor descriptor) throws Exception;
public void stopSharedRpcOperatorService(String serviceName) throws Exception;
// New addition to RuntimeContext
public RosClient getRosClient(String serviceName);
// New addition to FunctionContext (enables RPC access from Table API / SQL UDFs)
public RosClient getRosClient(String serviceName);addRpcOperatorService— registers a service within the current job (same lifecycle as the job).startSharedRpcOperatorService— submits a standalone ROS-only job to the cluster. The service is independent of any consumer job and can be shared across multiple jobs within the same Application.stopSharedRpcOperatorService— stops a previously started shared service by name.
8. Configuration
All RPC service parameters are declared per service via RosDescriptor.Builder (see §4). In addition, each parameter can be overridden through Flink configuration without modifying job code, using the key pattern ros.<service-name>.service.<parameter>:
Key Pattern | Type |
| Integer |
| Integer |
| Integer |
| Double |
| MemorySize |
| MemorySize |
Precedence: Configuration > Code. If a configuration key is present (via flink-conf.yaml or -D at submission), it overrides the value declared in RosDescriptor.Builder. The code-declared value serves as the development default. This allows operations teams to tune deployment parameters without modifying the application code.
# Example: override parallelism and queue capacity for "model-svc"
ros.model-svc.service.parallelism: 8
ros.model-svc.service.queue-capacity: 2048
ros.model-svc.service.task-heap-size: 8g9. Metrics
RPC service Tasks automatically register the following metrics, scoped at the Task level (<host>.taskmanager.<tm_id>.<job_name>.<task_name>.<subtask_index>.<metric>).
Request counting:
Metric Name | Type | Semantics |
| Counter | Total number of requests received and started processing |
| Meter | QPS (60s sliding window) |
| Counter | Number of successfully processed requests |
| Counter | Number of failed requests (user code threw exception) |
| Counter | Number of requests rejected due to full queue |
| Counter | Total number of result elements produced |
| Meter | Results produced per second |
| Gauge<Double> | Success rate over the last 60s (0.0–1.0) |
Utilization:
Metric Name | Type | Semantics |
| Gauge<Long> | Milliseconds per second spent processing requests (0–1000) |
| Gauge<Long> | Milliseconds per second spent waiting for requests (0–1000) |
| Gauge<Integer> | Number of requests in the queue (excludes accumulators and in-flight) |
| Gauge<Double> | Queue utilization ratio (0.0–1.0) |
| Gauge<Integer> | Number of dispatched but not yet completed requests |
| Gauge<Double> | In-flight utilization ratio (0.0–1.0) |
| Gauge<Integer> | Requests waiting in batch accumulators |
Batch processing:
Metric Name | Type | Semantics |
| Counter | Total number of batch flushes |
| Counter | Flushes triggered by reaching |
| Counter | Flushes triggered by |
| Gauge<Double> | Average batch size of recent flushes |
Metrics are registered through Flink's standard MetricGroup, compatible with all existing metric reporters (Prometheus, JMX, etc.) and the Web UI Metrics tab.
10. REST API & Web UI
A new vertexType field is added to the response body (JobVertexDetailsInfo) of the existing REST endpoint GET /jobs/:jobid/vertices/:vertexid, to allow the Web UI to identify RPC service vertices and render service-specific views:
// GET /jobs/:jobid/vertices/:vertexid response (excerpt)
{
"id": "cbc357ccb763df2852fee8c4fc7d55f2",
"name": "Model Service",
"parallelism": 4,
"maxParallelism": 128,
"vertexType": "ROS_SERVICE",
"now": 1716700000000,
"subtasks": [...]
}vertexType enum values:
Value | Meaning |
| Normal vertex |
| RPC service vertex, hosting |
For vertices with vertexType = ROS_SERVICE, a new "RPC" tab is added, displaying real-time RPC metrics for each subtask in a table:
Column | Data Source |
Subtask | Subtask index |
Success |
|
Failed |
|
Rejected |
|
Queue |
|
Queue Usage |
|
In-Flight |
|
In-Flight Usage |
|
Avg Batch Size |
|
Success Rate |
|
Throughput |
|
Data is fetched via the existing subtask metrics REST endpoint (GET /jobs/:jobid/vertices/:vertexid/metrics) and auto-refreshes every 10 seconds. Example shown below.
Proposed Changes
Architecture Overview
In-job service (addRpcOperatorService):
+-- JobMaster -----------------------------------+
| |
| ServiceRegistry |
| "model-svc" -> {#0: addr1, #1: addr2} |
| ^ | |
| RosCoordinator EndpointProvider |
| (register/deregister) (query endpoints)|
+----------+--------------------------|----------+
| |
+-- TM A --+----------+ +-- TM B --|----------+
| RpcTask | | StreamTask |
| RpcOperator | | ProcessFunction |
| RPC Endpoint <----+---+------RosClient |
| | | |
| Separate SSG | | Default SSG |
+----------------------+ +---------------------+Each RosDescriptor corresponds to an independent JobVertex (with invokable RpcTask), having its own parallelism, resources, and SlotSharingGroup. It has no data edges connecting it to the data plane and belongs to a different Pipelined Region.
Shared service (startSharedRpcOperatorService):
+-- Dispatcher -----------------------------------------+
| |
| SharedServiceRegistry |
| "shared-model-svc" -> {#0: addr1, #1: addr2} |
| ^ | |
| register/deregister subscribe/push |
+----------+------------------------------|-------------+
| |
+-- JM-A (ROS-only job) ---+ +-- JM-B (consumer job) --------+
| | | |
| SharedRosCoordinator | | EndpointProvider |
| ^ | | local lookup → fallback |
| | | | to Dispatcher |
+----------|----------------+ +----------------|---------------+
| |
+-- TM-1 --+----------+ +-- TM-2 -------|----------+
| RpcTask | | StreamTask |
| RpcOperator | | ProcessFunction |
| RPC Endpoint <----+---------+------RosClient |
| | | |
+----------------------+ +--------------------------+The shared service runs as a standalone ROS-only job. Consumer jobs discover its endpoints transparently — the JobMaster first checks its local ServiceRegistry, then falls back to the Dispatcher's SharedServiceRegistry.
RpcTask
A new RpcTask is introduced as a Task type parallel to StreamTask to host the RPC service. A new AbstractInvokable was chosen over reusing StreamTask because StreamTask is built around InputGate/ResultPartition/OperatorChain and assumes data input/output exists; an RPC service has no data edges, and forcing it to fit would introduce numerous empty implementations and conditional branches.
RpcTask uses a two-level capacity model with separate controls for queuing and in-flight processing:
Queue permit controls the total number of waiting requests (queue + accumulators). When exhausted, new requests are rejected with
OVERLOADED.In-flight permit controls the number of dispatched-but-incomplete requests. When exhausted, the invoke thread blocks until a response completes, providing natural backpressure.
Batch-capable methods (declared via
@BatchorgetBatchConfig()) bypass the queue and enter per-method accumulators directly. The invoke thread's run loop flushes accumulators when the batch is full or the wait time expires.processRequestandprocessBatchRequestare always called serially on the invoke thread, guaranteeing thread safety for user code.
Service Discovery
Service discovery operates at two levels — JobMaster level for in-job services and Dispatcher level for shared services.
In-job services (addRpcOperatorService):
The JobMaster maintains a ServiceRegistry that records serviceName → List<ServiceEndpoint> mappings:
Server side: After startup, RpcTask registers its endpoint address with RosCoordinator via OperatorEvent, which writes it to the ServiceRegistry. When a subtask fails, its endpoint is automatically deregistered.
Client side: Endpoints are queried on demand through the EndpointProvider interface, which provides extensible load balancing strategies (the first version supports round-robin). When endpoint changes occur (e.g., instance addition or removal), the JM pushes updates to relevant TaskManagers so that clients can discover changes in a timely manner without waiting for a cache miss.
Shared services (startSharedRpcOperatorService):
The Dispatcher maintains a SharedServiceRegistry that records endpoints for shared services across jobs:
Server side: The ROS-only job's RpcTask registers its endpoints with the Dispatcher's SharedServiceRegistry (via SharedRosCoordinator). When a subtask fails, its endpoint is automatically deregistered.
Client side: When
getRosClient()is called, the JobMaster first looks up endpoints in its local ServiceRegistry. If no endpoints are found (i.e., the service is not in-job), it falls back to querying the Dispatcher's SharedServiceRegistry. This makes shared service discovery transparent to user code — the samegetRosClient("service-name")API works for both in-job and shared services.Subscription and push: Consumer jobs subscribe to shared service endpoint updates at the Dispatcher. When endpoints change (instance added/removed/failed), the Dispatcher pushes updates to all subscribed consumer JobMasters, which in turn forward them to the relevant TaskManagers.
Neither registry participates in checkpointing — after a restart, each subtask re-registers to rebuild it.
Communication
The underlying communication mechanism between RosClient and the RPC service is decoupled from the upper-level interface. The first version directly reuses Flink's existing Pekko RPC infrastructure (zero additional dependencies). For high-latency workloads such as model inference, the additional overhead introduced by the communication layer is manageable.
Pekko imposes a per-message size limit (`pekko.framesize`, configurable). This is sufficient for most scenarios. For workloads with very large payloads (e.g., multimodal inputs), passing data references rather than raw data is recommended. If high-QPS or large-payload scenarios require it in the future, transport layer implementations such as gRPC/Netty can be introduced without affecting the upper-level interface definitions.
Serialization
Method parameters and return values of request() are based on Flink's existing serialization framework. POJO types are automatically optimized using PojoSerializer, while other types fall back to Kryo serialization to support all Java types. Users can register custom types through Flink's existing serialization configuration to optimize performance.
Failover Isolation
In-job services:
The RPC service JobVertex has no data edges to the data plane and belongs to a different Pipelined Region:
Data-plane operator failure → Only the data plane restarts; the RPC service is unaffected. The client proactively sends a cancellation signal during cleanup, causing the service to discard queued requests from the restarting client.
RPC service subtask failure → Only that subtask restarts; the data plane continues running. In-flight requests to the failed instance receive an immediate connection error (no timeout wait). The client retries against surviving instances, or returns
UNAVAILABLEif none exist.
Note on scheduler compatibility: The region-level failover isolation described above applies to the DefaultScheduler, which supports restarting individual Pipelined Regions independently. The AdaptiveScheduler currently only supports full-graph restarts — both failover and rescale rebuild the entire ExecutionGraph, including RpcOperator vertices. Enhancing AdaptiveScheduler with partial restart capability is an independent scheduler improvement orthogonal to this FLIP.
Shared services:
The shared service and consumer jobs are entirely separate jobs with independent lifecycles. Consumer job restarts do not affect the service, and vice versa. Client-side failure handling is the same as in-job services — retry against surviving instances, or UNAVAILABLE if none exist.
Resource Management
Each RPC service automatically creates a separate SlotSharingGroup, with resource requirements declared through RosDescriptor and mapped to a ResourceProfile. This is fully compatible with Flink's existing K8s/YARN resource management, supporting different resource configurations for different services.
Note: Resource declaration for heterogeneous devices (e.g., GPU) will be addressed in a dedicated FLIP that covers GPU as a first-class resource with proper scheduling support. The current proposal focuses on the RPC service primitive itself and supports standard Flink resource dimensions (CPU, heap/off-heap memory).
Stateless Design
RPC services do not participate in checkpointing. The primary target scenarios — AI-oriented data processing workloads — are typically stateless at the service level. This covers the majority of anticipated use cases without introducing the complexity of distributed snapshots for service state.
The RosClient itself is also stateless — it holds no pending-request state that requires checkpointing. As described in §5, there are two usage patterns: synchronous invocation (request(...).get()) blocks within processElement and completes before a checkpoint barrier arrives, so no pending requests exist at checkpoint time; asynchronous invocation uses AsyncDataStream with RichAsyncFunction, where the existing AsyncWaitOperator manages pending futures as part of the checkpoint protocol. In either case, RosClient requires no special checkpoint handling — the same as any other async HTTP or RPC client used within AsyncFunction.
Compatibility, Deprecation, and Migration Plan
Backward Compatibility: This is a purely additive feature. Jobs that do not use RPC services are completely unaffected.
State Compatibility: RPC services do not participate in checkpointing, so there are no state compatibility concerns.
Deprecation: This FLIP does not deprecate any existing interfaces.
Test Plan
Unit Tests & Integration Tests & Manual Tests will be used to verify this change.
Rejected Alternatives
Reuse StreamOperator / StreamTask
We considered making the RPC service a special StreamOperator (with no input channels), running inside StreamTask. However, StreamTask/OperatorChain is built around InputGate/ResultPartition with deep assumptions about data input/output. An RPC service has no data edges, and forcing it to fit would require introducing numerous empty implementations and conditional branches, violating existing invariants. Introducing independent RpcOperator interfaces and RpcTask is cleaner and provides extension space for RPC service-specific lifecycle management in the future.
Sidecar Process Model
We considered launching external processes (e.g., vLLM server) alongside the TaskManager as sidecars to provide services. However, sidecar lifecycle management is complex and not portable across deployment environments. It is also orthogonal to Flink's scheduling and resource management, unable to leverage slot allocation and failure recovery. Our approach runs the RPC service as a standard Flink Task, directly reusing existing scheduling, resource management, and failure recovery mechanisms.
Follow-up Tasks
Automatic Rewriting
Automatically identify operators suitable for (or explicitly designated by the user for) decoupled deployment (e.g., GPU operators), split them from the data plane into independent RPC services, and insert proxy operators at the original positions. Proxy operators only handle RPC forwarding and can be chained with upstream and downstream operators. User code requires no modifications to gain resource isolation and independent scaling capabilities.
Python API
Native PyFlink integration that defines RPC services through decorators (e.g., @remote), lowering the barrier for Python users.
