spring-data-pipeline · v1.1.0

Order Data Pipeline

How order CSV files travel from a landing directory into PostgreSQL: detection, registration, event hand-off, orchestrated batch import, validation, reject handling and daily reporting — and what keeps each hop safe under crashes, redeliveries and retries.

Runtime
Java 21 · Spring Boot 3.5
Processing
Spring Batch 5 · Cloud Task 3
Messaging
Cloud Stream 4.3 · RabbitMQ
Orchestration
Spring Cloud Data Flow 2.11
Storage
PostgreSQL · Liquibase

1. Overview

Upstream systems drop order files (*.csv) into a shared inbox directory. The pipeline turns each complete file into exactly one Spring Batch JobInstance, which validates every line, upserts good orders into the orders table and records bad lines in order_rejects. Nightly reporting jobs aggregate both into daily summary tables.

The design is deliberately split into small, independently scalable pieces connected by durable state:

Detect & register

file-poller — a long-running service that notices stable files, de-duplicates them and stages them atomically.

Hand off

A transactional outbox relays an IngestionRequested.v1 event to RabbitMQ with publisher confirms.

Launch

ingestion-event-consumer de-duplicates deliveries via an inbox table and launches the import task through the SCDF REST API.

Process

orders-batch — a short-lived Spring Cloud Task running ordersImportJob (one file per execution) or the summary jobs.

The ingestion_file table is the single source of truth for where every file is in its lifecycle; each component owns a well-defined slice of its state machine.

2. Architecture

Pipeline architecture Producers write CSV files to the inbox. file-poller registers and stages files, writes an outbox event, and relays it to RabbitMQ. ingestion-event-consumer receives the event and launches the orders-import task through Spring Cloud Data Flow. orders-batch reads the staged file, writes orders and rejects to PostgreSQL, and archives the file. Producers upstream systems orders-*.csv Shared volume inbox/ → staging/ duplicates/ file-poller scan · register · stage outbox relay RabbitMQ pipeline.ingestion .requests quorum queue + DLQ ingestion-event- consumer inbox de-dup · launch SCDF server task orchestration orders-import orders-batch (task) ordersImportJob prepare → import → finalize Archive archive/yyyy/MM/dd/ completed files PostgreSQL schema pipeline: ingestion_file · file_identity · file_observation · pipeline_switch · outbox_event · inbox_message · orders · order_rejects · *_daily_summary schema dataflow: SCDF metadata · BOOT3_TASK_* / BOOT3_BATCH_* (job repository, restart state) write scan move publish deliver POST /tasks/ executions/launch spawn read staged file archive on success registry, outbox orders, rejects dataflow
Solid arrows: data and control flow. Dashed arrows: PostgreSQL access (the consumer also reads/writes ingestion_file and inbox_message).

3. Modules

ModuleKindResponsibility
pipeline-schemaLibrary (resources)Liquibase changelogs for all application tables, plus the framework (Batch/Task) changelog. Release tags release-1.0.0, release-1.1.0.
pipeline-commonLibrary (auto-config)Event contract IngestionRequestedEvent, IngestionFileStatus, SafePaths, Checksums, correlation/MDC helpers, schema-compatibility guard, search_path support, ops security.
db-migratorRun-to-completion jobApplies pending Liquibase changeSets (excluding the contract label), then verifies the expected release tag. Runs as a Kubernetes Job / Helm hook before app rollout.
file-pollerLong-running serviceScans the inbox, detects complete files, de-duplicates, stages, writes the outbox event and relays it to RabbitMQ. Exposes the operator API.
ingestion-event-consumerLong-running serviceConsumes IngestionRequested.v1, validates, de-duplicates, and launches the orders-import task via SCDF.
orders-batchSpring Cloud TaskHosts ordersImportJob, ordersDailySummaryJob and rejectDailySummaryJob; the job is selected by spring.batch.job.name.

Supporting assets: orchestration/scdf/scdf.sh (registers the app and defines tasks via the SCDF REST API), deploy/compose/ (local Postgres schemas and an SCDF image with a Java 21 runtime), and samples/input/ (example order files).

