Your SFTP upload job sometimes leaves a bank's consumer reading half-written settlement files; how do you make each drop atomic and each retry safe?
answer
- visible from the moment it opens
- a name the reader ignores
- one request publishes the file
- what plain RENAME does on a clash
- a retry after the rename
basics
~20 sUpload under a temporary name the consumer ignores, close it, then rename it to the final name in one request; before retrying, check whether the final file already exists, because plain SFTP rename fails on a clash and posix-rename silently overwrites.
solid answer
~40 sAn SFTP upload creates the file under its final name at once and fills it with many writes, so a poller can read it half-done. I upload to an agreed temporary name — `settle-20261006.csv.part`, or a staging folder on the same filesystem — and rename it when the upload has closed; the rename is one request, so the reader sees either no file or the whole one. SFTP version 3's plain `RENAME` fails if the target exists, while OpenSSH's `[email protected]` extension replaces it atomically; Paramiko and ssh2-sftp-client expose both, and JSch's `rename` uses the extension when the server offers it. For retries, the final name is deterministic per business day, and the job checks it first: a matching file means already delivered, not upload again.
code
python · 18 linesimport paramiko
client = paramiko.SSHClient()
client.load_system_host_keys("ci_known_hosts")
client.connect("sftp.bank.example.com", username="deploy",
key_filename="/run/secrets/deploy_key")
final = "incoming/settle-20261006.csv"
tmp = final + ".part"
try:
sftp = client.open_sftp()
try:
sftp.stat(final)
print("already delivered, nothing to do")
except FileNotFoundError:
sftp.put("out/settle-20261006.csv", tmp)
sftp.posix_rename(tmp, final)
finally:
client.close()go deeper
Recall the pattern: upload under a temporary name the reader ignores, then rename it to the final name once the upload is complete.
Explain why a file is visible while it is written, why one rename request is atomic on one filesystem, and how plain RENAME differs from posix-rename.
Walk every failure point of the job and show that each retry is safe, especially a crash after the rename, using deterministic names and a check before upload.
Frame the drop as a contract with the partner: agreed temporary patterns or markers, deduplication on their side, and who owns a duplicate settlement file.
## Why the consumer sees half a file An SFTP upload is not one operation. The client opens the remote file — creating it, or truncating an existing one — then sends many write requests, and finally closes it. The file exists under the name you opened from the first moment. A consumer at the bank that polls the incoming folder every minute can list it, see `settle-20261006.csv`, and read it while only part of the data has arrived. Nothing in the protocol warns the reader; the only fix is to make the final name appear only when the content is complete. ## Upload, then rename The standard pattern has three steps: 1. **Upload under a temporary name** the consumer is agreed to ignore: a suffix such as `.part`, or a separate staging folder on the **same filesystem** as the incoming folder. 2. **Finish the upload**: close the file, and if the job needs it, confirm the size (Paramiko's `put` stats the file after upload by default) or ask the server to flush to disk (`put -f` in OpenSSH's sftp, which needs the server's `[email protected]` extension). 3. **Rename to the final name** in a single request. Because a rename is one request handled by the server's filesystem, the reader sees either no final file or a complete one. Two conditions keep it that way: both names must be on one filesystem — the SFTP draft allows a server to refuse a rename across filesystems — and the consumer must really ignore the temporary pattern. Agree that pattern with the partner in writing; an atomic rename does not help if their poller picks up `*.part` too. Where a partner cannot filter names, a **marker file** is the usual alternative: upload the data, then upload an empty `settle-20261006.csv.done`, and the consumer acts only on files that have a marker. ## Plain RENAME versus posix-rename | Request | Defined by | Target already exists | |---|---|---| | `SSH_FXP_RENAME` | SFTP version 3 draft | error — the rename fails | | `[email protected]` | OpenSSH extension, advertised in the server's version reply | replaced atomically, like POSIX `rename()` | How the libraries expose this: - **Paramiko**: `SFTPClient.rename()` sends the standard request; `posix_rename()` sends the extension. - **ssh2-sftp-client**: `rename()` expects the target not to exist; `posixRename()` uses the extension and replaces an existing target. - **JSch**: `ChannelSftp.rename()` switches to the extension automatically when the server advertises it with version "1". The difference matters for retries, not for the first delivery. ## Making retries idempotent A job can die at any step, and the retry must be safe from each one: - **Died during upload.** A partial `.part` file is left. The retry opens it again, which truncates it, and writes it fresh. Resuming with `put -a` is tempting but assumes the partial copy matches the local file; a fresh upload of a settlement file is cheaper than a corrupt one. - **Died between upload and rename.** The retry repeats the upload and the rename. Nothing was published, so nothing is duplicated. - **Died after the rename, before the job recorded success.** This is the dangerous one. The file is delivered and the consumer may already have taken it. A plain rename now fails because the target exists; a `posix-rename` overwrites it, and if the consumer had already moved the first copy away, the overwrite becomes a **second delivery**. So the job should **check the final name before uploading**. With a deterministic name — derived from the business date or batch ID, never from the run's clock — a retry can stat the final path, compare size or a checksum the partner exposes, and stop with "already delivered". If the consumer removes files after pickup, that check cannot see them, which is why the partner's side should also deduplicate on the file name or a batch ID inside the file. ```python try: sftp.stat(final) # deterministic name: retry finds the earlier delivery print("already delivered") except FileNotFoundError: sftp.put(local, tmp) # confirm=True stats tmp afterwards sftp.posix_rename(tmp, final) ``` ## Checks before going live - The account may rename in the drop folder; some servers restrict which requests a transfer account may send. - The consumer's ignore pattern is written down on both sides. - Final names are unique and deterministic per business object. - Alerts fire on a non-zero exit or an exception, not only on silence.
- Paramiko's put fails with a stat error on a drop server that moves every new file away the moment it is closed. Why, and what do you change?`SFTPClient.put` defaults to `confirm=True`: after the upload it stats the remote path to compare sizes. If the server has already moved the file, that stat fails although the upload succeeded. Pass `confirm=False` there and rely on the rename's status, or ask the partner to move files only once they carry the final name.
- Why must the temporary file sit on the same filesystem as the final name?A rename within one filesystem only changes a directory entry, which is what makes it atomic. The SFTP draft lets a server refuse a rename between filesystems, so a staging folder on another volume can turn the publishing step into an error. A suffix in the same folder, or a staging folder on the same volume, avoids that.
- Closing the file quickly is enough to stop readers seeing partial data
- SFTP's plain RENAME overwrites an existing target like mv does
- posix-rename makes a retried delivery impossible to duplicate
- Naming files with the run's timestamp makes retries safe
- Resuming every failed upload with put -a is always safe