Overview

Deploying Flink is easy. Running it in production on a regulated, business-critical platform is not. The stream-processing logic articles in this Lab series cover windowing, joins, and state semantics; this article covers the operational layer that keeps those pipelines alive: how the cluster is structured on OpenShift, how checkpoints are persisted safely so a pod restart does not reprocess hours of transaction data, and what exactly-once end-to-end really costs in latency and throughput.

The running example is a transaction screening and fraud-detection pipeline: a few hundred thousand messages per day arriving from several upstream channels (card, instant and cross-border transfers for a payments business; orders, refunds and payouts for a marketplace), with a hard requirement that duplicate execution is a production incident, not a tolerated edge case. That constraint drives every configuration choice here.

Flink vs Kafka Streams for this use case

The Kafka Streams & Flink article covers the library-vs-cluster trade-off. The short answer: Flink wins when the pipeline crosses microservice boundaries, when state exceeds 20 GB per partition, or when you need multi-source joins with different Kafka clusters. For per-service enrichment, Kafka Streams is simpler. For a cross-domain payment screening platform, Flink is the right call.

Cluster topology

Flink runs a JobManager (coordinator, scheduler, checkpoint coordinator) and one or more TaskManagers (worker nodes that execute the actual operators). In Kubernetes/OpenShift terms:

Two architectural choices have the biggest production impact: whether the JobManager is HA (yes, always), and whether checkpoints go to a durable object store (yes, always). Everything else is tuning.

Flink Kubernetes Operator

The Flink Kubernetes Operator (version 1.9) manages the lifecycle of Flink clusters and jobs as Kubernetes custom resources. It replaces imperative flink run commands with a declarative FlinkDeployment CRD that GitOps tooling can own. The operator handles job submission, checkpoint-based upgrades, and graceful shutdown via savepoints.

Without operatorWith operator (v1.9)
Manual flink run per deploymentGitOps-managed FlinkDeployment CR
Savepoints triggered by hand before upgradesOperator triggers savepoint, waits, then restarts
JobManager restarts lose job stateHA metadata in ZooKeeper; job auto-resumes
Scaling requires manual TaskManager replica changeAutoscaler adjusts replicas based on lag metrics
Multiple YAML files to trackSingle FlinkDeployment per pipeline
OpenShift SCC constraint

Flink’s default container runs as UID 9999. OpenShift’s restricted SCC rejects non-root images that don’t declare a runAsNonRoot: true security context. Either use the official apache/flink:1.19-scala_2.12-java17 image which already sets UID 9999, or configure a custom SCC that allows that UID range. Do not use anyuid in production; most hardening baselines (CIS benchmarks, sector security standards) prohibit it.

Deploying on OpenShift

The steps below assume the Flink Kubernetes Operator is already installed via the OperatorHub catalog (namespace-scoped into flink-operator). The pipeline being deployed is the payment screening job from the real-time fraud detection article.

  1. Create the namespace and RBAC

    The operator needs a ServiceAccount with permission to manage Pods, Services, and ConfigMaps in the target namespace. Use a minimal Role, not cluster-admin.

  2. Create the S3 secret and ConfigMap

    Checkpoint storage credentials for MinIO, Ceph or a cloud object store go in a Kubernetes Secret referenced by the FlinkDeployment. Never bake credentials into the image.

  3. Build and push the application JAR image

    Use a multi-stage Dockerfile: Maven build stage, then copy the fat JAR into the Flink base image. Tag with the commit SHA for traceability. Push to the internal OpenShift registry.

  4. Apply the FlinkDeployment CR

    The operator watches this CR and creates the JobManager and TaskManager pods. The job stanza points to the JAR and entry class. Savepoint path is set here for upgrade continuity.

  5. Verify checkpoint completion

    Watch the Flink dashboard or query the /jobs/:id/checkpoints REST API. The first checkpoint should complete within 60 seconds of job startup. If it does not, the pipeline has not reached a recoverable state.

  6. Wire Prometheus scraping

    Add the metrics.reporter.prom.class and metrics.reporter.prom.port Flink configuration entries. Create a PodMonitor so Prometheus discovers the pods.

flink-payment-screening.yamlyaml
apiVersion: flink.apache.org/v1beta1
kind: FlinkDeployment
metadata:
  name: payment-screening
  namespace: flink-prod