4. End-to-end flow

  1. File landsA producer writes orders-2026-10-20.csv into the inbox (in-progress names like .tmp/.part are ignored).
  2. Stability checkEvery 15 s the poller records size and mtime in file_observation. A file qualifies once it is ≥ 30 s old, unchanged across the required number of polls, and (optionally) has a ready marker.
  3. RegisterSHA-256 is computed; an ingestion_file row is inserted as RECEIVED and the identity key is claimed in file_identity. Losing the claim → DUPLICATE.
  4. StageThe file is atomically renamed to staging/<fileId>.csv (duplicates go to duplicates/).
  5. QueueIn one transaction the row becomes QUEUED and an IngestionRequested.v1 event is inserted into outbox_event.
  6. RelayEvery 2 s the outbox relay locks a batch (FOR UPDATE SKIP LOCKED), publishes to RabbitMQ and marks rows published only after a positive publisher confirm.
  7. ConsumeThe consumer validates the event, confines its location to allowed roots, claims the eventId in inbox_message and locks the file row.
  8. LaunchPOST /tasks/executions/launch on SCDF with name=orders-import and arguments=fileId=<uuid> correlationId=…. Row → LAUNCHED with the task execution id.
  9. ImportThe orders-batch task runs ordersImportJob: re-verify the file (path, size, checksum) → PROCESSING; read/validate/upsert in chunks of 500; skipped lines go to order_rejects.
  10. FinalizeThe file is moved to archive/yyyy/MM/dd/; counts are written and the row becomes COMPLETED. On failure it becomes FAILED and can be restarted from the last committed chunk.
  11. ReportNightly, the orders-reporting composed task recomputes the last 7 days of order_daily_summary and reject_daily_summary in parallel.

5. Stage 1 · file-poller

One poll cycle (FilePoller.poll(), cron */15 * * * * * UTC) does four things in order:

  1. Honour the runtime switch — if pipeline_switch['file-poller'].enabled is false, skip. Operators toggle it for all replicas through POST /actuator/poller.
  2. Take the cluster-wide lock — pg_try_advisory_lock on a dedicated connection. Only one replica scans at a time; if a pod dies, PostgreSQL drops the session and releases the lock, so there is no lease to expire.
  3. Recover unfinished registrations — rows left in RECEIVED by a crash are queued if the staged file exists, or marked REJECTED if the file vanished from the inbox.
  4. Scan — list up to max-files-per-poll (100) candidates oldest-first and register the complete ones.

When is a file "complete"?

CheckRuleDefault
Name filterMatches include-glob; not hidden (.-prefixed); not ending in an ignore suffix; regular file only (symlinks, dirs ignored)*.csv; .tmp .part .partial .filepart .crdownload
Minimum agenow − mtime ≥ min-file-age30 s
StabilitySize and mtime unchanged for N consecutive polls (persisted in file_observation, so it survives restarts)1 poll
Ready markerIf ready-marker-suffix is set (e.g. .done), <name>.done must existoff
Hash-time recheckSize/mtime are re-read after hashing; if they changed, registration is abandoned until the next pollalways

Crash-safe registration (FileRegistrar)

StepActionIf the process dies right after…
TX1Insert ingestion_file (RECEIVED) and claim the identity in file_identity; mark DUPLICATE if the claim is lostNext scan finds the row by source_path and resumes staging
MoveAtomic rename into staging/<fileId>.csv (or duplicates/<fileId>-<name>)recoverUnfinished() sees the staged file and queues it
TX2RECEIVED → QUEUED and outbox insert in the same transactionNothing lost: the outbox relay publishes the event

The inbox and staging directories must be on the same filesystem so the claim is an atomic rename. The poller fails fast at startup if they are not, or if any directory is missing or not writable.

Duplicate detection — identity rules

identity-ruleKeyEffect
CHECKSUM (default)sha256:<hash>Same content is a duplicate regardless of file name — robust against re-sends under a new name.
NAME_AND_CHECKSUMname-sha256:<sha(name)>:<hash>A re-sent file with a new name is processed again.
NAME_AND_SIZEname-size:<sha(name)>:<size>Cheap heuristic, no content check.

The primary key of file_identity is the de-duplication point: exactly one file can win the insert … on conflict do nothing race.

Outbox relay (OutboxRelay)

6. Stage 2 · Messaging

Topology

