Your [TryFunction] caught the error, and the records you wrote are still in the table. In this webinar, Volodymyr Dvernytskyi (Microsoft MVP, Ukraine) explains how AL actually manages write transactions, and why it differs from the SQL and try/catch habits most developers bring with them. Luc van Vugt moderates.
The session covers five tools that control a transaction: Commit(), [CommitBehavior], if Codeunit.Run, [TryFunction], and [TransactionModel]. It then moves on to raising errors well with ErrorInfo and collectible errors, and ends with a decision map and a review checklist.
The content is based on seven articles Volodymyr contributed to Microsoft’s BCQuality repository. Slides and a demo app with all code samples are on GitHub: Drakonian/rollback-that-wasnt.

What a Transaction Is in Business Central
A transaction is a group of database changes that succeed together or fail together. Posting a customer payment from a journal writes a bank account ledger entry, a customer ledger entry, and G/L entries that balance. All of it is written, or none of it.
In SQL you write BEGIN TRAN and COMMIT yourself. In AL, the runtime does it for you. Nothing happens until the first Insert, Modify, or Delete. That opens the write transaction, and every later write joins it. When execution ends without an error, the runtime commits.
Of the ACID properties, the session focuses on atomicity, because that is the part your AL code controls. Volodymyr shows it with a sales invoice: if posting fails at the G/L step, everything rolls back and the user can fix the setup and post again. If every write were saved immediately, you would get a half-posted invoice, and posting again would create duplicates.
Who Owns the Transaction
The runtime owns it. If an unhandled error occurs, the runtime rolls back to the last commit. An explicit Commit() in the middle splits the work into two transactions. Everything before the commit is final, and a later error only undoes the second part. Calling another codeunit does not start a new transaction.

A rollback undoes inserts, modifies, and deletes on normal tables since the last commit. It does not undo:
- Variables, including a record passed by
varinto a codeunit that failed - Temporary records
- Single-instance codeunit state
- HTTP calls already made, emails already sent, telemetry already emitted
- Anything committed earlier
The base app uses this on purpose. Posting preview runs the real posting inside if Codeunit.Run, while subscribers copy every entry into temporary tables. At the end it raises an intentional error. The real posting rolls back, the temporary copies survive, and those copies are what the preview shows.
Three Ways a Rollback Goes Wrong
Volodymyr groups the bugs into three symptoms, all caused by a wrong guess about what the transaction covers.
1. The rollback that wasn’t
A page action gives a customer a VIP price group. The work is in a [TryFunction] that validates the price group, calls Modify, and then raises an error if the credit limit is zero. The caller shows “Discount not applied” when the function returns false.
For a customer with no credit limit, the user sees the message, but the customer is VIP anyway. The try function caught the error, but the Modify was not undone. The action then ended without an unhandled error, so the runtime committed. This applies to Business Central online. On-premises, writes inside try functions are blocked by default, so you get an error instead.

Other ways to get the same result:
- A
Commit()in an event subscriber you have never seen - A
Commit()added just soif Codeunit.Runis allowed - Clearing collected errors and then continuing
2. The rollback you didn’t want
A service call fails, so the code inserts an error log entry and then raises an error with the same text. The error rolls back the log entry, so the failure is never logged. To make the log survive:
- If you need to continue, write the log after
if Codeunit.Runreturns false. - If you need to stop, send the details to telemetry or write the log from a background session.
- In a test,
asserterroralso rolls back your GIVEN data, so commit the fixture first.
Do not fix it with a Commit() between the insert and the error. The log survives, but so does everything else written so far, which brings you back to the first problem.
3. The rollback that can’t happen
A job queue handler posts a payload to another system over HTTP and then updates the local status. If the local step fails, Business Central rolls back its own changes, but the export already exists on the other side. The job queue retries and the other system receives it twice.
Volodymyr suggests two fixes:
- Outbox pattern: posting only saves a “to send” row, and a job queue entry sends it after the commit.
- Stable request ID: send something like the record’s
SystemId, so the other system can ignore a request it has already seen.
Business Central does this itself: external business events go out only after the commit. He also warns that an HTTP call inside a write transaction holds your locks for the whole call.
Five Tools That Control the Transaction
The tools fall into three groups: where a transaction ends, what an error undoes, and how you prove it in tests.

