Laravel / Advanced / Lesson 21
Transactional outbox and delivery recovery
Persist an event intent with a domain write and design a recoverable publisher and idempotent consumer.
On this page
Lesson goals
- Explain the database and broker crash window.
- Persist domain state and an outbox record in one transaction.
- Design bounded publishing, deduplication and recovery evidence.
- Persist domain changes and event intents together while recognizing the broker commit gap.
- Design bounded publisher recovery and consumer deduplication for repeated delivery.
Locate the dual-write gap
A database transaction and a message broker normally do not share one atomic commit. Publishing before a database commit may announce a change that later rolls back; publishing only after commit may lose the event if the process dies before it sends. An outbox records the event intent in the same database transaction as the business change. A separate publisher later sends committed intents. This design improves recoverability but does not make the broker and database one transaction.
Persist the intent with the change
The example assumes an existing orders table and an outbox table on the same database connection, with a unique event_id and suitable columns. A generated event ID is stable for this intent and accompanies all delivery attempts. The transaction either commits both writes or rolls both back on an exception. Validate and authorize the input before entering the transaction; do not put an irreversible network call inside a closure that may be retried.
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
DB::transaction(function () use ($orderId) {
DB::table('orders')->insert(['id' => $orderId]);
DB::table('outbox')->insert([
'event_id' => (string) Str::uuid(),
'event_type' => 'order.created',
'payload' => json_encode(['order_id' => $orderId], JSON_THROW_ON_ERROR),
]);
});
The schema and connection are application prerequisites. The publisher is separate and the event payload here contains only a synthetic identifier.
Claim and publish deliberately
A publisher selects committed pending rows in bounded batches, coordinates ownership with other publishers using database-supported locking or leases, and sends each event to the broker. The exact claim algorithm depends on the database and deployment topology, so test it against the actual engine. If a publisher crashes after sending but before marking the row delivered, it will likely send again. Marking delivered before sending instead risks losing the event.
Make redelivery safe
Consumers must handle duplicate event IDs. In the same consumer-side transaction, insert a unique processed-event marker and apply the associated database change only if the marker was newly inserted. The example shows the conditional shape, assuming a unique constraint on event_id and a compatible insertOrIgnore implementation. A separate external effect still needs its own idempotency mechanism or reconciliation; a database marker cannot atomically control an unrelated provider.
The behavior of insertOrIgnore varies by database and can suppress errors beyond duplicate keys. Verify the engine-specific semantics and inspect failures; prefer an explicit conflict strategy where the database supports one and the application needs narrower handling.
DB::transaction(function () use ($event, $applyDatabaseChange) {
$inserted = DB::table('processed_events')->insertOrIgnore([
'event_id' => $event['event_id'],
]);
if ($inserted === 1) {
$applyDatabaseChange($event);
}
});
The unique event_id constraint and the same database transaction are essential. The callback represents an application-specific database update, not an external call.
Verify recovery and operations
In disposable infrastructure, force failures before commit, after commit but before publish, and after publish but before marking delivery. Check that rolled-back work creates no event, committed intent remains recoverable, and redelivery does not repeat the consumer’s effect. Monitor pending count, oldest pending age and failure categories without exposing payloads. Define retention, poison-message handling, replay permissions and alerts, then periodically rehearse recovery with representative data.
Trace the two independent commit boundaries
A domain database and a message broker ordinarily do not share one atomic commit. If an application publishes order.created before its database transaction commits, a later rollback can leave consumers reacting to an order that does not exist. If it commits the order and then sends directly, a crash between those steps can leave a real order with no event. Draw both timelines before selecting an implementation. The problem is not solved by hiding the broker call in a helper: the failure boundary remains between two separately owned systems.
A transactional outbox records an event intent in the same database transaction and connection as the domain change. If the transaction rolls back, neither the order nor its outbox row should be committed. If it commits, a separate publisher can find the pending row after a process crash. This makes intent recoverable, not magically atomic with the broker. The Laravel 12 fragments here assume the stated tables, uniqueness constraints, broker adapter, and disposable synthetic records. They are illustrative, non-runnable, and have not been executed on a database or broker.
Define durable intent and stable event identity
An outbox row should carry a stable event identifier, type or schema version, minimal payload, creation time, and the status or claim information needed by the application's publisher. The event identity belongs to the business intent, not to a delivery attempt. Validate and authorize the command before writing, then insert the domain change and outbox intent together on the same transactional connection. A unique event identifier protects identity, but the application must also define how an incoming command retried after an uncertain response maps to the same or a new intent.
Keep sensitive data out of payloads when an identifier and authorized lookup suffice, and define schema evolution for consumers. A random identifier generated once for a committed intent can be reused on every publish and replay; generating a new identifier inside every retry defeats consumer deduplication. A transaction closure may be retried under configured database behavior, so do not put an irreversible external call inside it. Test the committed row and payload along with the domain state, and test rollback with neither row present.
Claim bounded work and recover the publish window
A publisher should select committed pending intents in bounded batches and coordinate claims among concurrent publishers using mechanisms supported by the target database and deployment. A claim can use row locking or a lease design, but its safety depends on transaction isolation, lock duration, failure recovery, and the specific engine. Do not claim a particular lock algorithm is portable without testing it. Define how expired claims become eligible, how failed attempts back off, and how a poison event stops consuming unlimited work while remaining visible to operators.
The critical sequence is send, receive the broker's relevant acknowledgment, and then record delivery according to the broker and application contract. If the publisher crashes after the broker accepts the event but before marking the outbox row delivered, retry may publish it again. Marking delivered before a successful send avoids that duplicate at the cost of possible event loss. Preserve the same event_id on retries and test the crash window in disposable infrastructure. Bounded batches, pending age, and clear failure categories support recovery; they do not guarantee that a broker or consumer completed the business effect.
Deduplicate at the owner of each effect
A consumer can receive an event more than once. For a local database effect, insert a unique processed-event marker and apply the change in the same consumer-side transaction, only when the marker is newly inserted. The exact conflict strategy must match the target engine. Laravel's insertOrIgnore can suppress errors beyond duplicate keys on some databases, so do not treat every ignored insert as a harmless duplicate without verifying the engine and failure modes. A duplicate marker and a failed business update must not leave a false completed state; test rollback and repeated delivery with the intended engine.
An email, payment, or other external provider is outside that database transaction. A unique local marker cannot atomically guarantee that a provider sent an email exactly once. A crash before the call, or after the call but before recording success, can leave an uncertain outcome. Use a provider-supported idempotency key where available, or a documented reconciliation and manual-review strategy. Keep the same event identity through replay and define marker retention to cover the required replay window. Never claim that an outbox alone provides exactly-once effects across unrelated systems.
Observe pending work and rehearse recovery
Use disposable infrastructure to force failure before the domain commit, after commit before publish, after broker acceptance before marking delivery, and during consumer processing. Assert the order, outbox row, broker observation where available, processed marker, and final business state at their respective boundaries. Test two publishers competing for bounded work, expired claim recovery, a poison event, and duplicate delivery under the target engine's actual claim design. A fake broker can verify publish intent, but it cannot establish broker durability, network behavior, or real acknowledgment semantics.
Monitor pending count, age of the oldest pending intent, publish failures, retry counts, and consumer outcomes with bounded labels and no sensitive payloads. Define alert thresholds from service objectives and observed workload, retention and cleanup for delivered rows and deduplication markers, and who may authorize replay. A replay must preserve the original event identity and relevant authorization context. Document the tested database, broker, isolation, claims, and failure assumptions. This evidence shows recoverability for a configured path, not a universal exactly-once guarantee.
20 worked examples
1. Publish before rollback
Problem: Show why publishing before the order commit can create a false event.
- The broker has received an event before the database transaction completes.
- The rollback removes the order while the independently published event remains possible.
database transaction: insert order 17
broker: publish order.created for 17
database transaction: rolls back
// Synthetic dual-write timeline.
Illustrative fragment requiring the stated disposable database, publisher, and fixtures; it has not been executed here.
Expected result: A consumer may observe order.created for an order that did not commit.
Why this result follows: A broker send cannot be rolled back automatically with an unrelated database transaction.
2. Crash after commit
Problem: Identify the gap when direct publication follows a database commit.
- The order is durable after commit.
- The process stops before sending and no durable publication intent exists in the fixture.
database: commit order 17
process: crashes before broker send
outbox: none
// Synthetic timeline.
Illustrative fragment requiring the stated disposable database, publisher, and fixtures; it has not been executed here.
Expected result: The order exists but its event can be lost.
Why this result follows: Separate commit and send operations leave a failure window without durable handoff intent.
3. Atomic domain and intent
Problem: Write an order and its outbox event in one local transaction.
- The order and event intent are written on the same database transaction.
- A successful commit makes both rows available to later application work.
DB::transaction(function () use ($orderId, $eventId) {
DB::table('orders')->insert(['id' => $orderId]);
DB::table('outbox')->insert(['event_id' => $eventId, 'event_type' => 'order.created', 'payload' => json_encode(['order_id' => $orderId], JSON_THROW_ON_ERROR)]);
});
// Fixture: both tables share a transactional connection; eventId='evt-17'.
Illustrative fragment requiring the stated disposable database, publisher, and fixtures; it has not been executed here.
Expected result: Order 17 and pending event evt-17 commit together.
Why this result follows: The local transaction couples domain state with recoverable event intent on its connection.
4. Rollback removes intent
Problem: Verify neither order nor outbox row commits after a synthetic exception.
- The exception occurs before the transaction commits.
- The database rolls back both inserts under the stated connection behavior.
DB::transaction(function () {
DB::table('orders')->insert(['id' => 17]);
DB::table('outbox')->insert(['event_id' => 'evt-17', 'event_type' => 'order.created']);
throw new RuntimeException('synthetic failure');
});
// Fixture: same transactional connection and no preexisting rows.
Illustrative fragment requiring the stated disposable database, publisher, and fixtures; it has not been executed here.
Expected result: Neither order 17 nor outbox event evt-17 is committed.
Why this result follows: A failed local transaction cannot leave a committed intent for the rolled-back domain change.
5. Stable event identifier
Problem: Preserve one stable event ID across publisher attempts.
- Both attempts refer to the same committed event intent.
- Keeping evt-17 allows a consumer to recognize repeated delivery.
committed outbox row: event_id=evt-17, order_id=17
publish attempt 1: event_id=evt-17
publish attempt 2: event_id=evt-17
// Fixture: first acknowledgement was uncertain.
Illustrative fragment requiring the stated disposable database, publisher, and fixtures; it has not been executed here.
Expected result: Both messages carry evt-17.
Why this result follows: Event identity must survive delivery attempts to support durable consumer deduplication for the operation.
6. New ID on retry
Problem: See why a new event ID defeats consumer duplicate detection.
- The identifiers differ even though the business intent is unchanged.
- A consumer keyed only by event_id sees two distinct events.
attempt 1: business intent order 17, event_id=evt-A
attempt 2: same intent, event_id=evt-B
consumer uniqueness: event_id
Illustrative fragment requiring the stated disposable database, publisher, and fixtures; it has not been executed here.
Expected result: The same business effect may be applied twice.
Why this result follows: Generating identity per attempt defeats a duplicate guard based on stable event identity.
7. Commit before publication
Problem: Recover a pending intent after a process crash.
- The outbox row is durable because it committed with the order.
- A later publisher can find that pending row and attempt delivery.
database: order 17 and outbox evt-17 commit
process: crashes before broker send
publisher restart: selects committed pending evt-17
Illustrative fragment requiring the stated disposable database, publisher, and fixtures; it has not been executed here.
Expected result: The committed intent remains recoverable after restart.
Why this result follows: Persisted intent closes the post-commit pre-send loss window for this local database design.
8. Crash after broker acceptance
Problem: Retry a pending outbox row after uncertain acknowledgment recording.
- The broker may already have the event while the local row remains pending.
- Retrying the same event ID can send a duplicate to the consumer.
publisher: sends evt-17
broker: accepts evt-17
publisher: crashes before marking delivered
restart: evt-17 is still pending
Illustrative fragment requiring the stated disposable database, publisher, and fixtures; it has not been executed here.
Expected result: The publisher may send evt-17 again.
Why this result follows: A send and its local delivered marker are separate operations, so repeated publication must be expected.
9. Marking before send
Problem: Identify loss caused by marking delivery too early.
- The local marker says delivered even though no send occurred.
- The restart query ignores the row because it is no longer pending.
outbox evt-17: mark delivered
process: crashes before broker send
restart: publisher selects only pending rows
Illustrative fragment requiring the stated disposable database, publisher, and fixtures; it has not been executed here.
Expected result: The event can be lost to the broker.
Why this result follows: Recording delivery before an acknowledged send trades a possible duplicate for possible message loss.
10. Bounded publisher batch
Problem: Limit the amount of pending work selected per publisher pass.
- The query orders pending rows and caps the selected batch at 100.
- A separate claim protocol is still needed when multiple publishers can compete.
$rows = DB::table('outbox')->whereNull('delivered_at')
->orderBy('id')->limit(100)->get();
// Fixture: one publisher; claim and send protocol are handled separately.
Illustrative fragment requiring the stated disposable database, publisher, and fixtures; it has not been executed here.
Expected result: At most 100 pending rows are selected in this pass.
Why this result follows: A bounded batch limits one pass without itself proving exclusive publisher ownership.
11. Competing claims
Problem: Review two publishers using a target-engine claim protocol.
- The design must coordinate ownership before both publishers process the same pending row.
- The actual lock and isolation semantics determine whether the competing claim is excluded.
publisher A: claims pending evt-17 under database-supported lock
publisher B: attempts the same claim concurrently
// Fixture: claim transaction and isolation are configured and tested on the target engine.
Illustrative fragment requiring the stated disposable database, publisher, and fixtures; it has not been executed here.
Expected result: The intended invariant is one active claim for evt-17 under the tested protocol.
Why this result follows: Publisher coordination is an engine-specific concurrency contract, not a property of selecting rows alone.
12. Expired claim recovery
Problem: Make an abandoned publisher lease eligible for controlled retry.
- The original publisher does not complete its claimed work.
- After the declared lease expires, the recovery process may claim the pending event again.
evt-17 claim: owner=A, lease expires at 12:05
A crashes at 12:03
recovery time: 12:06
// Fixture: claim protocol permits reclaim after expiry.
Illustrative fragment requiring the stated disposable database, publisher, and fixtures; it has not been executed here.
Expected result: evt-17 becomes eligible for a bounded retry.
Why this result follows: A lease recovery policy prevents a crashed publisher from leaving pending work permanently stuck.
13. Consumer unique marker
Problem: Apply a local effect only for a newly inserted event marker.
- The first delivery inserts its marker and applies the local database change in the same transaction.
- A repeated event whose marker already exists must not apply that change again.
DB::transaction(function () use ($event, $applyDatabaseChange) {
$inserted = DB::table('processed_events')->insertOrIgnore(['event_id' => $event['event_id']]);
if ($inserted === 1) { $applyDatabaseChange($event); }
});
// Fixture: unique event_id; engine-specific ignore behavior verified.
Illustrative fragment requiring the stated disposable database, publisher, and fixtures; it has not been executed here.
Expected result: One committed marker corresponds to one local effect in the fixture.
Why this result follows: A unique marker and transactional effect coordinate duplicate handling for the consumer’s database.
14. Consumer rollback
Problem: Avoid a false processed marker when the local effect fails.
- The marker insert and local change share the same consumer transaction.
- The exception causes the transaction to roll back both under the stated database conditions.
DB::transaction(function () use ($event) {
DB::table('processed_events')->insert(['event_id' => $event['event_id']]);
applyLocalChange($event); // fixture: throws before commit
});
Illustrative fragment requiring the stated disposable database, publisher, and fixtures; it has not been executed here.
Expected result: No processed marker or partial local effect is committed.
Why this result follows: A failed consumer transaction must not permanently mark unapplied work as complete.
15. insertOrIgnore limitation
Problem: Distinguish a duplicate marker from another ignored database error.
- A zero result is not automatically proof that only a duplicate-key condition occurred on every engine.
- Verify the engine semantics and use a narrower supported conflict strategy when other failures must surface.
$inserted = DB::table('processed_events')->insertOrIgnore(['event_id' => $eventId]);
// Fixture: target engine may ignore errors beyond duplicate keys.
// Application requires narrow conflict handling.
Illustrative fragment requiring the stated disposable database, publisher, and fixtures; it has not been executed here.
Expected result: The application does not classify every ignored insert as a safe duplicate without evidence.
Why this result follows: Database-specific ignore behavior can hide failures beyond the intended deduplication case in this consumer.
16. External email gap
Problem: Explain why a unique marker cannot guarantee exactly-once email.
- The local marker and remote email send do not share one atomic commit.
- A crash can leave uncertainty about whether the provider delivered the message.
consumer: insert local processed marker
provider: send email
consumer: crash before recording provider result
// Local database and mail provider are separate systems.
Illustrative fragment requiring the stated disposable database, publisher, and fixtures; it has not been executed here.
Expected result: Use a provider-supported idempotency or reconciliation contract.
Why this result follows: A database marker cannot atomically control an unrelated external effect owned by the mail provider.
17. Poison event
Problem: Bound repeated publication failure for one unprocessable event.
- The publisher records repeated failure for the same stable event.
- The configured terminal path stops unlimited retries while keeping the intent visible.
evt-17: publish attempt 1 fails
evt-17: publish attempt 2 fails
policy: after configured limit, mark for review and alert
// Synthetic operations trace.
Illustrative fragment requiring the stated disposable database, publisher, and fixtures; it has not been executed here.
Expected result: evt-17 enters the defined review state after the limit.
Why this result follows: A poison-event policy bounds work and preserves evidence for authorized recovery of the event.
18. Pending-age signal
Problem: Observe delayed outbox work without exposing sensitive event payloads.
- The metric summarizes the age of pending work for a declared service.
- Its labels use a bounded vocabulary rather than individual event IDs or payloads.
metric: outbox_oldest_pending_age_seconds
labels: service=orders, outcome=pending
// Fixture: bounded labels; event payloads are not metric labels.
Illustrative fragment requiring the stated disposable database, publisher, and fixtures; it has not been executed here.
Expected result: Operators can detect an aging pending backlog under a defined threshold.
Why this result follows: Pending age is a recovery signal when its population and alert policy are explicitly defined.
19. Replay preserves identity
Problem: Replay a committed event without changing its event ID.
- The replay carries the original durable event identity.
- The existing marker identifies it as already applied under the consumer contract.
authorized replay: event_id=evt-17
consumer marker: evt-17 already processed
// Fixture: retention still covers this replay window.
Illustrative fragment requiring the stated disposable database, publisher, and fixtures; it has not been executed here.
Expected result: The local consumer effect is not applied a second time.
Why this result follows: Stable identity and sufficient marker retention preserve duplicate protection during an authorized event replay.
20. Fake broker limitation
Problem: State what a publisher test using a fake broker establishes.
- The fake captures the event the application requested to publish.
- It does not establish real broker durability, network behavior, or acknowledgment semantics.
$broker = new FakeBroker();
$publisher->publishPending();
$this->assertSame('evt-17', $broker->sent()[0]['event_id']);
// Fixture: fake records calls; no real broker is contacted.
Illustrative fragment requiring the stated disposable database, publisher, and fixtures; it has not been executed here.
Expected result: The test verifies publish intent for evt-17 only.
Why this result follows: A fake isolates application behavior while leaving the actual broker boundary untested.
Common errors and fixes
An event is published for a rolled-back order
- Why it happens
- The broker send occurred before the database committed.
- How to fix it
- Write an outbox intent in the same transaction as the order.
- Prevent it next time
- Test rollback with no committed order or intent.
An event disappears after commit
- Why it happens
- A process died before its separate broker send.
- How to fix it
- Recover committed unsent outbox rows with a publisher.
- Prevent it next time
- Monitor oldest pending age and test the crash window.
A consumer applies the same event twice
- Why it happens
- Redelivery after a publisher crash was not accounted for.
- How to fix it
- Deduplicate using a unique event ID and transactional state change.
- Prevent it next time
- Test duplicate delivery and retain markers for the required replay window.
20 practice exercises
1. The publisher sends an event and crashes before marking it delivered. What should happen on restart?
Show hint
The broker may have accepted the event even though the local marker is still pending.
Show worked solution
The committed pending intent remains eligible for a bounded retry. The event may be sent again, so a consumer must deduplicate its stable event ID. Check both publisher recovery and the consumer’s single durable effect.
After restart the committed pending row remains eligible for a bounded retry, so evt-17 can be published again. Preserve its event ID and make the consumer deduplicate the local effect. Test publisher recovery and the consumer’s durable state separately; the outbox does not make broker and database one transaction.
Check your solution
- The pending event can be retried with the same ID.
- Repeated delivery produces one local consumer effect.
2. Why is a unique database marker insufficient for sending an email exactly once?
Show hint
The local marker and the mail provider do not share an atomic commit.
Show worked solution
The marker and external mail provider do not share an atomic transaction. A crash between the marker and the send, or between the send and recording success, leaves an uncertain outcome. Use provider-supported idempotency or a documented reconciliation strategy.
A crash can happen after the marker but before sending, or after sending but before recording the provider result. A unique database marker cannot resolve that external uncertainty alone. Use provider-supported idempotency or a documented reconciliation and review strategy, and test the failure window with synthetic messages.
Check your solution
- The external atomicity gap is identified.
- A supported idempotency or reconciliation path is defined.
3. An order event is sent before its database transaction rolls back. Explain the inconsistency.
Show hint
The broker does not share the local commit.
Show worked solution
The broker may deliver order.created even though the order transaction later rolls back, so a consumer can react to nonexistent committed state. Write the order and an outbox intent in one database transaction, then publish only committed intents. Test the rollback and assert that neither domain row nor outbox row commits.
Check your solution
- The pre-commit send can announce rolled-back state.
- The transactional outbox rollback leaves no committed intent.
4. An order commits and the process crashes before direct broker send. Design a recoverable handoff.
Show hint
Persist intent with the domain change.
Show worked solution
Insert the order and an outbox row with a stable event ID in the same database transaction. A separate bounded publisher can later find the committed pending row and send it. Test the post-commit pre-send crash in disposable infrastructure, and verify that the publisher recovers the same event identity.
Check your solution
- The committed order has a pending outbox intent.
- A restarted publisher can recover the event.
5. A publisher sends evt-17 then crashes before marking delivery. Predict the restart behavior.
Show hint
The broker may already have accepted the event.
Show worked solution
The committed pending row can be selected again, so the publisher may send evt-17 a second time. Preserve that identifier and require the consumer to deduplicate it. Test publisher recovery and the consumer’s single local effect separately; do not mark delivered before sending merely to avoid duplicates.
Check your solution
- The event remains eligible for retry.
- The consumer does not duplicate the local effect.
6. A publisher marks a row delivered before sending and then crashes. Explain the risk.
Show hint
The local marker can get ahead of the broker.
Show worked solution
The event may be lost because the restart scan no longer considers the row pending even though the broker never received it. Design the acknowledgment and delivered-marker sequence around the actual broker contract, accepting that retries may duplicate delivery. Test the crash window and monitor pending work.
Check your solution
- The premature marker can hide an unsent event.
- The recovery design handles uncertain sends.
7. An outbox row is committed with event_id evt-17. What must retry and replay preserve?
Show hint
Identity belongs to the intent, not an attempt.
Show worked solution
Keep evt-17 unchanged in every publish attempt and authorized replay, along with the relevant operation context. A new identifier could bypass the consumer’s duplicate marker and repeat the effect. Test an uncertain first send followed by replay and assert the consumer treats both messages as the same event.
Check your solution
- All attempts carry evt-17.
- The consumer applies the local effect at most once.
8. Two publishers select pending rows concurrently. What claim evidence is required? explicitly.
Show hint
A select alone may not assign exclusive ownership.
Show worked solution
Choose a bounded claim protocol using locking or leases supported by the actual database and isolation configuration. Test two controlled publishers competing for the same synthetic row on a disposable target-engine instance, including crash and lease recovery. Assert the intended ownership invariant and document engine-specific assumptions.
Check your solution
- Only the intended active claim is granted.
- Crash and claim recovery are tested.
9. A publisher owns a lease but crashes before sending. Define recovery after expiry.
Show hint
An abandoned claim must not remain stuck forever.
Show worked solution
Record enough claim state and a bounded lease so a recovery process can make the committed pending event eligible again after the lease expires. Test a synthetic crash and later reclaim under the target database’s actual clock and locking design. Preserve the original event ID during the retry.
Check your solution
- The abandoned event becomes eligible again.
- The original event identity is retained.
10. A publisher repeatedly fails on one malformed event. Design a poison-event policy.
Show hint
Avoid infinite hot retries while preserving evidence.
Show worked solution
Use a bounded retry and backoff policy, then move the event into a visible failed or review state according to the application contract. Record a safe failure category, alert the appropriate operators, and restrict replay authority. Test that the event is not silently lost and that other pending work can proceed.
Check your solution
- Retries are bounded.
- The failed intent remains visible for review.
11. A consumer receives evt-17 twice. Design a local database deduplication test. independently.
Show hint
The marker and effect need the same transaction.
Show worked solution
Use a unique event_id marker and apply the local business change only when the marker is newly inserted in the same consumer-side transaction. Deliver evt-17 twice against a disposable target database and assert one marker and one effect. Test a distinct event so the guard does not reject all work.
Check your solution
- There is one marker for evt-17.
- The local effect occurs once.
12. A consumer inserts a marker then its local update throws. What must rollback prove?
Show hint
A marker alone must not claim unfinished work.
Show worked solution
Run the marker insert and local database update in the same transaction and force an exception before commit. Assert that neither the processed marker nor a partial update persists, so a later retry can apply the event. State the connection and engine assumptions explicitly.
Check your solution
- No processed marker commits.
- No partial local effect commits.
13. insertOrIgnore returns zero for a marker insert. Why is a duplicate not the only possible explanation?
Show hint
Ignore semantics vary by database.
Show worked solution
Some engines may ignore errors beyond duplicate keys, so a zero result should not automatically be classified as a harmless duplicate without target-engine evidence. Use an explicit conflict strategy where supported and required, and test nonduplicate failure paths. Preserve the transaction and surface unexpected errors.
Check your solution
- The engine’s ignore behavior is verified.
- Unexpected insert failures are not silently treated as duplicates.
14. A unique marker is written before an external email send. Does that prove exactly-once email?
Show hint
The provider is outside the database transaction.
Show worked solution
No. A crash can occur after the marker but before sending, or after sending but before the result is recorded. Use a provider-supported idempotency mechanism or a documented reconciliation and review workflow, preserving the stable event identity. Test the uncertain outcome without sending real email.
Check your solution
- The external atomicity gap is stated.
- An explicit recovery or idempotency contract exists.
15. A transaction callback both inserts an order and calls a broker. Explain the retry risk.
Show hint
An external call cannot be rolled back with the database.
Show worked solution
A database transaction may roll back or be retried while the broker send has already occurred, producing a false or duplicate event. Insert an outbox intent with the order inside the transaction and publish committed rows separately. Test rollback and publisher retry using synthetic records.
Check your solution
- No irreversible broker send occurs inside the retried transaction.
- Committed intent is published separately.
16. An outbox table grows indefinitely after delivery. What lifecycle policy should be designed?
Show hint
Retention and replay needs must be balanced.
Show worked solution
Define retention and cleanup for delivered rows, processed markers, audit requirements, and the maximum supported replay window. Ensure marker retention is long enough that a permitted replay does not bypass deduplication. Test cleanup on disposable synthetic data and avoid deleting pending or unresolved intents.
Check your solution
- Pending intents are not removed by routine cleanup.
- Marker retention covers the declared replay window.
17. A dashboard counts pending rows but cannot show how long work has waited. Add a signal.
Show hint
Age can reveal a stuck backlog even with a small count.
Show worked solution
Track the age of the oldest committed pending intent along with pending count and failure categories, using bounded labels without event payloads. Choose alerts from the service’s observed workload and recovery objective. Test an artificially aged synthetic row and verify the reported population and units.
Check your solution
- Oldest pending age is measured.
- Payloads and unique event IDs are not metric labels.
18. A fake broker captures evt-17 in a publisher test. What remains unproven?
Show hint
A fake observes the application request, not a real broker.
Show worked solution
The test can assert that the publisher attempted to send the expected stable event ID, but it cannot establish broker durability, network behavior, or acknowledgment semantics. Add a separately controlled integration scenario if those guarantees matter, and independently test consumer deduplication.
Check your solution
- Publish intent is asserted.
- Real broker and consumer behavior remain separate.
19. An operator replays an already processed event with a new ID. Explain the defect.
Show hint
A new identity can bypass the marker.
Show worked solution
Preserve the original event ID and relevant authorization context during an approved replay. With the marker retained for the supported replay window, the consumer can recognize a committed prior effect. Test both an already processed event and a previously rolled-back consumer attempt using disposable data.
Check your solution
- Replay uses the original ID.
- A previously committed effect is not duplicated.
20. A crash occurs after domain commit and before publication. List the state assertions for recovery.
Show hint
Check each resource at its own boundary.
Show worked solution
Assert that the synthetic order and pending outbox row are committed, then restart the publisher and observe an attempt carrying the same event ID. Deliver the event twice to the consumer and assert one processed marker and one local effect. Do not claim the fake broker proves real delivery durability.
Check your solution
- The committed intent survives the crash.
- Repeated delivery produces one local consumer effect.
Key takeaways
- An outbox makes committed intent recoverable but permits duplicate delivery.
- Prove recovery and idempotency at each separate effect boundary.
- An outbox makes committed intent recoverable but does not make database and broker one transaction.
- Stable event identity and a transactional consumer marker protect local effects from duplicate delivery.
- External effects need their own idempotency or reconciliation contract.