ElementValueNotes
Destination (exchange)pipeline.ingestion.requestsProducer binding ingestionRequests
Consumer group / queuepipeline.ingestion.requests.orders-pipelineQuorum queue; declared by the producer (required-groups) so events are retained even before the consumer first starts
Dead-letter queuepipeline.ingestion.requests.orders-pipeline.dlqQuorum; failed messages are republished with x-exception-* headers
Content typeapplication/jsonEvent type header IngestionRequested.v1

Event contract — IngestionRequested.v1

FieldTypeConstraintMeaning
eventIdUUIDrequiredUnique per event; consumer inbox de-duplication key
fileIdUUIDoptionalSet by the poller; null for external publishers (consumer registers the file itself)
locationstring≤ 1024File path; must resolve inside the consumer's allowed roots
originalNamestring≤ 255Name as delivered (operator visibility)
checksumSha256string[0-9a-f]{64}Content hash
sizeByteslong≥ 0Content size
sourcestring≤ 64Publishing system, e.g. file-poller
correlationIdstring≤ 64End-to-end trace id
occurredAtinstantrequiredWhen the file became available
{
  "eventId": "6f1c…", "fileId": "0b9e…",
  "location": "/data/pipeline/staging/0b9e….csv",
  "originalName": "orders-2026-10-20.csv",
  "checksumSha256": "9a4f…", "sizeBytes": 1834,
  "source": "file-poller", "correlationId": "c2d7…",
  "occurredAt": "2026-10-20T08:15:30Z"
}

7. Stage 3 · ingestion-event-consumer

IngestionRequestHandler processes each delivery with at-least-once semantics:

  1. Validate — Bean Validation on the event and SafePaths.resolveWithin(allowedRoots, location), which rejects .. traversal, paths outside the roots and symlinks escaping a root. Invalid events are never retried.
  2. Claim the message in inbox_message (key: consumer name + eventId) with a 5-minute lease:
    • DONE already → acknowledge and ignore (duplicate delivery);
    • leased by another instance → throw, the binder retries later;
    • otherwise claimed, with an attempt counter.
  3. External events (no fileId) — register a new ingestion_file row directly as QUEUED with identity sha256:<hash>; duplicates are recorded and not launched.
  4. Lock the file row (SELECT … FOR UPDATE), verify that location and checksum match the registration, and skip if status is in LAUNCH_NOT_NEEDED (LAUNCHED, PROCESSING, COMPLETED, DUPLICATE, REJECTED).
  5. Launch the orders-import task via SCDF and, in the same transaction, set the row to LAUNCHED and the inbox entry to DONE.

Failure classification

SituationExceptionBehaviour
Bad payload, schema violation, unsafe path, mismatchInvalidEventExceptionNot retried → DLQ; inbox entry FAILED
SCDF 4xx (unknown definition, rejected request)PermanentLaunchExceptionNot retried → file LAUNCH_FAILED, message to DLQ
SCDF 5xx, timeout, connection error, 429TransientLaunchExceptionRetried: 4 attempts, back-off 2 s × 3 up to 60 s; after the last attempt → LAUNCH_FAILED + DLQ

Launch-then-crash is safe. If the consumer dies after SCDF accepted the launch but before its commit, the redelivered message launches again — and Spring Batch refuses the second execution because the JobInstance identified by fileId is already running or complete.

SCDF launch request

POST {pipeline.dataflow.uri}/tasks/executions/launch
Content-Type: application/x-www-form-urlencoded

name=orders-import
arguments=fileId=0b9e… correlationId=c2d7…,java.lang.String,false
properties=deployer.orders-batch.kubernetes.limits.memory=1Gi   (optional)

→ {"executionId": 42, "schemaTarget": "boot3"}

Only fileId is an identifying job parameter; correlationId is passed as non-identifying so it does not create new JobInstances.

8. Stage 4 · orders-batch — ordersImportJob

A short-lived Spring Cloud Task. One file = one execution = one JobInstance. The job is prepareFile → importOrders → finalizeFile.

Step 1 — prepareFile (tasklet, re-runs on every restart)

Step 2 — importOrders (chunk-oriented, fault tolerant)