Commit()
Commit() does not mean “save my part”. Everything written since the last commit becomes final, including your caller’s writes and every subscriber’s writes. It also releases locks.
Legitimate uses:
- A batch checkpoint with a persisted watermark
- Right before
Page.RunModalorif Codeunit.Run, when the state so far is complete - Right before
StartSession, because the background session cannot see uncommitted rows
Anti-patterns are a defensive commit “just to be safe”, committing every 500 rows with progress kept only in memory, committing to silence the write-transaction error, and committing inside event subscribers.

For batch work, Volodymyr shows a checkpoint pattern from BCQuality. The bad version commits every 500 rows and keeps the last processed number in a variable. If it fails at row 1,700, the first 1,500 are committed but the variable is gone, so a retry cannot skip finished work. The good version stores progress in a table, processes one bounded chunk per pass, and saves the watermark in the same transaction as the chunk. His review rule: every Commit() gets a comment saying why everything before it is final.
[CommitBehavior]
[CommitBehavior] controls other people’s commits. Your code writes, raises an integration event, and then fails validation. A subscriber you have never seen calls Commit(). Without the attribute, your partial state becomes final together with the subscriber’s rows, and the later error has nothing left to undo. With CommitBehavior::Ignore the subscriber’s commit does nothing and the error rolls back both. With CommitBehavior::Error the commit itself raises a runtime error.

The four rules:
- With
Ignore,Commit()does nothing. WithError, it raises an error. - It covers the method and everything it calls, until the method exits, even with an error.
- The stricter one wins: a parent’s
Errorbeats a child’sIgnore. - It affects explicit commits only, not the implicit commit at the end of
if Codeunit.Run.
Microsoft uses this in the base app. Sales posting runs the posting lines under Ignore (wrapped in a procedure, with an event to turn it off), and posting preview uses Error, because a single commit would turn a preview into a real posting. Volodymyr recommends Ignore to protect a publisher whose changes must be all or nothing, and Error when a commit would be a correctness bug, such as in previews and dry runs. Use it only where the publisher holds uncommitted writes when the event fires, not on every event.
📖 Docs: CommitBehavior attribute — Microsoft Learn reference, including the note that it does not apply to the implicit commit of Codeunit.Run.
if Codeunit.Run
Volodymyr calls if Codeunit.Run AL’s scoped undo button. When you use the return value, the codeunit gets its own transaction boundary. On success, the runtime commits at the end of the codeunit. On failure, it rolls back, returns false, and GetLastErrorText holds the reason. Without the return value, it is an ordinary call inside the caller’s transaction.
It only works on a clean state. If a write transaction is already open, the runtime refuses the call. The compiler does not catch this.
His “loop trap” example applies VIP pricing to every customer, one if Codeunit.Run per customer, and writes a log row before each run. The first log row opens a write transaction, so the run is refused. The right fix is a read-only outer loop: collect failures in a list in memory and write the log after the loop. Three common wrong fixes:
- Commit before every run: it runs, but you now commit once per row, and the log claims a customer got VIP pricing when the run actually failed.
- Adding [CommitBehavior]: it cannot switch off
Codeunit.Run‘s own commit, and the transaction is still open. if Database.IsInWriteTransaction() then Commit(): it commits your caller’s work without knowing what it is. Use it as a guard that raises an error instead.

[TryFunction]
Catching is not undoing. Microsoft Learn states that database changes made in a try method are not rolled back. Writes inside try functions are allowed by default online and blocked by default on-premises through the DisableWriteInsideTryFunctions server setting. It is only a try call when the return value is used. Otherwise it is an ordinary call, and errors propagate.
Good uses are failures that do not write: parsing HTTP responses, JSON, or XML, checking a filter the user typed, and third-party interop. Wrong uses are wrapping writes, catching and ignoring job queue errors, and adding try functions everywhere “just in case”.
For a try function that writes, Volodymyr gives three fixes:
- Try only the risky read-only part, then write outside the try.
- If you need atomic writes and a catch, use
if Codeunit.Run. - If the operation should stop, do not catch the error. Let it roll back.
📖 Docs: Handling errors using try methods — Microsoft Learn page that describes the rollback and write behavior of try methods.
[TransactionModel]
Tests prove all of this, and the first decision in a test codeunit is the transaction model. It should match the code under test:
- AutoRollback: everything rolls back at the end, and a call to
Commit()causes an error. Use it when the code never commits. - AutoCommit: changes persist, and the runner’s test isolation cleans up. Use it when the code commits, such as posting, job queue, and integrations.
- None: the test itself cannot write, and each page interaction commits on its own like a real client. Use it for UI and read-only tests.

