Skip to content

Lesson 31 of 45 · Persistence, Flow and State

Unit of Work and Identity Map

Intermediate•
lesson•
November 5, 2026•
~12 min read

The second save fails

The command-query separation lesson built a CancelReservationCommandHandler that asks the cancellation policy for the refund, cancels and saves the reservation, and then pays the refund. Here is that handler with the refund recorded as a row in our own database. Refunds is an interface the lesson doesn't show. Its record() method inserts a row into a refunds table, and a queued job sends it to the payment gateway later.

PHP
<?php declare(strict_types=1); namespace App\Reservations; use App\Payments\Refunds; use App\Reservations\Cancellation\CancellationPolicy; use Psr\Clock\ClockInterface; final readonly class CancelReservationCommandHandler { public function __construct( private Reservations $reservations, private CancellationPolicy $policy, private Refunds $refunds, private ClockInterface $clock, ) {} public function handle(CancelReservationCommand $command): void { $now = $this->clock->now(); $reservation = $this->reservations->withId($command->reservationId); $refund = $this->policy->refundFor($reservation->totalPrice, $reservation->stayDates, $now); $reservation->cancel($command->reason, $now); $this->reservations->save($reservation); if (!$refund->isZero()) { $this->refunds->record($reservation->paymentId(), $refund); } } }

If record() throws, the reservation is already cancelled in the database and no refund exists. The problem is that each save or record commits on its own, and the handler has no way to say "these two writes belong together".

Patterns of Enterprise Application Architecture (PoEAA) by Martin Fowler names two patterns for this. A Unit of Work, in his catalog entry, "Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems." An Identity Map "Ensures that each object gets loaded only once by keeping every loaded object in a map. Looks up objects using the map when referring to them." A business transaction here means one use case, which is what one command handler runs.

What a Unit of Work does

Fowler gives the reason in plain terms. Writing to the database after every change "can lead to lots of very small database calls, which ends up being very slow". A Unit of Work instead "keeps track of everything you do during a business transaction that can affect the database. When you're done, it figures out everything that needs to be done to alter the database as a result of your work."

That is three jobs. It remembers which objects you loaded and changed, which you created, and which you deleted. It decides at the end what SQL that adds up to. It sends the SQL together, so the database sees either all of it or none of it.

Doctrine already has one

The Active Record vs Data Mapper lesson showed EntityManagerInterface with find() and flush(). The EntityManager is a Unit of Work. The Doctrine documentation says "A Unit of Work is committed (and a new one started) by invoking EntityManager#flush()", and that "only EntityManager#flush() ever causes write operations against the database to be executed."

Doctrine's page on transactions adds that flush() "wraps all of these changes in a single transaction." So a handler that changes two things and calls flush() once writes both or neither:

PHP
<?php declare(strict_types=1); namespace App\Reservations; use App\Payments\Refund; use App\Reservations\Cancellation\CancellationPolicy; use App\Reservations\Exceptions\ReservationNotFound; use Doctrine\ORM\EntityManagerInterface; use Psr\Clock\ClockInterface; final readonly class CancelReservationCommandHandler { public function __construct( private EntityManagerInterface $entityManager, private CancellationPolicy $policy, private ClockInterface $clock, ) {} public function handle(CancelReservationCommand $command): void { $now = $this->clock->now(); $reservation = $this->entityManager->find(Reservation::class, $command->reservationId->value) ?? throw new ReservationNotFound($command->reservationId); $refund = $reservation->refundFor($now, $this->policy); $reservation->cancel($command->reason, $now); if (!$refund->isZero()) { $this->entityManager->persist(new Refund($reservation->paymentId(), $refund)); } $this->entityManager->flush(); } }

Reservation is the Doctrine entity from the rich domain model lesson, changed the way the command-query separation lesson changed the plain class. Its cancel() returns void. Its fields are private, so the handler can't pass the price and dates to the policy itself. A refundFor(DateTimeImmutable $now, CancellationPolicy $policy): Money query on the entity does that and changes nothing. Refund is a second entity the lesson doesn't show; its constructor takes a PaymentId and a Money. Nothing reaches the database until flush(). The reservation was loaded through find(), so Doctrine is tracking it and finds the changed status on its own. The Refund is new, so it needs persist(). Both statements run inside one transaction.

Call flush() once, at the end of the use case. A flush() after each step splits the Unit of Work back into separate commits.

What an Identity Map does

Fowler describes the bug it prevents: "If you aren't careful you can load the data from the same database record into two different objects. Then, when you update them both you'll have an interesting time writing the changes out to the database correctly."