ComponentImplementation
ReaderFlatFileItemReader, UTF-8, header verified (BOM-tolerant, case-insensitive), RFC 4180 tokenizer with strict column count, saveState=true for restart
ProcessorOrderValidationProcessor — validates and normalises one line into an OrderRecord
WriterJdbcBatchItemWriter with an idempotent upsert on order_id that only updates when business columns actually changed
Chunk size500 items per transaction
Skip policyInvalidOrderException, FlatFileParseException; limit 1000 per file (exceeded → job fails)
Retry policyTransientDataAccessException, 3 attempts
Skip listenerRejectRecorder writes order_rejects inside the chunk transaction; unique (file_id, line_number) makes replays harmless

Input format

order_id,customer_id,order_date,product_sku,quantity,unit_price,currency
ORD-1001,CUST-001,2026-10-20,SKU-AAA,2,19.99,EUR
ORD-1002,CUST-002,2026-10-20,SKU-BBB,1,249.5,usd
ord-1003,cust-003,2026/10/19,sku-ccc,10,0.3333,GBP

Validation & normalisation rules

FieldRuleReject codes
order_id, customer_id, product_skuRequired; trimmed and upper-cased; must match [A-Z0-9][A-Z0-9_-]{0,63}MISSING_*, INVALID_*
order_dateyyyy-MM-dd or yyyy/MM/dd; not in the future (business zone); not before earliest-order-date (2000-01-01)MISSING_ORDER_DATE, INVALID_ORDER_DATE, FUTURE_ORDER_DATE, ORDER_DATE_TOO_OLD
quantityWhole number, 1 … max-quantity (100 000)MISSING_QUANTITY, INVALID_QUANTITY, QUANTITY_OUT_OF_RANGE
unit_priceDecimal, 0 ≤ price < 1012, at most 4 decimal places; stored at scale 4MISSING_UNIT_PRICE, INVALID_UNIT_PRICE, UNIT_PRICE_OUT_OF_RANGE, UNIT_PRICE_PRECISION
currencyISO-4217 code (upper-cased); optional allow-listMISSING_CURRENCY, INVALID_CURRENCY, CURRENCY_NOT_ALLOWED
Whole lineWrong column count / unparseable quotingMALFORMED_LINE (with a 200-char excerpt)
Derived total_amountunit_price × quantity, rounded HALF_EVEN to the currency's minor units (e.g. JPY → 0 decimals)—

Step 3 — finalizeFile

A job listener sets the MDC (fileId, jobExecutionId, correlationId) for the whole run and marks the row FAILED with the collected failure messages if the job does not complete. fail-on-job-failure=true makes the task exit non-zero so SCDF and Kubernetes see the failure.

9. Reporting jobs & SCDF task definitions

Both summary jobs recompute a sliding window (lookback-days = 7) with an idempotent upsert, so re-runs, retries and late files always converge to the same result.

JobSourceTarget (primary key)
ordersDailySummaryJoborders grouped by date, currencyorder_daily_summary (order_date, currency) — count, total amount
rejectDailySummaryJoborder_rejects grouped by local date (business zone), reason codereject_daily_summary (reject_date, reason_code) — count

Task definitions created by orchestration/scdf/scdf.sh define:

DefinitionDSL (abridged)Purpose
orders-importorders-batch --spring.batch.job.name=ordersImportJobLaunched per file by the consumer
orders-daily-summaryorders-batch … ordersDailySummaryJob, single-instanceStandalone summary
reject-daily-summaryorders-batch … rejectDailySummaryJob, single-instanceStandalone summary
orders-reporting<daily: … || rejects: …>Composed, parallel split; fails if either fails. Scheduled nightly (30 1 * * * UTC) on Kubernetes
orders-reporting-sequentialdaily: … && rejects: …Composed, sequential; rejects run only after the order summary succeeded

scdf.sh commands: register, define, bootstrap (both), schedule, launch-import <fileId>, launch <definition>, execution <id>, executions <definition>. The app is registered with bootVersion=3, so SCDF uses the BOOT3_TASK_* / BOOT3_BATCH_* metadata tables.

10. File lifecycle (ingestion_file.status)

