Field note / Java

SFTP File Ingestion That Never Fails Silently

Partial files, duplicate drops, bad rows and files that never arrive. A practical design for SFTP ingestion in Java that tells you when something is wrong.

5 min read

  • Java
  • Spring Boot
  • SFTP
  • Integrations
  • PostgreSQL

SFTP is the integration nobody wants to talk about and every bank, payroll provider and healthcare clearinghouse still uses. It’s boring until the morning someone asks why yesterday’s accounts never showed up, and the honest answer is that the job ran, found nothing, and reported success.

The dangerous thing about file-based integrations is not that they fail. It’s that most of their failures look exactly like success. This post is the design I reach for so that every one of those failures is loud.

The five ways a file feed goes wrong

  1. You read a file while it’s still being written. You process half the rows and move the file to “done”.
  2. The same file arrives twice. A partner re-uploads after a timeout, or renames and re-sends. You import every row twice.
  3. The file is valid but some rows aren’t. One bad date in row 4,812 either kills the whole import or gets skipped without a trace.
  4. The file never arrives. The job runs, the directory is empty, the job exits cleanly. Nobody notices for days.
  5. The import half-finishes. The process dies after inserting some rows. The next run either skips the file or imports the first half again.

A good ingestion pipeline has an explicit answer for each one.

1. Only pick up finished files

Agree on a completion signal with the sender. In order of preference:

  • A marker file: the sender uploads accounts_20261012.csv, then accounts_20261012.csv.done. You only process files that have a marker.
  • Upload-then-rename: the sender writes accounts_20261012.csv.part and renames it when complete. You ignore .part files.
  • Size stability as a last resort: list the file, wait, list again, and only process it if the size and modification time haven’t changed. This works, but it’s a guess, so log it as one.

Then move the file out of the inbox before you process it: inbox/ to processing/. That one move prevents two pollers, or two instances of your app, from grabbing the same file.

2. Make the import idempotent

File names are not identities. Partners reuse them, and a re-sent file may have a new name. Key on content instead:

CREATE TABLE ingested_file (
    id           BIGSERIAL PRIMARY KEY,
    feed         TEXT        NOT NULL,
    file_name    TEXT        NOT NULL,
    sha256       TEXT        NOT NULL,
    status       TEXT        NOT NULL,  -- CLAIMED, IMPORTED, REJECTED
    row_count    INT,
    error_count  INT,
    received_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
    UNIQUE (feed, sha256)
);

Claiming the file is a single insert:

public Optional<Long> claim(String feed, String fileName, String sha256) {
    return jdbc.query("""
            INSERT INTO ingested_file (feed, file_name, sha256, status)
            VALUES (?, ?, ?, 'CLAIMED')
            ON CONFLICT (feed, sha256) DO NOTHING
            RETURNING id
            """,
            (rs, i) -> rs.getLong("id"),
            feed, fileName, sha256)
        .stream().findFirst();
}

An empty result means you’ve seen this exact content before. Move the file to duplicates/, log it, and stop. The database constraint does the work; no “check then insert” race.

3. Validate rows, don’t just parse them

Decide up front which errors reject the whole file and which reject a row:

  • File-level: wrong header, wrong column count, unexpected encoding, a trailer whose record count doesn’t match the body. These mean the file is not what you think it is. Reject it and alert.
  • Row-level: a bad date, an unknown account type, a missing required field. Import the good rows, write the bad ones to a rejection table with the line number and the reason, and report the count.
record RowError(long fileId, int lineNumber, String field, String reason) {}

The rejection report is what the operations team sends back to the partner. Without it, “some rows failed” turns into a week of email.

Also set a threshold. Five bad rows out of ten thousand is a data quality issue. Six thousand bad rows out of ten thousand is a format change on the sender’s side, and you should reject the file instead of importing the four thousand that happened to parse.

4. Alert on what didn’t happen

This is the one most pipelines miss. Every feed has an expected schedule: “the accounts file arrives every business day by 6:00”. Write that down as data:

record FeedExpectation(String feed, LocalTime deadline, Set<DayOfWeek> days) {}

A separate check runs after each deadline and asks one question: is there an IMPORTED row for this feed today? If not, alert. Not on an exception, on an absence.

An ingestion job that found nothing to do should never report the same status as one that imported ten thousand rows.

5. Load into staging, then publish

Never parse straight into the tables the rest of the system reads. Load into a staging table tagged with the file id, validate there, and publish to the live tables in one transaction:

  1. Insert all rows into staging_account with file_id.
  2. Run the row-level validation; move bad rows to the rejection table.
  3. In one transaction: upsert from staging into account, mark the file IMPORTED with its counts, delete its staging rows.

If the process dies at step 1 or 2, the live tables are untouched and the file is still CLAIMED. A cleanup job can safely delete stale staging rows for that file and retry. If it dies during step 3, the transaction rolls back. There is no state in which half a file is live.

6. Keep the evidence

After processing, move the file to archive/ (or rejected/) with the file id in the name, and keep it for as long as your retention policy allows. When someone asks “what exactly did the partner send us on the 12th?”, the answer should be a file, not a reconstruction.

And watch what you log. Files from banks and healthcare partners carry account numbers and personal data. Log file ids, counts and line numbers, not row contents.

The checklist

  • The sender has a completion signal, and you only process complete files.
  • Files move out of the inbox before processing.
  • Imports are keyed on content hash, enforced by a unique constraint.
  • File-level and row-level errors are separate, with a rejection report and a threshold.
  • A missing file raises an alert by its deadline.
  • Data goes through staging and is published in one transaction.
  • Every file is archived, and logs contain ids and counts, not personal data.

None of this needs a framework. It’s a table, a few directories and an honest definition of “done”. The payoff is that when a feed breaks, you hear about it from your monitoring, not from a customer.

← All writing