Skip to content
mentoor

Topic 5 of 5 · 5 min read

Partial failure and resource cleanup

Goal: Find the failure path that leaves AI-written code in a half-done state and restore consistency.

A multi-step operation can fail in the middle, and AI code almost always writes the steps as if every one will succeed. Review the code by asking what the system looks like if step two throws.

Check yourself · 1 of 3

A function reduces stock, then charges a card, and the charge fails. What is the best structure?

Choose one answer

Why it matters

Take "place an order": save the order, reduce stock, charge the card, send the email. If the charge fails after stock is reduced, the shop has lost inventory and has no sale. If the process crashes between steps, nobody notices until a customer complains. Resource leaks are the quieter cousin: a database connection or file opened and never closed works for hours, then the pool runs dry and the whole service stops.

How to review it

  1. List the steps that change something outside the function: database rows, files, payments, messages, caches.
  2. Pretend each step fails and ask what state remains. Write it down.
  3. Pick a strategy per case:
    • One database, several writes: a transaction, so everything commits or nothing does.
    • Several systems: do the reversible step first, the irreversible one last, and record intent in a table so a job can finish or undo it later. A compensating action, such as refunding a charge, undoes a step that cannot be rolled back.
    • Retries after a crash: make each step idempotent so rerunning is safe.
  4. Check cleanup. Files, sockets, locks and connections must be released on every path. Use with in Python, try/finally in JavaScript and Java, defer in Go, and using in C#.

Before and after

def place_order(cart, card):
    order = db.insert_order(cart)
    db.reduce_stock(cart)
    payment.charge(card, order.total)
    mailer.send_receipt(order)

A declined card leaves the stock removed and the order saved as if it were paid. A reviewed version keeps the database work atomic and puts the irreversible charge at the end:

def place_order(cart, card):
    with db.transaction():
        order = db.insert_order(cart, status="pending")
        db.reduce_stock(cart)
        payment.charge(card, order.total, idempotency_key=order.id)
        db.mark_paid(order)
    queue.enqueue("send_receipt", order.id)

If charge raises, the transaction rolls back. The receipt goes to a queue so an email failure cannot undo a paid order.

What goes wrong

  • Cleanup only on success. conn.close() after the work, but not when the work raises.
  • Catching an error and moving on after half the writes have happened.
  • A transaction around a network call that holds locks while it waits.
  • Temporary files left behind in a loop that fails on item 400.

Examples

The leaked connection

const conn = await pool.getConnection();
const rows = await conn.query(sql);
conn.release();
return rows;

If query throws, release never runs, and after enough errors the pool is empty. Put release in a finally block.

Half a batch

for user in users:
    user.plan = "pro"
    user.save()
    billing.create_subscription(user)

If billing fails on user 50, 49 users are upgraded and one is saved as pro without a subscription. Process each user in its own transaction, log failures, and make the job safe to rerun.

Key points

  • For each step that changes something outside the function, ask what state remains if the next step fails.
  • Use one transaction for several writes to a single database so they succeed or fail together.
  • Across systems, do the irreversible step last, and use compensating actions and idempotent reruns.
  • Release files, connections and locks on every path with with, finally, defer or using.
  • Move non-essential side effects, such as email, out of the critical path into a queue.

Common mistakes

  • Closing resources after the work instead of in finally or with.
  • Assuming a crash cannot happen between two lines.
  • Wrapping a slow external call inside a database transaction.
  • Retrying a half-done operation without making it idempotent.

Check yourself · 2 of 3

Where should a file or database connection be closed so it is released on errors too?

Choose one answer

Check yourself · 3 of 3

Which step belongs last in a multi-step flow that touches several systems?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic