Running Integration Batches with a Kubernetes Job-based Scheduler
A scheduled Integration Platform workload needs an execution environment, whether it processes a large dataset or calls an external system. If the Scheduler executes the batch code in its own process, a Scheduler failure becomes an execution failure, and it becomes difficult to isolate per-job resources and versions.
This article describes a design that reads schedule metadata and creates Kubernetes Jobs. The key is to make the Scheduler a Control Plane, not the workload executor, and separate actual batch processing into an Execution Plane made of one-shot Pods. The explanation uses no dependency on a particular organization, cluster, image registry, or internal API.
Divide the Scheduler from the execution area
Section titled “Divide the Scheduler from the execution area”A Scheduler that executes batch code directly creates several problems.
- Different batches share the same process and memory.
- A leak or infinite wait in one job affects the next job.
- Changing an image version or execution setting requires deploying the Scheduler as well.
- Execution results are mixed with Scheduler logs, making job-level observation difficult.
- After a restart, it is difficult to determine whether an execution request was already sent.
The Scheduler should therefore be limited to deciding and requesting “which workload runs when.” Kubernetes handles Pod placement, restart behavior, termination state, and resource isolation, while the batch container owns business processing and result recording.
| Area | Responsibility | Failure boundary |
|---|---|---|
| Control Plane | Schedule lookup, Cron evaluation, dispatch, deduplication, result tracking | Scheduler restart and API errors |
| Kubernetes API | Job validation, persistence, Pod creation and status management | API latency and permission errors |
| Execution Plane | Batch code, input processing, success/failure result | Application and external-system errors |
| Metadata Store | Source of Interface and execution configuration | DB errors and invalid metadata |
This separation prevents “the schedule is registered” and “the work succeeded” from being treated as one state. Registration is desired state, Job creation is a dispatch result, and the Pod termination condition is the execution result.
The overall sequence
Section titled “The overall sequence”The general flow validates one schedule read from the Metadata Store, wraps it in a standard execution DTO, and translates it into a Kubernetes Job.
There are two ways to implement recurring execution. All schedules can be registered directly as Kubernetes CronJobs, but the model in this article has one Scheduler query the Metadata Store, evaluate Cron, and create a Job when needed. This makes it easier to manage Interface metadata centrally, apply a new image version or extra argument immediately, and apply common policy to every dispatch.
Scheduler and Control Plane sequence
Section titled “Scheduler and Control Plane sequence”The Scheduler process starts the same control flow through a fixed-period tick or an external trigger API.
- Query schedule metadata where
enabledis true (orstatus: ACTIVE). - Read
ifId,ifType, andifGroupfor each item. - Parse
cronExpressionusing UNIX Cron rules and check whether it matches the current time. - Validate image name and version, JVM memory, and additional execution arguments.
- Build an execution request from
ifIdand the metadata data. - Ask the control API to create a
batch/v1 Jobthrough the Kubernetes API. - Record the returned Job name, namespace placeholder, and labels as a dispatch result.
- Observe Job status afterward and record the execution result separately.
Manual execution should use the same path. An API such as POST /cron/trigger/{ifId} looks up one metadata item and calls the same Job-creation function. If an all-execution API is needed, it can iterate over active items, but it should preserve each Job’s dispatch result instead of turning one request into a large synchronous operation.
The Control Plane API response is not the batch result. A response that represents “was the request accepted by the Kubernetes API?” is more appropriate, for example:
{ "ifId": "<interface-id>", "dispatch": { "accepted": true, "jobName": "<job-name>", "namespace": "<tenant-namespace>", "correlationId": "<correlation-id>" }}Even after accepted: true, the Pod can fail to start or can fail during execution. The status semantics must therefore be documented so that an API caller does not mistake immediate acceptance for successful business processing.
Translate metadata into a Job spec
Section titled “Translate metadata into a Job spec”A schedule row in the Metadata Store is not a Kubernetes resource. The Control Plane first normalizes the internal model and maps only approved fields into the Job spec.
| Schedule metadata | Job or Pod destination | Design intent |
|---|---|---|
ifId | label, IF_ID, batch job parameter | Execution identity and result correlation |
ifType, ifGroup | label or constrained environment variable | Classification and search |
cronExpression | Scheduler trigger condition | Do not duplicate Cron inside the Pod |
imageName + imageVersion | container.image | Pin execution code to a release |
jvmXms, jvmXmx | JAVA_OPTS, memory request/limit calculation | Align JVM and Kubernetes resources |
extraArgs | Allowlisted env, args, or host alias | Balance extensibility and safety |
Use an immutable version such as name:version for images. If a mutable tag such as latest is allowed, the same schedule can run different code at different times. The real registry address and credentials should be injected through an image pull secret or platform policy rather than exposed in code or metadata.
The following is a conceptual Job spec. All values are public-document placeholders.
apiVersion: batch/v1kind: Jobmetadata: generateName: <interface-id>- labels: app: integration-batch ifid: <interface-id>spec: backoffLimit: 0 ttlSecondsAfterFinished: 86400 template: metadata: labels: app: integration-batch ifid: <interface-id> spec: restartPolicy: Never containers: - name: <interface-id> image: <registry>/<batch-image>:<immutable-version> env: - name: IF_ID value: <interface-id> - name: JAVA_OPTS value: >- -Dspring.batch.job.name=<interface-id> -Xms<initial-memory> -Xmx<maximum-memory> resources: requests: cpu: <cpu-request> memory: <memory-request> limits: cpu: <cpu-limit> memory: <memory-limit>In an implementation, Kubernetes client models such as V1Job, V1JobSpec, V1PodTemplateSpec, and V1Container can build this structure. Use generateName in Job metadata to create a unique name for each execution, and put only stable values in labels so they remain useful for result queries and operational searches.
JVM memory and container memory must use the same basis. A useful starting point is containerMemory = ceil(Xmx × 1.2), but this is only a heuristic that adds 20% to the heap. Metaspace, thread stacks, direct buffers, native libraries, and monitoring agents consume memory outside the heap, so setting the container limit equal to Xmx can produce OOMKilled under otherwise normal load. Do not apply the heuristic unchanged to every workload: tune profiles from peak RSS observed in load tests, enforce a guardrail that keeps Xmx at or below 80% of the limit, and validate platform minimum and maximum memory limits.
The memory request determines where the Scheduler can place the Pod, while the limit is the actual termination boundary. Keep requests close to limits for long-running, steady batches; size the gap for short bursty work from measurements. Callers must not select execution nodes arbitrarily. The Control Plane should inject only approved nodeSelector or node-affinity rules and required tolerations. Clean Jobs and Pods with ttlSecondsAfterFinished, but retain execution results and sizing evidence such as peak memory in the Result Store beyond that TTL.
Concurrency and Idempotency
Section titled “Concurrency and Idempotency”Cron expresses a time; it does not prevent duplicate execution. If two Scheduler replicas run, or a slow tick overlaps the next tick, two Jobs can be created for the same ifId. There are two viable answers, and they are a trade-off rather than a right and a wrong choice.
Deterministic naming. Derive the Job name from <ifId>-<scheduled-slot> and let the Kubernetes API be the arbiter. The second replica that tries to create the same name receives 409 AlreadyExists, so duplicate dispatch is rejected by the API server itself with no extra store. This is exactly the mechanism the CronJob controller uses when it names a Job after its schedule time. The constraints are real, though: a Job name must be a DNS subdomain of at most 63 characters, so a long ifId plus a slot suffix has to be truncated or hashed deterministically, and the name is only unique while the object exists. Once ttlSecondsAfterFinished deletes the Job, the same name becomes available again and a late retry can create a genuine duplicate run.
generateName plus a dispatch-store unique constraint. Let Kubernetes assign a unique suffix per execution, and put the uniqueness decision in a dispatch store with a unique index. This distinguishes every execution cleanly, survives TTL deletion because the dispatch row outlives the Job object, and allows deliberate reruns with a different key. The cost is an extra store, plus a window where the row and the Job object can disagree.
A common combination uses both: a deterministic label or annotation for reconciliation and a dispatch row for authority, with generateName for the object name. In either case, give each execution an idempotency key such as:
<interface-id>:<scheduled-slot>:<revision>With deterministic naming, this key is encoded into the Job name and the 409 AlreadyExists response is the duplicate check. With generateName, the Control Plane records this key conditionally in the Metadata Store or a separate dispatch store.
- Insert a
PENDINGrow with a unique constraint. - Only the replica that succeeds gets permission to create the Job.
- Save the Kubernetes API Job name as
DISPATCHED. - If the same key already exists, look up the existing Job and do not create another.
- If a request times out with an unknown result, search by label or dispatch key before retrying.
Because a deleted Job frees its name, a deterministic-name design must also keep a dispatch or result record beyond the TTL boundary. Otherwise a replay long after cleanup looks identical to a first run.
Job creation and dispatch-row recording occur in different systems, so they cannot form one complete transaction. Add deterministic labels and run a reconciliation loop for the case where the response is lost just after the Kubernetes API request. When a PENDING item is stale, do not simply assume that no Job exists; search the Kubernetes API by key and decide whether creation occurred.
Concurrency policy can differ per Interface.
- Allow: use for independent work that is safe to overlap.
- Forbid: hold a new dispatch until the previous Job ends.
- Replace: stop the previous run and replace it. Define partial processing and compensation behavior explicitly.
For most data integrations, Forbid is a safe default, but it can postpone execution forever when a job exceeds the next interval. Set a maximum duration, stale-Job rule, and operator-forced rerun procedure together.
Decide Retry and backoff by layer
Section titled “Decide Retry and backoff by layer”Putting Retry in every layer turns one failure into an explosion of duplicate calls. Separate responsibilities as follows.
| Failure point | Default handling |
|---|---|
| Cron parse or metadata validation | No retry; record a configuration error |
| Transient Kubernetes API error | Limited Control Plane Retry with exponential backoff |
| Image pull or Pod scheduling | Observe Kubernetes state and alert operations |
| Transient external error in batch process | Handle through batch policy or a rerunnable Job |
| Non-idempotent side effect | No automatic Retry; use idempotency and manual confirmation |
backoffLimit specifies how many times a failed Pod is retried. If an external call can already create a side effect, use backoffLimit: 0 and implement business-level deduplication and resume points inside the batch, when that is safer. If input is immutable and the task is fully idempotent, a limited backoffLimit can be appropriate.
Control Plane HTTP Retry and Kubernetes Job Pod Retry are different events. The first asks whether the Job object was created; the second asks whether the container execution failed. Do not merge them into one attempt count. Record dispatchAttempt, podAttempt, and businessAttempt separately.
TTL and cleanup
Section titled “TTL and cleanup”Keeping completed Jobs forever increases API-query and etcd-management pressure. Use ttlSecondsAfterFinished to clean successful and failed Jobs after a defined period. The example uses one day as a placeholder policy; choose the actual value based on audit and incident-analysis retention needs.
TTL is not a replacement for result retention. Before deleting the Job, preserve the following in a Result Store or log system.
- Schedule key,
ifId, image digest or immutable version - Creation, start, and finish timestamps and duration
- Job name, Pod name, and correlation ID
- Exit code, Job condition, and failure reason
- Processed count and external-call statistics
Failed Jobs may be retained longer than successful ones, or results can be stored separately and both Job types can use the same TTL. If a separate cleanup controller exists, record a CLEANED state so a deleted Job is not mistaken for a failure; after the retention boundary, queries should expose the state as “unknown.”
Separate image from config
Section titled “Separate image from config”Put executable code and defaults in the batch image, and keep environment-specific connection information and secrets outside the image.
- Image: batch binary, dependencies, and default entrypoint
- Config: environment-specific endpoint references, feature flags, and timeout profiles
- Secret: credentials, tokens, and private keys
- Runtime metadata:
IF_ID, correlation ID, execution slot, and image version
Do not store raw passwords or tokens in schedule metadata. Even an extensible JSON field such as extraArgs needs an allowlist; validate the range and type of environment names, host aliases, and arguments. If callers can inject arbitrary command, privileged options, host paths, or service accounts, the Scheduler becomes a cluster-control API in practice.
Inject environment configuration into the Job through ConfigMap and Secret references, or through the platform’s external secret provider. Promoting the same image digest while changing only configuration preserves the deployment assumption that “the code is the same and only configuration differs.”
Observability and execution results
Section titled “Observability and execution results”Scheduler logs cannot show how many records the Pod actually processed. Control Plane and Execution Plane must share the same correlation context.
Collect at least these metrics.
scheduler_tick_total,scheduler_tick_lag_secondsdispatch_attempt_total,dispatch_success_total,dispatch_error_totaljob_active,job_succeeded,job_failedjob_duration_seconds,job_queue_delay_seconds- Per-Interface business record count and external-call error count
Write ifId, dispatch key, Job name, Pod name, image version, and attempt as structured log fields. Do not log payloads or credentials by default; mask any diagnostic values that must be recorded. If tracing is available, propagate the correlation ID from Scheduler API through Control Plane and Kubernetes API to the batch-start event.
The execution result model separates dispatch from business execution.
{ "dispatchStatus": "DISPATCHED", "executionStatus": "SUCCEEDED", "ifId": "<interface-id>", "scheduledSlot": "<utc-slot>", "jobName": "<job-name>", "imageVersion": "<immutable-version>", "startedAt": "<timestamp>", "finishedAt": "<timestamp>", "processedCount": 123, "errorCount": 0}DISPATCHED means that the Job was registered with the Kubernetes API, while SUCCEEDED means that the actual batch ended with a successful exit code. Separating these states lets the system correctly classify API timeouts, image-pull failures, Pod evictions, and application exceptions.
Security and permission boundaries
Section titled “Security and permission boundaries”The Scheduler should call the Kubernetes API using a least-privilege ServiceAccount and Role. Limit it to creating, getting, listing, and watching Jobs in the required namespace. Keep Pod exec, Secret read, and cluster-wide resource-management permissions separate.
Also enforce these checks at the Control Plane boundary.
- Ensure
ifIdand label values contain no unsupported characters or excessive length. - Require images to match the approved registry placeholder and repository prefix and to use an immutable-version rule.
- Validate memory, CPU, and Cron expressions for syntax and range.
- Merge only fields that pass the
extraArgsschema and allowlist. - Fix namespace and ServiceAccount through policy instead of letting callers select them.
This prevents the Scheduler API from becoming an indirect path for creating arbitrary Kubernetes workloads.
Operational scenarios and trade-offs
Section titled “Operational scenarios and trade-offs”This design isolates execution and makes versions explicit, but it adds Kubernetes API and state-collection complexity. Decide the following trade-offs in advance.
- If execution volume is very high, limit Job objects and watch events or consider grouping work into batches.
- If many short jobs arrive per second, Pod startup latency may dominate; a queue worker can be more suitable.
- Long-running jobs need a heartbeat and lease to distinguish stale state.
- Record a snapshot of metadata at execution time so a metadata change does not retroactively modify an existing Job.
- When an operator reruns a workload, use a different idempotency key for the new manual run and the original scheduled slot.
Changing a Cron expression does not change the image or configuration of a Job that already exists. The next execution uses the new metadata; changing the current run requires an explicit cancel-and-replace procedure.
Summary
Section titled “Summary”A Kubernetes Job-based Scheduler is not merely a feature that converts Cron into Kubernetes resources. It is an execution model that separates Metadata Store desired state, Control Plane dispatch, Kubernetes workload lifecycle, and Execution Plane business results.
- The Scheduler evaluates schedules and manages Job-creation requests.
- The metadata-to-Job translator maps only validated fields into a Kubernetes spec.
- An idempotency key and concurrency policy control duplicate execution.
- Control Plane Retry and Pod
backoffLimithandle different failures. - TTL cleans Kubernetes objects but does not replace execution-result retention.
- Separating image, config, and secrets allows the same batch release to be promoted safely.
- Correlation IDs, metrics, and structured logs make dispatch and execution observable together.
With these boundaries, schedule changes and batch-image releases do not destabilize the Scheduler itself, and each Integration workload can be executed, traced, and reprocessed independently.