ingestion_file state machine RECEIVED to QUEUED to LAUNCHED to PROCESSING to COMPLETED. RECEIVED can become DUPLICATE or REJECTED. QUEUED can become LAUNCH_FAILED. PROCESSING can become FAILED or REJECTED. FAILED and LAUNCH_FAILED return to QUEUED by operator retry. RECEIVED QUEUED LAUNCHED PROCESSING COMPLETED DUPLICATE REJECTED LAUNCH_FAILED FAILED staged SCDF ok prepare finalize identity taken retries exhausted job failed unsafe / checksum file vanished before staging operator retry: POST /api/files/{id}/retry → QUEUED (new event via outbox)
Blue: in flight · green: success · amber: retryable · red: terminal. A FAILED job restarts from its last committed chunk; PROCESSING → PROCESSING is also allowed so a crashed task can be restarted.
StatusSet byMeaning
RECEIVEDfile-pollerRegistered; file may still be in the inbox
QUEUEDfile-poller / consumer (external)Staged; event in outbox or on the queue
LAUNCHEDconsumerTask execution started via SCDF
PROCESSINGorders-batchJob running
COMPLETEDorders-batchImported and archived; counts recorded
FAILEDorders-batchJob failed; restartable
LAUNCH_FAILEDconsumerLaunch retries exhausted or permanent launch error; retryable
DUPLICATEfile-poller / consumerSame identity as an accepted file; terminal
REJECTEDfile-poller / orders-batchUnsafe, missing, oversized or altered input; terminal

11. Data model (schema pipeline)

TableKeyPurpose
ingestion_fileid (uuid)One row per file seen: source (POLLER/EVENT), names and paths, identity key, SHA-256, size, status (CHECK constraint), attempts, task/job execution ids, record counts, last error, correlation id
file_identityidentity_keyDuplicate-detection claim → file_id
file_observationpathSize/mtime history and stable_count for the stability check
pipeline_switchnameOperator on/off switches shared by all replicas (seeded file-poller = true)
outbox_eventidTransactional outbox (jsonb payload, attempts, next_attempt_at, published_at); partial index on unpublished rows
inbox_message(consumer, message_id)Consumer de-dup, lease, attempts, outcome (LAUNCHED, SKIPPED_*, DUPLICATE_FILE)
ordersorder_idBusiness data: customer, date, SKU, quantity, numeric(19,4) unit price, numeric(19,2) total, currency, source file + line
order_rejectsid; unique (file_id, line_number)Rejected lines with reason code, reason and optional raw excerpt
order_daily_summary(order_date, currency)Daily order count and total
reject_daily_summary(reject_date, reason_code)Daily reject count per reason

Spring Batch / Cloud Task metadata lives in the dataflow schema with the BOOT3_ prefix when SCDF launches the task. Task pods set pipeline.db.search-path=dataflow,pipeline, so a single connection sees both schemas and chunk writes commit atomically with the batch metadata.

12. Reliability guarantees

Failure scenarioWhat happensMechanism
Producer still writing the fileNot picked upIgnore suffixes, min age, unchanged-poll count, hash-time recheck, optional ready marker
Two poller replicasOnly one scans; both may relayPG advisory lock for scanning; SKIP LOCKED for outbox
Poller crashes mid-registrationRegistration resumesThree-step registrar + recoverUnfinished()
Same file sent twice (any name)Second copy → DUPLICATE, moved asidefile_identity primary key
Broker downEvents wait in the outboxPublisher confirms + exponential back-off
Crash between confirm and commitEvent published twiceConsumer inbox de-dups on eventId
Two events for the same fileOne launchRow lock + LAUNCH_NOT_NEEDED statuses
Consumer crashes after launch, before commitRedelivery; second execution refusedJobInstance identity = fileId
SCDF unavailableRetried, then LAUNCH_FAILED + DLQBinder retry/back-off; operator retry
Malicious path in eventRejected, not retriedSafePaths confinement + symlink check
File altered after registrationREJECTEDSHA-256 re-check in prepareFile
Job crashes mid-fileRestart from last chunkReader state in step context; upsert + unique reject key make replays harmless
Too many bad linesJob FAILEDSkip limit (1000)
Overlapping summary runsPreventedsingle-instance-enabled (task lock); idempotent upserts
App deployed before migrationStartup refusedSchema compatibility guard (required Liquibase tag)

13. Schema management

14. Operations & security

Endpoints