spec:
  image: image-registry.openshift-image-registry.svc:5000/flink-prod/payment-screening:1.4.2
  flinkVersion: v1_19
  flinkConfiguration:
    # Checkpoint: incremental to MinIO every 30 s
    execution.checkpointing.interval: "30000"
    execution.checkpointing.mode: EXACTLY_ONCE
    execution.checkpointing.max-concurrent-checkpoints: "1"
    state.backend: rocksdb
    state.backend.incremental: "true"
    state.checkpoints.dir: s3://flink-checkpoints/payment-screening/checkpoints
    state.savepoints.dir: s3://flink-checkpoints/payment-screening/savepoints
    # JobManager HA via ZooKeeper
    high-availability: zookeeper
    high-availability.zookeeper.quorum: zookeeper.zookeeper.svc:2181
    high-availability.storageDir: s3://flink-checkpoints/payment-screening/ha
    # Metrics: Prometheus
    metrics.reporter.prom.factory.class: org.apache.flink.metrics.prometheus.PrometheusReporterFactory
    metrics.reporter.prom.port: "9249"
  serviceAccount: flink-sa
  jobManager:
    resource:
      memory: "2048m"
      cpu: 1
    replicas: 2   # leader + standby; needs HA enabled
  taskManager:
    resource:
      memory: "8192m"
      cpu: 4
    replicas: 3
  job:
    jarURI: local:///opt/flink/usrlib/payment-screening-1.4.2-fat.jar
    entryClass: com.example.streaming.PaymentScreeningJob
    parallelism: 12
    upgradeMode: savepoint

Checkpointing

A checkpoint is a consistent snapshot of the entire distributed streaming state, including Kafka consumer offsets. If a TaskManager dies and a new one starts, Flink restores the operators from the last successful checkpoint and resumes consuming from the Kafka offsets recorded in that checkpoint. No data is lost; some data may be reprocessed (the window between the last checkpoint and the failure). Incremental checkpoints only write changed RocksDB SST files, which reduces checkpoint size from several GB to tens of MB for a typical transaction pipeline.

Checkpoint interval vs checkpoint timeout

The default checkpoint timeout is 10 minutes. If a checkpoint takes longer than 10 minutes (which can happen when RocksDB state grows large), Flink cancels it and logs a warning—but continues processing. You will not notice until a recovery reveals a stale restore point hours behind the current offset. Set execution.checkpointing.timeout explicitly and alarm on checkpoint failures. For a 5 GB state backend, 90 seconds is a reasonable initial timeout.

The recommended checkpoint-to-S3 path uses the Flink S3 filesystem plugin bundled with the distribution. For any S3-compatible store (MinIO, Ceph, IBM COS), configure the S3 endpoint override:

flink-conf.yaml additions for S3-compatible storageyaml
# Place in the flinkConfiguration stanza of the FlinkDeployment CR
s3.endpoint: https://s3.storage.example.com
s3.path.style.access: "true"
# Credentials: Flink does not expand ${...} in its configuration. Supply
# AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY to the pods from a Secret
# (podTemplate env), or use workload identity, and let the S3 filesystem
# plugin (flink-s3-fs-presto for checkpoints) pick them up.
# Incremental checkpoints: only changed SST files are uploaded
state.backend.incremental: "true"
# Retain 3 completed checkpoints in case a restore to a specific one is needed
state.checkpoints.num-retained: "3"

Exactly-once

Flink’s exactly-once guarantee covers the processing state. Whether the end-to-end pipeline achieves exactly-once depends on the source and sink connectors too. With Kafka:

  • Source (Kafka consumer): offsets are checkpointed with the state. On recovery, Flink resets the Kafka consumer to the checkpointed offset. The source delivers at-least-once to the operators (events between the last checkpoint and the failure are replayed), but with idempotent operators the end result is exactly-once.
  • Sink (Kafka producer): the Kafka sink uses two-phase commit: transactions are opened at each checkpoint barrier, committed when the checkpoint succeeds, aborted when it fails. This requires the downstream topic to use transactions-aware consumers (isolation.level=read_committed). The latency cost is real: a 30-second checkpoint interval means the sink data becomes visible every 30 seconds, not per-record.
Exactly-once with non-Kafka sinks

