Story #40 Database Transactions · Atomicity · Multi-Step API Operations

The Invoice Header That Survived Without Its Line Items

"The API returned an error. The invoice header still landed in the database"

A billing platform inserted an invoice header and its line items in separate repository calls with no transaction boundary. A constraint failure on one line item returned a 500 error—but the header had already committed. A reporting job counted it as a valid invoice.

What happened

A billing platform exposed an endpoint that created an invoice and its line items. The implementation first inserted the invoice header, then inserted each line item in a separate repository call. A database constraint failure occurred on one line item after the header and earlier items had already been committed.

The API returned a 500 response. The client correctly treated the request as failed and did not notify the customer. However, the incomplete invoice remained in the database. A background reporting job later picked up the header and counted it as a valid invoice, while the finance portal showed a total that did not match its line items.

The team discovered that the service method had no transaction boundary covering all related writes. Unit tests mocked the repository and verified the error response, but never inspected persisted state after a mid-operation failure.

Root cause

Related database changes committed independently despite the API representing them as one atomic operation. Error response assertions did not verify rollback or persisted state.

The fix

The fix moved the related writes into a single transaction and added consistency constraints. Where operations span external systems and cannot share a database transaction, the design uses an explicit recoverable workflow rather than pretending the operation is atomic.

Testing gaps and preventive tests

Inject failures between writes, verify rollback, test constraint violations, and validate reconciliation for intentionally non-atomic workflows. Tests must inspect the durable state after both success and error responses.

Business impact

Incomplete invoices entered financial reporting and required manual cleanup and reconciliation.

Lesson learned

An error response is not proof that the system left no side effects. Tests must inspect the durable state.

The Invoice Header That Survived Without Its Line Items