ServiceEndpointAccessPurpose
both:8081/actuator/health (liveness, readiness incl. DB), /infoanonymousKubelet probes
both:8081/actuator/prometheusanonymous (configurable)Metrics scrape
file-pollerGET /actuator/pollerOPSSwitch state, outbox backlog, file counts per status
file-pollerPOST /actuator/poller {"enabled": false}OPSPause/resume polling for all replicas
file-pollerGET /api/files?status=&limit=, GET /api/files/{id}OPSInspect files (limit ≤ 500)
file-pollerPOST /api/files/{id}/retryOPSFAILED/LAUNCH_FAILED → QUEUED + new event (409 if not retryable or staged file missing)
consumer/actuator/bindingsOPSInspect/stop/start the Rabbit binding

Security (OpsSecurityAutoConfiguration): stateless HTTP Basic, single in-memory user with role OPS (credentials from PIPELINE_SECURITY_OPS_USERNAME/PASSWORD). The management port 8081 is never exposed through Ingress/Route; use TLS whenever traffic leaves the pod network.

Key metrics

MetricTagsSource
pipeline.poller.cyclesoutcome: completed, locked, disabled, errorfile-poller
pipeline.poller.cycle.duration—file-poller
pipeline.poller.filesoutcome: registered, duplicate, lost, io_errorfile-poller
pipeline.outbox.pending / .published / .failurestypefile-poller
pipeline.ingestion.eventsoutcome: launched, skipped, duplicate_message, duplicate_file, rejected, failed_attemptconsumer
pipeline.ingestion.retries—consumer
pipeline.orders.rejectedreasonorders-batch (OTLP push)
pipeline.files.completed—orders-batch (OTLP push)

Correlation & logging

A correlationId is generated at registration and carried in the ingestion_file row, the event payload, the x-correlation-id message header and a non-identifying job parameter. Every log line includes it via MDC:

INFO [corr=c2d7…] [file=0b9e…] [job=17]  Import completed: written=3 rejected=1

Logs contain line numbers and reason codes only — never full record contents.

15. Configuration reference

Required environment

VariableUsed byMeaning
SPRING_DATASOURCE_URL / _USERNAME / _PASSWORDallPostgreSQL connection (from a Secret)
SPRING_RABBITMQ_*poller, consumerBroker connection
PIPELINE_POLLER_INBOX_DIR / _STAGING_DIR / _DUPLICATES_DIRpollerLanding directories (inbox and staging on the same volume)
PIPELINE_CONSUMER_ALLOWED_ROOTSconsumerDirectories event locations must resolve into
PIPELINE_DATAFLOW_URI, PIPELINE_DATAFLOW_TOKENconsumerSCDF server and optional bearer token
PIPELINE_BATCH_ALLOWED_ROOTS, PIPELINE_BATCH_ARCHIVE_DIRorders-batchReadable input roots; archive destination (empty = leave in place)
PIPELINE_BATCH_TABLE_PREFIX, PIPELINE_TASK_TABLE_PREFIXorders-batchBATCH_/TASK_ standalone; SCDF passes BOOT3_*
PIPELINE_SECURITY_OPS_USERNAME / _PASSWORDpoller, consumerOps API credentials

Tunables (defaults)

PropertyDefaultPropertyDefault
pipeline.poller.cron*/15 * * * * *pipeline.consumer.max-attempts4
pipeline.poller.min-file-age30spipeline.consumer.lease5m
pipeline.poller.required-unchanged-polls1consumer concurrency / prefetch2 / 10
pipeline.poller.identity-ruleCHECKSUMpipeline.dataflow.import-task-nameorders-import
pipeline.poller.max-files-per-poll100pipeline.batch.chunk-size500
pipeline.poller.ready-marker-suffix(none)pipeline.batch.skip-limit1000
pipeline.poller.outbox.relay-interval-ms2000pipeline.batch.retry-limit3
pipeline.poller.outbox.batch-size50pipeline.batch.max-file-size-bytes512 MiB
pipeline.poller.outbox.publish-timeout10spipeline.batch.zoneUTC
pipeline.poller.outbox.max-backoff5mpipeline.batch.summary.lookback-days7

Version constraint. The stack is pinned to Spring Boot 3.5 / Batch 5 / Task 3 because SCDF 2.11 (the last OSS line) understands Boot 3 task apps but not Boot 4 / Batch 6. The SCDF local deployer needs a Java 21 runtime inside its image (deploy/compose/scdf/Dockerfile); on Kubernetes each task runs as its own pod.