To test the rollback that wasn’t: if the code catches and ignores the error, call it and assert the record is unchanged. If the code raises the error, use asserterror under AutoCommit and then assert no partial state is left. Under AutoRollback, a stray commit raises its own error, asserterror catches that one, and the test passes with the bug still there. Your test design has to follow your transaction design.
Raising Errors Well
The second half of the craft is raising errors so the user can act on them. ErrorInfo lets you separate what the user sees (Message) from troubleshooting detail (DetailedMessage), set telemetry properties, and give context (record ID, field number, page number) for actions in the error dialog:
- Show-it (
AddNavigationAction) opens the right page on the right field. - Fix-it (
AddAction) runs a global method that takes theErrorInfo. The method name is plain text, so a typo fails only at runtime. Reference the codeunit by name so the compiler at least checks that part. - The single-parameter
TestFieldform adds a Show-it action for you.
[ErrorBehavior(ErrorBehavior::Collect)] on a procedure gathers collectible errors and keeps going. At the end, unhandled collected errors become one error and the transaction rolls back. Non-collectible errors still stop execution at once. The demo shows one dialog that lists three problems in an import, instead of three separate runs.
There is a collectible version of the rollback that wasn’t. An import inserts staging lines, collects four errors, calls GetCollectedErrors(true) to read and clear them, shows a message, and exits. With no error left, the runtime commits the staging lines anyway, and the next run hits a duplicate key. Clearing errors is not handling them. Either raise the summary as one error, or clear inside if Codeunit.Run.
📖 Docs: Collecting errors — Microsoft Learn guide to ErrorBehavior::Collect, including the warning that clearing collected errors does not roll back database changes.
All of It in One Real Procedure
Volodymyr closes the technical part with the dispatcher from his open-source library Parallel Worker, which runs AL work in parallel background sessions. The dispatcher marks a chunk as running and commits with a comment explaining why. It clears the error buffer and calls the worker through if Codeunit.Run. If the worker fails, the boundary rolls back its writes. The dispatcher reads the error first, re-reads the record (because the variable is not rolled back), marks the chunk failed, and commits again. The worker runs through a wrapper marked [CommitBehavior(CommitBehavior::Error)], so a worker that calls Commit() fails instead of breaking the undo.
Decision Map and Ship Checklist
The talk includes a decision map that asks questions such as “Has your code already written records when the error can happen?” and “Should those records be undone?” and leads to the right tool. The interactive version is in the slides on GitHub.
The checklist for code review:

- No
Insert,Modify, orDeleteinside a[TryFunction]. - Every
Commit()has a comment that says why. - To skip a failed record and continue, run each one in
if Codeunit.Runwith nothing written before the loop. - Events raised before your changes are final carry
[CommitBehavior]. - Error logs are written after the rollback, never just before the error.
ClearCollectedErrors()orGetCollectedErrors(true)is followed by an error, or sits insideif Codeunit.Run.- Job queue codeunits let errors fail the entry.
- Tests for code that commits use
AutoCommit, and one checks that nothing is left after a failure.
His five lines to take home:
- Catching is not undoing.
Commit()doesn’t mean “save my part”. It means “everything so far is final”.if Codeunit.Runis AL’s scoped undo button, and it only works on a clean slate.- Other people’s commits are promises you never made.
- Clearing errors isn’t handling them.
📖 Resource: microsoft/BCQuality — the repository with the transaction and error-handling articles this session is based on (pull request #11). It can be installed as a plugin so AI code-review agents can link rules to articles.
Q&A
Luc asked whether CommitBehavior::Ignore should be the default on publishers. Volodymyr said it might be good in theory, but a lot of code in the base app, the system application, and partner extensions relies on the current behavior, so backward compatibility would be a problem.
Luc also asked about the on-premises versus online difference for try functions. Volodymyr confirmed it is a server (NST) setting in both cases. On-premises defaults to blocking writes inside try functions, and you can change it. Online allows the writes, does not undo them, and you cannot change the setting.
Asked whether the presentation is available, Volodymyr published the slides and demo app at github.com/Drakonian/rollback-that-wasnt. You can find more of his writing at vld-bc.com.
This post was drafted with AI assistance based on the webinar transcript and video content.