The two-phase commit protocol requires the sink to support transactional writes. Kafka does. A REST API, a direct JDBC connection (without XA), or a custom HTTP sink does not. If your pipeline writes to a non-transactional sink—a partner message queue, a legacy system-of-record API, an SFTP export—you have at-most-once (if you skip retries) or at-least-once (if you retry). Making those sinks idempotent at the consumer side is the only path to effectively-once semantics. The Idempotent Consumers article covers that pattern.

KafkaSink configuration (Java)java
KafkaSink<ScreeningDecision> sink = KafkaSink.<ScreeningDecision>builder()
    .setBootstrapServers("kafka.kafka-prod.svc:9092")
    .setRecordSerializer(
        KafkaRecordSerializationSchema.builder()
            .setTopic("screening-decisions")
            .setValueSerializationSchema(new AvroSerializationSchema<>(ScreeningDecision.class))
            .build())
    // EXACTLY_ONCE uses Kafka transactions; requires checkpoint mode EXACTLY_ONCE
    .setDeliveryGuarantee(DeliveryGuarantee.EXACTLY_ONCE)
    // Transactional ID prefix: unique per job to avoid transaction conflicts on restart
    .setTransactionalIdPrefix("payment-screening-")
    .setKafkaProducerConfig(props -> {
        props.setProperty(ProducerConfig.TRANSACTION_TIMEOUT_CONFIG, "120000"); // 2 min
        props.setProperty(ProducerConfig.ACKS_CONFIG, "all");
        props.setProperty(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, "true");
    })
    .build();
Transaction timeout must exceed checkpoint interval + checkpoint duration

A Kafka transaction that is not committed within its timeout is aborted by the broker. If a checkpoint takes 90 seconds and the transaction timeout is 60 seconds, the sink aborts its transaction, the checkpoint fails, and the job restores from the previous checkpoint. Set the transaction timeout explicitly on the sink, comfortably above the checkpoint interval plus the longest checkpoint and restart time. The Kafka producer default is 60 000 ms, Flink’s Kafka connector applies its own default, and the brokers cap the value at transaction.max.timeout.ms (15 minutes by default) — so set both deliberately.

RocksDB tuning

RocksDB is the default state backend for large stateful Flink jobs. Its default configuration is optimised for a generic workload, not for a screening pipeline where state is read heavily (sanctions lookups) and written moderately (velocity counters). Two tuning areas matter most: the block cache (keeps hot SST blocks in memory, reduces read I/O) and write buffer (batches writes before flushing to L0).

RocksDBTuner.javajava
public class RocksDBTuner implements RocksDBOptionsFactory {

  private static final Logger LOG = LoggerFactory.getLogger(RocksDBTuner.class);

  @Override
  public DBOptions createDBOptions(DBOptions currentOptions, Collection<AutoCloseable> handlesToClose) {
    return currentOptions
        .setMaxBackgroundJobs(4)         // parallel compaction threads
        .setInfoLogLevel(InfoLogLevel.WARN_LEVEL);
  }

  @Override
  public ColumnFamilyOptions createColumnOptions(ColumnFamilyOptions currentOptions,
                                                   Collection<AutoCloseable> handlesToClose) {
    // 256 MB block cache per TaskManager slot: hot sanctions data stays in memory
    LRUCache cache = new LRUCache(256 * 1024 * 1024L);
    handlesToClose.add(cache);
    return currentOptions
        .setTableFormatConfig(new BlockBasedTableConfig()
            .setBlockCache(cache)
            .setBlockSize(64 * 1024))     // 64 KB blocks
        .setWriteBufferSize(128 * 1024 * 1024L)   // 128 MB write buffer
        .setMaxWriteBufferNumber(2)
        .setLevel0FileNumCompactionTrigger(4);
  }
}

Register in flinkConfiguration: state.backend.rocksdb.options-factory: com.example.streaming.RocksDBTuner.

State TTL is also configured in the operator code, not in RocksDB. For velocity counters (how many transactions in the last 5 minutes), set a TTL on the state descriptor so RocksDB does not accumulate per-customer rows indefinitely:

State TTL setupjava
StateTtlConfig ttlConfig = StateTtlConfig
    .newBuilder(Time.minutes(15))              // evict after 15 min of inactivity
    .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
    .setStateVisibility(StateTtlConfig.StateVisibility.NeverReturnExpired)
    .cleanupInRocksdbCompactFilter(1000)       // compact-filter cleans lazily
    .build();