Doctrine's identity map is part of the same UnitOfWork. The Doctrine documentation says it "will only ever give you access to one instance of the Article with ID 1234", however many times you ask. This class checks it:

PHP
<?php declare(strict_types=1); namespace App\Reservations; use Doctrine\ORM\EntityManagerInterface; final readonly class DoctrineIdentityCheck { public function __construct(private EntityManagerInterface $entityManager) {} public function loadsOneInstance(ReservationId $id): bool { $first = $this->entityManager->find(Reservation::class, $id->value); $second = $this->entityManager->find(Reservation::class, $id->value); return $first === $second; } }

For an id that exists, loadsOneInstance() returns true. Both variables point at the same object, so a change made through one is visible through the other, and flush() has exactly one object to compare against the original row.

Eloquent has no identity map. Every find() builds a new model from the returned row. Two handlers, or two helper classes inside one handler, that each load the reservation get two objects that know nothing about each other. This class uses the Eloquent Reservation model from the rich domain model lesson, whose cancel() takes a reason and the time:

PHP
<?php declare(strict_types=1); namespace App\Reservations; use Psr\Clock\ClockInterface; final readonly class TwoLoadsOfOneReservation { public function __construct(private ClockInterface $clock) {} public function cancelTwice(ReservationId $id): void { $now = $this->clock->now(); $first = Reservation::query()->findOrFail($id->value); $second = Reservation::query()->findOrFail($id->value); // $first !== $second: two objects for one row $first->cancel('Guest changed plans', $now); $second->cancel('Duplicate booking', $now); $first->save(); $second->save(); } }

Both objects loaded a confirmed reservation, so both cancel() calls pass the status check. Eloquent's performUpdate() sends only the attributes that changed on that object. Both changed the same columns, so the row ends up with the reason from $second, and nothing in the code noticed that the guard in cancel() ran against stale state. Had the two objects changed different columns, both updates would have landed, but only because the columns happened not to overlap.

The Laravel version: the handler's transaction

Eloquent offers no Unit of Work either. What Laravel gives you is the database transaction, and the handler uses it to do the Unit of Work's last job: write everything or nothing.

Laravel's DatabaseManager forwards unknown method calls to the default connection (__call() in DatabaseManager.php), and the connection's transaction() method opens a transaction, runs your closure, and commits. If the closure throws, it rolls back and rethrows (ManagesTransactions.php in Laravel 13.x). The handler shouldn't call DB::transaction() directly, because that ties the use case to Laravel's facade. It depends on a small interface instead:

PHP
<?php declare(strict_types=1); namespace App\Framework\Persistence; use Closure; interface Transaction { /** * Run the work. Everything it writes commits together, or nothing does. */ public function run(Closure $work): void; }
PHP
<?php declare(strict_types=1); namespace App\Framework\Persistence; use Closure; use Illuminate\Database\DatabaseManager; final readonly class LaravelTransaction implements Transaction { public function __construct(private DatabaseManager $database) {} public function run(Closure $work): void { $this->database->transaction($work); } }

transaction() takes an optional second argument, $attempts. With the default of 1 the closure runs once. With a higher number Laravel runs the closure again after a failure such as a deadlock, so any closure you pass with more attempts must be safe to run twice.

The adapter needs a binding. This is the ReservationsServiceProvider from the Event Bus lesson with one new line, the Transaction binding at the end of register(), and its two imports:

PHP
<?php declare(strict_types=1); namespace App\Providers; use App\Billing\ChargeStayBalanceCommand; use App\Billing\ChargeStayBalanceCommandHandler; use App\Framework\Bus\CommandBus; use App\Framework\Bus\LaravelCommandBus; use App\Framework\Bus\LogCommandDuration; use App\Framework\Events\EventDispatcher; use App\Framework\Events\LaravelEventDispatcher; use App\Framework\Events\LoggingEventDispatcher; use App\Framework\Persistence\LaravelTransaction; use App\Framework\Persistence\Transaction; use App\Reservations\CheckOutGuestCommand; use App\Reservations\CheckOutGuestCommandHandler; use App\Reservations\Infrastructure\EloquentReservations; use App\Reservations\Infrastructure\QueryBuilderReservationSummaries; use App\Reservations\Reservations; use App\Reservations\ReservationSummaries; use App\Support\SystemClock; use Illuminate\Contracts\Bus\Dispatcher; use Illuminate\Contracts\Foundation\Application; use Illuminate\Support\ServiceProvider; use Psr\Clock\ClockInterface; use Psr\Log\LoggerInterface; final class ReservationsServiceProvider extends ServiceProvider { public function register(): void { $this->app->bind(Reservations::class, EloquentReservations::class); $this->app->bind(ReservationSummaries::class, QueryBuilderReservationSummaries::class); $this->app->bind(EventDispatcher::class, fn (Application $app): EventDispatcher => new LoggingEventDispatcher( $app->make(LaravelEventDispatcher::class), $app->make(LoggerInterface::class), )); $this->app->bind(ClockInterface::class, SystemClock::class); $this->app->bind(CommandBus::class, LaravelCommandBus::class); $this->app->bind(Transaction::class, LaravelTransaction::class); } public function boot(Dispatcher $bus): void { $bus->map([ CheckOutGuestCommand::class => CheckOutGuestCommandHandler::class, ChargeStayBalanceCommand::class => ChargeStayBalanceCommandHandler::class, ]); $bus->pipeThrough([LogCommandDuration::class]); } }

The handler now writes both rows inside one run() call and dispatches its event after the transaction has committed. It asks the policy for the refund before cancelling and reads the payment id through $reservation->paymentId(), as the handler in the command-query separation lesson does:

PHP
<?php declare(strict_types=1); namespace App\Reservations; use App\Framework\Events\EventDispatcher; use App\Framework\Persistence\Transaction; use App\Payments\Refunds; use App\Reservations\Cancellation\CancellationPolicy; use Psr\Clock\ClockInterface; final readonly class CancelReservationCommandHandler { public function __construct( private Reservations $reservations, private CancellationPolicy $policy, private Refunds $refunds, private Transaction $transaction, private EventDispatcher $events, private ClockInterface $clock, ) {} public function handle(CancelReservationCommand $command): void { $this->transaction->run(function () use ($command): void { $now = $this->clock->now(); $reservation = $this->reservations->withId($command->reservationId); $refund = $this->policy->refundFor($reservation->totalPrice, $reservation->stayDates, $now); $reservation->cancel($command->reason, $now); $this->reservations->save($reservation); if (!$refund->isZero()) { $this->refunds->record($reservation->paymentId(), $refund); } }); $this->events->dispatch(new ReservationCancelled($command->reservationId)); } }

If record() throws, the reservation update rolls back with it. The dispatch() line sits outside the closure on purpose. A listener that runs while the transaction is open can read rows that later roll back, as the Domain Events lesson explained. (ReservationCancelled here is the one-field event from the rich domain model lesson; the version that carries the refund goes out the same way.) Queued listeners marked ShouldQueueAfterCommit wait for the commit; dispatching after run() returns gives the same guarantee to synchronous listeners.

To check the rollback, the test below uses a Refunds fake whose record() throws:

PHP
<?php declare(strict_types=1); namespace App\Testing; use App\Billing\Money; use App\Payments\PaymentId; use App\Payments\Refunds; use RuntimeException; final class ThrowingRefunds implements Refunds { public function record(PaymentId $paymentId, Money $amount): void { throw new RuntimeException('The refunds table is unavailable'); } }

The test seeds a confirmed reservation that checks in 30 days from now. It binds FlexibleCancellation from the Strategy pattern lesson, which refunds the full price, so the refund is not zero and record() is reached. It runs the handler, expects the exception, and then reads the row back:

PHP
<?php declare(strict_types=1); namespace Tests\Feature\Reservations; use App\Booking\GuestId; use App\Payments\Refunds; use App\Reservations\Cancellation\CancellationPolicy; use App\Reservations\Cancellation\FlexibleCancellation; use App\Reservations\CancelReservationCommand; use App\Reservations\CancelReservationCommandHandler; use App\Reservations\ReservationId; use App\Reservations\ReservationStatus; use App\Testing\ThrowingRefunds; use Illuminate\Database\ConnectionInterface; use Illuminate\Foundation\Testing\RefreshDatabase; use RuntimeException; use Tests\TestCase; final class CancelReservationAtomicityTest extends TestCase { use RefreshDatabase; public function test_a_failing_refund_leaves_the_reservation_confirmed(): void { $reservationId = ReservationId::next(); $guestId = GuestId::next(); $database = $this->app->make(ConnectionInterface::class); $database->table('guests')->insert(['id' => $guestId->value, 'full_name' => 'Ana Petrovska']); $database->table('rooms')->insert(['id' => 14, 'number' => '214']); $database->table('reservations')->insert([ 'id' => $reservationId->value, 'guest_id' => $guestId->value, 'room_id' => 14, 'check_in' => now()->addDays(30)->toDateString(), 'check_out' => now()->addDays(33)->toDateString(), 'status' => ReservationStatus::Confirmed->value, 'adults' => 2, 'children' => 0, 'price_cents' => 42000, 'currency' => 'USD', 'payment_id' => 'pay_8f3a21', ]); $this->app->instance(CancellationPolicy::class, new FlexibleCancellation()); $this->app->instance(Refunds::class, new ThrowingRefunds()); $handler = $this->app->make(CancelReservationCommandHandler::class); try { $handler->handle(new CancelReservationCommand($reservationId, 'Guest changed plans')); $this->fail('The handler should have thrown.'); } catch (RuntimeException $exception) { $this->assertSame('The refunds table is unavailable', $exception->getMessage()); } $status = $database->table('reservations')->where('id', $reservationId->value)->value('status'); $this->assertSame(ReservationStatus::Confirmed->value, $status); } }

The test seeds the rows the query handler's test seeds, plus payment_id. It assumes the plain Reservation the command-query separation lesson uses, with totalPrice, stayDates, paymentId() and a void cancel(), and a repository that also maps the payment_id column, which the repository lesson's version leaves out. Without the Transaction, the save() would already have committed and the assertion would find a Cancelled reservation. RefreshDatabase runs each test inside a database transaction, so run() here is a nested transaction and Laravel rolls it back to a savepoint instead of a full rollback. The pitfall "Calling a handler inside another transaction" below explains what else that nesting changes.

The same interface works in Symfony. This adapter implements it with EntityManagerInterface::wrapInTransaction(), which in Doctrine ORM 3 has the signature wrapInTransaction(callable $func): mixed. Doctrine's transaction page says it flushes the EntityManager before the commit, so the work you pass in only has to call persist():

PHP
<?php declare(strict_types=1); namespace App\Framework\Persistence; use Closure; use Doctrine\ORM\EntityManagerInterface; final readonly class DoctrineTransaction implements Transaction { public function __construct(private EntityManagerInterface $entityManager) {} public function run(Closure $work): void { $this->entityManager->wrapInTransaction($work); } }

If the work or the commit fails, Doctrine rolls back, closes the EntityManager and rethrows, so a handler that catches the exception must not keep using the same EntityManager.

Pitfalls

Writing your own change tracker. It is tempting to keep a list of "dirty" entities in a base class or a custom Transaction and flush it at the end. Doctrine's UnitOfWork does this with copies of original values, proxies and cascade rules, and a homemade version has to rebuild all of that. If you are on Eloquent, rely on the transaction and on save(), and keep each use case small enough that its handler saves one or two objects explicitly.

Calling flush() in the wrong place. A flush() inside a loop, inside a repository's save() for every call, or in a listener writes a partial Unit of Work. DoctrineReservations::save() in the repository lesson calls flush() because it was written to be called once per handler. If a handler saves three entities through three such repositories, it commits three times. In that case, remove the flush() from the repository and call it from the handler or a Transaction adapter.

Calling a handler inside another transaction. Laravel's transaction() commits only at the outermost level. In Illuminate/Database/Concerns/ManagesTransactions.php, the commit sits behind if ($this->transactions === 1) { (line 52 in Laravel 13.x), and a nested call only lowers the counter. When a caller, a test using RefreshDatabase or DatabaseTransactions, or a bus pipe has already opened a transaction, run() returning is not a commit, and the dispatch() after it sends the event before the data is durable. The guarantee holds only when the handler's run() is the outermost transaction, which is why the Command Bus lesson keeps transactions out of bus pipes.

Treating the transaction as a lock. A transaction makes the writes atomic. It doesn't stop a second request from reading the same reservation at the same time and cancelling it too. Locks and version columns solve that, and are a separate topic.

Letting Doctrine's identity map grow in a long-running worker. The identity map keeps a reference to every entity the EntityManager has loaded. In a web request, PHP throws the map away at the end. In a queue worker or an Octane process, it lives for as long as the process does. Memory grows, and a later job may be handed an entity loaded by an earlier one, which is out of date. EntityManager::clear() empties the map, and Doctrine's documentation says all managed entities "become detached". Symfony's Doctrine bridge ships DoctrineClearEntityManagerWorkerSubscriber, which calls clear() on every manager after a Messenger message is handled or fails (Symfony 8.1 source). I did not verify how a given app registers it, so check that your worker configuration includes it. Outside Messenger, call clear() yourself between jobs.

The one thing to remember

A Unit of Work makes everything a use case changes commit together, and an Identity Map makes sure one row means one object while it runs. Doctrine gives you both, and in Laravel the handler's transaction covers the first.

Course Content