Power Cut Mid-Export? Don't Ship a Half-Written File

The file was halfway written when the service restarted, yet the download link had already been made available to users. Such failures are not as simple as “the

How do you stop a half-written file from reaching users? The short answer

Write the output to a temporary file first, verify it, and only then replace the official entry point.

Your situationWhat to doWhy
Writing output files to a local diskWrite to a temporary file in the same directory, finish and close it, then call os.replaceReplacement controls which name readers see; it does not guarantee the data survives a power cut
Storing outputs in object storageUpload under an immutable object key and update the database pointer only after the upload is verifiedObject storage usually lacks the directory-rename semantics of a local file system
Delivering translated documentsConfirm the saved file is readable and in the correct format before marking the task deliverableFor users, completion ultimately means having a file that can be opened
Testing your release logicTreat the check as a protocol test, not a power-loss experimentOne successful read or write does not prove the system is safe from power loss

If your service writes files and then hands users a download link, a crash or power cut mid-write can leave an incomplete file that users still receive. This guide is for developers and operators who build export or translation pipelines and need to decide when a file counts as delivered.

You will see why the fix belongs at the release boundary rather than in an exception handler around the write. You will also get a release order, a list of states that decide when downloading is allowed, and guidance for local disks, object storage and translated documents.

Why a half-written file is a release problem

In the failure described here, the file was only partly written when the service restarted, yet the download link had already been made available. The problem is not simply that “the file occasionally fails to open”. The system treated an incomplete output as the official result.

  • The root cause is the release boundary: the link went live before the file was complete.
  • The remedy should be designed around that boundary, not just by wrapping the write operation in an exception handler.

Write a temporary file, then replace the official entry point

On a local file system, the common approach is to write a temporary file in the target directory and replace the official file only after it is finished.

Steps on a local file system

  1. Write the output to a temporary file in the target directory.
  2. Finish writing and close the file.
  3. Call os.replace to move it to the official name.

Two points matter here:

  • Same directory: placing the temporary file in the same directory avoids the common issue of cross-filesystem replacement.
  • What replacement does and does not do: atomic replacement determines which name the reader sees. It does not guarantee that the data will persist after a power outage.

Use a state diagram to set the release sequence

A state diagram in this approach does not create or overwrite files. It validates the delivery plan: the official path may be replaced only after writing, closing and content verification have all been completed.

The actual file writer still has to handle exception cleanup, permissions and platform-specific differences.

def publish_plan(written, closed, content_ok, same_filesystem):
    if not written:
        return ("write_temporary",)
    if not closed:
        return ("close_temporary",)
    if not content_ok:
        return ("quarantine_temporary",)
    if not same_filesystem:
        return ("prepare_destination_temporary",)
    return ("replace_destination", "confirm_readable", "mark_ready")

assert publish_plan(False, False, False, True) == ("write_temporary",)
assert publish_plan(True, False, True, True) == ("close_temporary",)
assert publish_plan(True, True, False, True) == ("quarantine_temporary",)
assert "mark_ready" not in publish_plan(True, True, True, False)
assert publish_plan(True, True, True, True)[-1] == "mark_ready"

This is a protocol test, not a power-loss experiment. If you need stronger durability guarantees, you will need to research file and directory synchronisation, disk and file system semantics, and fault injection testing. Do not present one successful read or write as proof that the system is safe from power loss.

Which states allow downloading

Use this table to decide what users can see and what recovery action to take in each state.

product stateexternal visibilityrecovery action
Writing to temporary file in progressdoes not provide a formal linkretry or clean up residual
content validation failedIsolation, no releaseretains debugging information
Replacement completed but read confirmation not yet receivedis not yet marked as successfulchecks the final path
can read and verify the match withprovides the resultrecord version and summary

Do not force-rename objects in object storage

Object storage usually does not have the directory-rename semantics of a local file system, so the local approach does not carry over directly.

  • Use immutable object keys for each uploaded output.
  • Update the formal pointer in your database only after the upload has completed and been verified.
  • If a CDN is involved, consider the cache key and how long the old version is kept.

Translation completion should include file delivery

When OmniDoc (product entry point) returns a processing status for your own product, do not immediately show “processing complete” as if the local download had succeeded. The status alone is not enough.

  • Check the saved file first: confirm that the translated file is readable and in the correct format.
  • Then mark the task deliverable.

For users, completion ultimately means having a file that can be opened.

Before you rely on this

This paper uses synthetic samples to demonstrate the processing method. Before processing important files, please retain the original copies and verify them against the boundaries and acceptance criteria outlined in this document.

📊 At a glance

ApproachWhere it appliesKey point
Temporary file, then os.replaceLocal file systemSame-directory placement; replacement controls the visible name, not persistence after an outage
Immutable object keys, then pointer updateObject storageAvoids forced renaming; update the database pointer after verification
Deliverable check after translationTranslated documentsConfirm the saved file is readable and in the correct format before marking it deliverable

🎯 Which approach fits you?

If you write output files to a local disk

Write to a temporary file in the same directory, close it, and then use os.replace to publish it.

If you store outputs in object storage

Upload under an immutable key and update the database pointer only after the upload is verified.

If you run document translation

Mark the task as deliverable only after confirming the saved file opens and has the correct format.

❓ FAQ

1. Why not just wrap the write in an exception handler?

The core problem is the release boundary: the system treated an incomplete output as the official result, so the fix must control when the file is released.

2. Does os.replace guarantee the data survives a power cut?

No. Atomic replacement determines which name the reader sees, but it does not guarantee the data will persist after a power outage.

3. Does a successful read and write prove power-loss safety?

No. The check described here is a protocol test, not a power-loss experiment, so one successful operation is not proof.

4. Can I rename objects in object storage the way I do on a local disk?

Usually not. Object storage typically lacks the same directory-rename semantics, so use immutable object keys and update the formal pointer after verification.

📝 Summary

A download link should appear only after the file is fully written, closed and verified. Build that order into your release logic, and treat a translated file as deliverable only once it opens correctly.

Try it now: upload a document and get it translated with the layout intact

Reference: Python tempfile

Updated 2026-11-29