ValueStateDescriptor<VelocityState> descriptor =
    new ValueStateDescriptor<>("velocity", VelocityState.class);
descriptor.enableTimeToLive(ttlConfig);

JobManager HA

A single JobManager pod is a single point of failure. If it dies, all running jobs halt until the pod restarts—which under default Kubernetes restart behaviour can take 30–90 seconds. With HA mode and a second JobManager replica, the standby is elected leader within seconds via ZooKeeper (or Kubernetes HA, which avoids running ZooKeeper), and the running jobs resume from the last checkpoint with no operator intervention.

For OpenShift deployments, run ZooKeeper in the same cluster using the Strimzi ZooKeeper component (if Kafka is already Strimzi-managed) or the Bitnami chart. In production, three ZooKeeper nodes is the minimum quorum that tolerates a single node failure.

Rolling upgrades and savepoints

A Flink application upgrade—new JAR, new parallelism, changed operator logic—requires stopping the running job, taking a savepoint, and restarting from it. A savepoint is a manually-triggered consistent snapshot; unlike a checkpoint, it is retained until explicitly deleted and its format is stable across Flink minor versions.

With the operator’s upgradeMode: savepoint, the upgrade workflow is fully automated: update the image tag in the FlinkDeployment CR, commit to Git, ArgoCD applies the change, the operator triggers a savepoint, waits for it to complete, and starts the new version from that savepoint. The pipeline is offline for 5–15 seconds (savepoint duration). For a screening pipeline with a hard SLA, schedule upgrades inside the agreed low-traffic or maintenance window of the downstream systems it feeds.

State schema compatibility on upgrade

A savepoint stores state keyed by operator name and UID. If you rename an operator, add a new stateful operator without explicitly assigning a UID, or change the serialisation format of a state class, the restore will fail or silently lose state. Set .uid("velocity-check") on every stateful operator. Use Avro for state serialisation—it supports schema evolution. Never use Java serialisation for operator state in production.

Observability

The most important Flink metrics for a payment screening pipeline are not the generic JVM ones. These five determine whether the pipeline is healthy:

MetricWhere to find itAlert threshold
lastCheckpointDurationJobManager REST API, Prometheus> 90 s → checkpoint at risk
lastCheckpointSizeJobManager REST APISpike > 2× average → state growth
records-lag-max (Kafka source)Kafka consumer group metrics> 50,000 → pipeline falling behind
numRecordsOutPerSecondPer-subtask TaskManager metricDrop > 30% → backpressure
fullRestartsJobManager metric> 0 in 5 min → job in restart loop

Route these into the platform Prometheus/Grafana stack via the PodMonitor approach. A Grafana dashboard with one row per metric, one column per TaskManager subtask, surfaces skew (one partition lagging while others are healthy) which is otherwise invisible in aggregated views.

Common pitfalls

Checkpoint storage fills silently

With state.checkpoints.num-retained: 3, only the 3 most recent checkpoints are kept—but only if the checkpoint is marked “complete”. A checkpoint that partially uploaded and then failed may leave orphaned SST files in S3 that the cleaner never touches, because they are not in the checkpoint directory index. Run a weekly S3 lifecycle rule to expire objects older than 7 days under the checkpoint prefix. MinIO, Ceph and the major cloud object stores all support lifecycle policies on a bucket prefix.

Parallelism mismatch corrupts state

Restoring from a savepoint at a different parallelism triggers a re-partitioning of keyed state. Flink handles this correctly—but only if your key serialiser is deterministic. A HashMap-backed POJO field with unstable hash codes will scatter state to wrong partitions on restore. Always test a parallelism change in staging by taking a savepoint from production (or a copy of it) and restoring at the new parallelism; verify that aggregation results match before cutting over.

OpenShift eviction kills TaskManagers mid-checkpoint

OpenShift evicts pods when node memory pressure is high. A TaskManager evicted mid-checkpoint leaves its local RocksDB in a partial state. Flink detects this and triggers a job restart from the previous complete checkpoint, but the eviction will keep repeating until the root cause is fixed. Set resource requests and limits carefully: the TaskManager heap plus the RocksDB block cache plus JVM off-heap must fit within the pod memory limit. Overcommitting memory on TaskManager pods to save cluster cost is one of the most common causes of production incidents on Flink-on-Kubernetes.