Course outline

Django / Correctness and production evidence / Lesson 21

After-commit callbacks and durable work

Schedule follow-up actions after a successful database commit and recognize the remaining delivery gap.

About 21 min read20 worked examples20 practice exercisesContent reviewed
On this page

Lesson goals

  • Explain callback timing for commit, rollback and autocommit.
  • Test registered callbacks without mistaking test isolation for production behavior.
  • Select durable recovery when a post-commit action cannot be lost.
  • Trace callback behavior across commits, savepoints and database connections.
  • Design a durable outbox and verify recovery from ambiguous delivery.

Place work after the commit

A worker that reads a newly created row can run before its transaction commits if a task is sent too early. Djangoโ€™s transaction.on_commit registers a callback for successful commit on the selected connection; callbacks registered inside rolled-back work are discarded. Outside an atomic block in autocommit mode, the callback runs immediately. Identify the database connection and the actual outer transaction before relying on that ordering.

Register a narrow callback

The example creates a synthetic order and registers a callback carrying its identifier. It assumes the Order model and enqueue_order function are defined by the application. The callback runs only after a successful commit; it is not itself part of that transaction. Capture stable identifiers rather than mutable objects where possible, and let the worker reload committed data under its own authorization and failure rules.

python Register a post-commit dispatch
from django.db import transaction

with transaction.atomic():
    order = Order.objects.create(reference='example-42')
    transaction.on_commit(lambda: enqueue_order(order.pk))

Order and enqueue_order are application-defined. The callback is illustrative and does not provide a durable outbox.

Account for failure after commit

A callback exception cannot roll back a transaction that has already committed. A process can also terminate after commit before the follow-up effect is durably accepted. Therefore on_commit prevents an early read but does not ensure that every committed order eventually produces a task. When the intent cannot be lost, persist an outbox record with the order in one database transaction and run a recoverable publisher; make consumers safe for duplicate delivery.

Test callback registration and execution

Django TestCase wraps tests in transactions that are rolled back, so ordinary commit callbacks do not naturally run as a real commit. The example uses captureOnCommitCallbacks to inspect and execute registered callbacks in a focused test. Also test rollback and, where actual commit behavior matters, use an appropriate transaction-level test with the intended database. A captured callback is evidence about the test fixture, not broker delivery.

python Capture callbacks in a Django TestCase
with self.captureOnCommitCallbacks(execute=True) as callbacks:
    create_order()
self.assertEqual(len(callbacks), 1)

The test assumes create_order registers a callback and a suitable fixture exists. Execution here does not prove a real broker accepted a job.

Observe and recover

Record safe operation identifiers and follow-up failure categories without placing payloads or credentials in logs. Define a bounded retry and reconciliation process, and monitor the age of outstanding durable intents if using an outbox. Test a commit followed by callback failure, and a publisher failure after sending but before marking completion. Compare database state and external effects; repeated delivery requires application or provider idempotency.

Locate the actual commit boundary

A transaction is a promise about a database connection, not a promise about a message broker. Suppose a request inserts an invoice and starts a worker before the outer transaction finishes. The worker uses its own connection and can reach the database while the invoice is still invisible. Registering a callback with transaction.on_commit delays dispatch until the connection commits successfully. It does not force an inner atomic block to commit independently: successful nested blocks normally release savepoints while the outer transaction remains open. Trace the whole call stack, including request-level transactions, before deciding when a worker will see the invoice.

Under Django's usual autocommit configuration, registration outside an atomic block runs the callback immediately. A helper cannot assume it always defers execution merely because it uses on_commit. If a caller needs multiple writes to form one unit, that caller must establish the atomic boundary. Conversely, a callback registered in a transaction that rolls back is discarded. That includes callbacks registered after a savepoint which is later rolled back, while callbacks registered before the savepoint can still survive if the outer transaction eventually commits.

Capture values and handle callback errors

on_commit accepts a zero-argument callable. Use functools.partial or bind an immutable identifier when constructing it; passing the result of calling a function would execute the action during registration. A callback should normally carry a primary key or event identifier, not depend on a mutable model instance whose attributes may change before commit. Reloading in a separate worker creates a clear point to handle deletion, authorization, and changed state. A worker may need a snapshot in an outbox payload if the required historical fact cannot be reconstructed from the current row.

Callbacks run in registration order after the successful commit. With the default robust=False, an uncaught callback exception prevents later callbacks for that transaction from running. With robust=True, Django logs exceptions derived from Exception and proceeds to later callbacks. Neither choice makes an external call transactional: the database commit already happened. Design error reporting and recovery around the committed state rather than promising that raising will undo it. Avoid putting slow network calls inside a transaction just to pretend the database and remote system share a rollback.

Reason about separate connections and savepoints

The using argument chooses the database connection whose commit triggers the callback. It must match the connection that stores the row whose visibility matters. For example, registering on default while an order is written inside atomic(using='billing') can execute the callback immediately if default is in autocommit. The billing transaction may still roll back. Passing using='billing' to both the transaction and callback provides the intended ordering on that connection, but Django does not turn two independent database connections into one distributed transaction.

Nested atomic blocks normally create savepoints. Consider registering A in the outer block, registering B in an inner block, then rolling back that inner block and handling the exception outside it. If the outer block later commits, A runs and B is discarded. Catch database errors outside the inner atomic block so Django can roll back its savepoint cleanly before continuing database work. If the outer block subsequently rolls back, neither callback runs. Record the position of registration and every rollback when debugging an apparently missing action.

Persist intent before depending on delivery

There is a failure window between database commit and successful acceptance by a broker or service. The application process may stop before a callback runs; a network timeout may leave it uncertain whether the receiver accepted the request. To preserve a required business event, insert an outbox row in the same database transaction as the business change. If either write fails, both roll back. A separate publisher repeatedly finds committed pending rows, sends their events, and records the outcome. An optional on_commit callback can wake the publisher sooner, but polling or another independent recovery path must still find pending rows when that wake-up is lost.

A publisher can crash after the receiver accepts an event and before the outbox row is marked sent. Retrying is necessary for recovery and can deliver a duplicate. Give the event a stable identifier, make the consumer record processed identifiers atomically with its own database effect, and use an external provider's supported idempotency key where the effect occurs outside that database. A unique constraint is essential to settle concurrent duplicate processing; a preliminary existence check alone races. Design retention, bounded retries, alerts, and manual resolution for poison events rather than silently dropping them.

Test registration, real commits, and recovery separately

Django TestCase normally encloses each test in a transaction that is rolled back, so production callbacks do not naturally execute at the test boundary. captureOnCommitCallbacks can collect callbacks registered within its context and optionally execute them. That is useful to verify registration and arguments, but executing a captured callback is a simulation, not evidence that a real database commit or broker delivery occurred. Use TransactionTestCase with a suitable test database when the test must observe an actual commit, accepting its different isolation and setup cost.

A convincing suite also creates a rollback case and checks both the business row and callback effect are absent. Inject an exception in a callback after a real commit and verify that the business row remains. Exercise a failed publisher before send, an ambiguous send followed by retry, and concurrent duplicate consumption against the production-like database. Compare the persisted event ID and resulting effect count instead of relying on a success log. Operationally, monitor the age and count of pending rows and failed attempts; a quiet callback log alone cannot reveal an intent that was never durably recorded.

20 worked examples

1. Autocommit executes immediately

Problem: Predict the order when no atomic block is active.

  1. There is no open transaction on the default connection under autocommit.
  2. Registration executes the callback before the next append runs.
python Autocommit executes immediately
from django.db import transaction
trace = []
transaction.on_commit(lambda: trace.append("callback"))
trace.append("after")
# trace == ["callback", "after"]

Illustrative Django fragment; a configured application and any named helpers are required.

Expected result: The trace is ["callback", "after"].

Why this result follows: Autocommit causes immediate execution when no transaction is active.

2. Outer commit releases the callback

Problem: Trace a callback registered inside a successful transaction.

  1. Registration queues the callable while the outer transaction remains open.
  2. Leaving the block commits before execution reaches the final append.
python Outer commit releases the callback
from django.db import transaction
trace = []
with transaction.atomic():
    transaction.on_commit(lambda: trace.append("committed"))
    trace.append("inside")
trace.append("outside")
# trace == ["inside", "committed", "outside"]

Illustrative Django fragment; a configured application and any named helpers are required.

Expected result: The trace is ["inside", "committed", "outside"].

Why this result follows: The outer commit triggers the queued callback before control continues.

3. Rollback discards a registered action

Problem: Determine whether an aborted transaction emits its notification.

  1. The exception leaves the atomic block and causes its transaction to roll back.
  2. Django discards the associated callback rather than appending the notification.
python Rollback discards a registered action
from django.db import transaction
trace = []
try:
    with transaction.atomic():
        transaction.on_commit(lambda: trace.append("notify"))
        raise ValueError("abort")
except ValueError:
    pass
# trace == []

Illustrative Django fragment; a configured application and any named helpers are required.

Expected result: The trace remains empty.

Why this result follows: Only a successful commit can release this queued callback.

4. Savepoint rollback preserves the outer callback

Problem: Trace which callback survives a caught inner failure.

  1. The inner exception rolls back its savepoint and discards the inner registration.
  2. The outer block exits successfully, so its earlier callback still runs.
python Savepoint rollback preserves the outer callback
from django.db import transaction
trace = []
with transaction.atomic():
    transaction.on_commit(lambda: trace.append("outer"))
    try:
        with transaction.atomic():
            transaction.on_commit(lambda: trace.append("inner"))
            raise ValueError("abort inner")
    except ValueError:
        pass
# trace == ["outer"]

Illustrative Django fragment; a configured application and any named helpers are required.

Expected result: The trace contains only "outer".

Why this result follows: The two registrations belong to different rollback scopes.

5. Bind a stable identifier

Problem: Avoid late binding when registering multiple order notifications.

  1. Each partial captures the current identifier when the callback is registered.
  2. Successful commit invokes enqueue_order with 11 and then 12 in registration order.
python Bind a stable identifier
from functools import partial
from django.db import transaction
with transaction.atomic():
    for order_id in (11, 12):
        transaction.on_commit(partial(enqueue_order, order_id))

Illustrative Django fragment; a configured application and any named helpers are required.

Expected result: Two calls receive 11 and 12 respectively.

Why this result follows: Binding arguments at registration avoids the loop variable late-binding trap.

6. Inner success still waits

Problem: Determine timing when an inner savepoint succeeds.

  1. The inner atomic block releases a savepoint without committing the outer transaction.
  2. The callback remains queued until the surrounding atomic block successfully exits.
python Inner success still waits
with transaction.atomic():
    with transaction.atomic():
        transaction.on_commit(lambda: trace.append("sent"))
    trace.append("inner exited")
# trace == ["inner exited", "sent"]

Illustrative fragment or trace; application models, fixtures and external services are assumed.

Expected result: The trace contains inner exited, then sent.

Why this result follows: Releasing a savepoint is not the outer database commit.

7. Outer rollback cancels inner work

Problem: Trace a successful inner block followed by outer failure.

  1. The inner block completes but its callback still belongs to the outer transaction.
  2. The later exception rolls back that transaction and discards the pending callback.
python Outer rollback cancels inner work
try:
    with transaction.atomic():
        with transaction.atomic():
            transaction.on_commit(lambda: trace.append("sent"))
        raise ValueError("outer failed")
except ValueError:
    pass
# trace == []

Illustrative fragment or trace; application models, fixtures and external services are assumed.

Expected result: Nothing is appended to the trace.

Why this result follows: Inner success cannot survive a subsequent outer rollback.

8. Registration order

Problem: Find the order of two callbacks following a commit.

  1. Both callbacks are registered on the same connection in a defined order.
  2. A successful outer commit invokes the first registration before the second.
python Registration order
with transaction.atomic():
    transaction.on_commit(lambda: trace.append("first"))
    transaction.on_commit(lambda: trace.append("second"))
# trace == ["first", "second"]

Illustrative fragment or trace; application models, fixtures and external services are assumed.

Expected result: The resulting trace is first, second.

Why this result follows: Django preserves callback registration order for the transaction.

9. Default error stops later callbacks

Problem: Predict the effect of an unhandled callback exception.

  1. The transaction commits before fail runs and raises its exception.
  2. With default robust=False the uncaught exception prevents the second callback from running.
python Default error stops later callbacks
def fail():
    trace.append("first")
    raise ValueError("delivery failed")
try:
    with transaction.atomic():
        transaction.on_commit(fail)
        transaction.on_commit(lambda: trace.append("second"))
except ValueError:
    pass
# trace == ["first"]

Illustrative fragment or trace; application models, fixtures and external services are assumed.

Expected result: The trace contains first only; the committed database work remains.

Why this result follows: Callback failure happens after commit and interrupts later callbacks by default.

10. Robust callbacks allow continuation

Problem: Find what follows a handled robust callback failure.

  1. The robust callback raises an Exception after the transaction commits.
  2. Django logs the failure and proceeds to the next registered callback.
python Robust callbacks allow continuation
def fail():
    trace.append("failed")
    raise ValueError("delivery failed")
with transaction.atomic():
    transaction.on_commit(fail, robust=True)
    transaction.on_commit(lambda: trace.append("next"))
# trace == ["failed", "next"]

Illustrative fragment or trace; application models, fixtures and external services are assumed.

Expected result: The trace contains failed and then next.

Why this result follows: robust=True isolates this callback exception from later callbacks.

11. Match the database alias

Problem: Identify the callback boundary for a billing write.

  1. The invoice is created on the billing connection inside its transaction.
  2. The callback is registered on that same connection and waits for its successful commit.
python Match the database alias
with transaction.atomic(using="billing"):
    invoice = Invoice.objects.using("billing").create(number="INV-7")
    transaction.on_commit(lambda: enqueue(invoice.pk), using="billing")

Illustrative fragment or trace; application models, fixtures and external services are assumed.

Expected result: The enqueue call happens after billing commits, assuming the process survives.

Why this result follows: The using argument binds callback timing to the selected connection.

12. Wrong connection can run early

Problem: Diagnose why a task starts before billing commits.

  1. The default connection is assumed to have autocommit enabled and no active transaction.
  2. Its callback runs immediately even though billing has not exited its atomic block.
python Wrong connection can run early
with transaction.atomic(using="billing"):
    Invoice.objects.using("billing").create(number="INV-8")
    transaction.on_commit(lambda: enqueue("INV-8"), using="default")

Illustrative fragment or trace; application models, fixtures and external services are assumed.

Expected result: The enqueue can precede the billing commit.

Why this result follows: Independent connections have independent transaction and callback state.

13. Capture registration in TestCase

Problem: Inspect one callback without a real commit.

  1. The helper registers one notice callback while TestCase retains its enclosing transaction.
  2. The capture context collects it without executing it because execute is false.
python Capture registration in TestCase
with self.captureOnCommitCallbacks(execute=False) as callbacks:
    register_invoice_notice()
self.assertEqual(len(callbacks), 1)
self.assertEqual(sent, [])

Illustrative fragment or trace; application models, fixtures and external services are assumed.

Expected result: One callback is captured and sent stays empty.

Why this result follows: Capture observes registration without forcing a database commit.

14. Execute a captured callback

Problem: Test a callback effect within a controlled fixture.

  1. The helper registers one callback that appends INV-9 to the synthetic sent list.
  2. The capture context executes it on exit even though TestCase has not committed.
python Execute a captured callback
with self.captureOnCommitCallbacks(execute=True) as callbacks:
    register_invoice_notice()
self.assertEqual(len(callbacks), 1)
self.assertEqual(sent, ["INV-9"])

Illustrative fragment or trace; application models, fixtures and external services are assumed.

Expected result: The list contains INV-9 and one callback was captured.

Why this result follows: execute=True simulates callback execution for this focused test.

15. Prove a real commit separately

Problem: Select an appropriate test base for observing committed rows.

  1. TransactionTestCase permits the explicit outer atomic block to reach an actual commit.
  2. The assertion inside sees no effect, while the assertion after exit sees the callback.
python Prove a real commit separately
class InvoiceCommitTests(TransactionTestCase):
    def test_notice_after_commit(self):
        with transaction.atomic():
            Invoice.objects.create(number="INV-10")
            transaction.on_commit(lambda: seen.append("done"))
            self.assertEqual(seen, [])
        self.assertEqual(seen, ["done"])

Illustrative fragment or trace; application models, fixtures and external services are assumed.

Expected result: The effect occurs after the atomic block completes successfully.

Why this result follows: This test exercises a commit boundary rather than only capturing registrations.

16. Persist an outbox intent

Problem: Make an invoice and its delivery intent atomic.

  1. Both rows are written through the same connection in the same transaction.
  2. A failure before commit rolls back both writes; success leaves a pending recoverable intent.
python Persist an outbox intent
with transaction.atomic():
    invoice = Invoice.objects.create(number="INV-11")
    Outbox.objects.create(event_id="evt-11", invoice_id=invoice.pk, status="pending")

Illustrative fragment or trace; application models, fixtures and external services are assumed.

Expected result: Either neither row commits or both rows commit together.

Why this result follows: The database transaction covers the business row and its durable intent.

17. Lost wake-up is recoverable

Problem: Analyze a committed outbox row after a process crash.

  1. The committed pending row survives even when the optional wake-up is lost.
  2. A separately scheduled poll can discover the same event and attempt delivery.
text Lost wake-up is recoverable
invoice=INV-12
outbox=evt-12,status=pending
commit=success
wake_publisher=process_crashed
periodic_poll=reads evt-12

Illustrative fragment or trace; application models, fixtures and external services are assumed.

Expected result: The publisher can recover evt-12 from the pending outbox.

Why this result follows: Recovery reads persistent intent instead of relying on an in-memory callback.

18. Retry after uncertain acceptance

Problem: Explain why a publisher can send the same event twice.

  1. The receiver accepted the first attempt but the publisher did not persist completion.
  2. The remaining pending row causes a retry carrying the same stable event identifier.
text Retry after uncertain acceptance
event=evt-13
send=receiver_accepted
publisher=crashed_before_mark_sent
restart=retry_evt-13

Illustrative fragment or trace; application models, fixtures and external services are assumed.

Expected result: The receiver may see evt-13 twice.

Why this result follows: An uncertain send cannot safely be treated as definitely unaccepted.

19. Deduplicate a local database effect

Problem: Guard a consumer against two deliveries of one event.

  1. A unique constraint on event_id lets only one competing transaction create the marker.
  2. The marker and account update commit together on the same database connection.
python Deduplicate a local database effect
with transaction.atomic():
    marker, created = ProcessedEvent.objects.get_or_create(event_id="evt-14")
    if created:
        Account.objects.filter(pk=7).update(balance=F("balance") + 5)

Illustrative fragment or trace; application models, fixtures and external services are assumed.

Expected result: Repeated delivery adds 5 once if both attempts use the same event ID.

Why this result follows: The unique marker and effect share one transactional boundary.

20. External side effects need their own key

Problem: Prevent duplicate remote charge attempts after a timeout.

  1. The first timeout does not establish whether the provider performed the charge.
  2. A retry reuses the event key so a supporting provider can recognize the same operation.
text External side effects need their own key
request_1: charge(invoice="INV-15", idempotency_key="evt-15") -> timeout
request_2: charge(invoice="INV-15", idempotency_key="evt-15") -> provider response
assumption: provider supports stable idempotency keys

Illustrative fragment or trace; application models, fixtures and external services are assumed.

Expected result: The provider returns the result of one logical charge under its documented guarantee.

Why this result follows: A stable provider-side key covers the external effect beyond the local transaction.

Common errors and fixes

A worker cannot find a new row

Why it happens
The task was sent before the transaction committed.
How to fix it
Register the dispatch with on_commit on the correct connection.
Prevent it next time
Test a separate worker and transaction visibility.

A callback failure is expected to undo the order

Why it happens
The callback runs after a successful commit.
How to fix it
Handle failure and reconciliation as a separate boundary.
Prevent it next time
Exercise a callback exception and inspect committed state.

A critical action disappears after a crash

Why it happens
An in-memory callback was assumed to guarantee durable delivery.
How to fix it
Persist an outbox intent in the business transaction.
Prevent it next time
Test crash windows and duplicate delivery.

20 practice exercises

1. What happens to a callback registered inside a transaction that rolls back?

Show hint

Follow the rollback scope that contains the registration.

Show worked solution

Django discards the callback associated with the rolled-back work. Verify that neither its effect nor the rolled-back record appears, using a test that represents the relevant transaction boundary.

A callback registered in the rolled-back transaction is discarded. Verify both the missing database row and missing callback effect at the relevant boundary; a captured registration alone does not demonstrate a successful commit.

Check your solution

  • The transactional row is absent after rollback.
  • The registered callback produces no effect.

2. The database commits and the process dies before sending a task. Is on_commit alone sufficient for guaranteed delivery?

Show hint

Separate ordering after commit from persistent delivery intent.

Show worked solution

No. The callback is not a durable message. Persist an outbox intent in the same transaction and use a recoverable publisher; make the consumer safe if the publisher retries after an uncertain send.

No: the in-memory callback may disappear with the process after commit. Store an outbox row with the business write and independently recover pending events; make the receiver safe for duplicate attempts after an uncertain send.

Check your solution

  • The outbox row commits with the business record.
  • A retry retains the event identifier and does not duplicate the receiver effect.

3. A helper registers a callback outside atomic with autocommit enabled. Predict whether a following print runs first.

Show hint

Consider whether there is a transaction to wait for.

Show worked solution

The callback executes immediately during registration, before the following print. Wrap related database changes and registration in atomic when the caller needs them to commit together.

Check your solution

  • Callback effect precedes the print.
  • The explanation explicitly assumes autocommit and no active transaction.

4. Register A outside an inner savepoint and B inside it. The inner block rolls back but the outer commits. Predict both effects.

Show hint

Track the savepoint associated with each registration.

Show worked solution

A executes after the outer commit. B is discarded with the inner savepoint rollback, so the final effect includes A alone even though the exception was caught.

Check your solution

  • A runs once after outer commit.
  • B never runs after the inner rollback.

5. An inner block succeeds and its outer transaction later rolls back. Explain the fate of its registered callback.

Show hint

Inner savepoint release is not a commit.

Show worked solution

The callback is discarded because the containing outer transaction never commits. The successful inner block only releases a savepoint and cannot make its work independent of the outer rollback.

Check your solution

  • No callback effect occurs.
  • The outer rollback cancels the inner registration.

6. A loop registers callbacks using lambda: send(item.pk). Repair it for item IDs 21 and 22.

Show hint

Bind each identifier when registering.

Show worked solution

Use functools.partial(send, item.pk) for each item, or bind the identifier as a lambda default. The callbacks then receive 21 and 22 instead of both reading the final loop value.

Check your solution

  • The first callback carries 21.
  • The second callback carries 22.

7. Two callbacks are registered; the first raises ValueError with robust=False. Determine the second callback and committed row outcomes.

Show hint

Separate callback failure from transaction rollback.

Show worked solution

The first exception stops later callbacks on that transaction under the default behavior. The database row remains committed because the exception occurs after commit, so recovery must handle the missed second effect.

Check your solution

  • The second callback does not execute.
  • The previously committed row still exists.

8. Repeat the previous failure with robust=True for the first callback. Explain what changes and what still requires recovery.

Show hint

Robustness handles callback exceptions, not delivery guarantees.

Show worked solution

Django logs the first Exception and runs the later callback. The failed first action is not automatically retried, and the already committed database change is unaffected by that failure.

Check your solution

  • The later callback is attempted.
  • The failed action needs its own recovery plan.

9. An order is written on database alias sales but its callback uses default. Explain a possible premature dispatch.

Show hint

Each connection maintains independent transaction state.

Show worked solution

If default is in autocommit with no active transaction, its callback runs immediately while sales is still open. Register using sales and write the order on sales to align their boundary.

Check your solution

  • Identify the default connection as the early trigger.
  • Pass using="sales" for both the write boundary and callback.

10. A TestCase helper registers two callbacks. Show how to count them without sending either notification.

Show hint

Use the capture context with execution disabled.

Show worked solution

Enter self.captureOnCommitCallbacks(execute=False), call the helper inside, and assert len(callbacks) equals two after exit. Check the fake sender remains empty; capture does not commit the test transaction.

Check your solution

  • The captured callback count is two.
  • The fake sender records no notifications.

11. A TestCase callback should append ready to a fixture list. Test its execution without claiming a real commit.

Show hint

The capture helper can execute collected callbacks.

Show worked solution

Use self.captureOnCommitCallbacks(execute=True) around registration and assert the list contains ready after the context exits. State that this simulates callback invocation and does not establish real commit or broker delivery.

Check your solution

  • The fixture list contains ready.
  • The test does not claim a real commit occurred.

12. Choose a Django test class for verifying that a callback executes after a real transaction commit.

Show hint

TestCase rolls back its enclosing transaction.

Show worked solution

Use TransactionTestCase and an explicit atomic block on the intended test database. Assert the callback has not fired inside the block and has fired after successful exit, then isolate any external effect.

Check your solution

  • No effect occurs before the block exits.
  • The effect appears following the real commit.

13. A transaction creates invoice INV-20 and a pending outbox event. Explain the result if the second insert fails.

Show hint

Both writes must use the same database transaction.

Show worked solution

The error rolls back the atomic block, leaving neither the invoice nor its outbox event committed. Keep both writes on one connection and let the exception reach the transaction boundary.

Check your solution

  • INV-20 is absent after rollback.
  • Its pending outbox event is also absent.

14. The database commits an outbox event but the process dies before waking the publisher. Design a recovery path.

Show hint

The wake-up should not be the only discovery mechanism.

Show worked solution

Run an independent periodic publisher that scans committed pending outbox rows and retries eligible events. Monitor pending age and failures so a broken poller does not leave the event invisible indefinitely.

Check your solution

  • The pending row survives the process crash.
  • A later poll can discover and attempt that event.

15. A publisher sends event evt-30 and crashes before marking it sent. Explain the retry risk and key choice.

Show hint

The receiver may already have accepted the event.

Show worked solution

Retry the pending event with the same stable event ID because acceptance is uncertain. The consumer or provider must deduplicate the repeated ID; creating a new ID would hide the duplicate relationship.

Check your solution

  • The retry retains evt-30.
  • The design tolerates the receiver seeing it twice.

16. Two consumers receive evt-31 concurrently and both check for a marker before inserting it. Repair the race.

Show hint

An ordinary read followed by insert is not exclusive.

Show worked solution

Enforce a unique constraint on the event identifier and create the marker in the same transaction as the local effect. Handle the losing duplicate without applying that effect a second time.

Check your solution

  • The database enforces uniqueness for evt-31.
  • Only the successful marker transaction applies the effect.

17. A callback sends email after an invoice commit and the email provider times out. Explain what the timeout proves.

Show hint

A timeout is not an acknowledgement of non-delivery.

Show worked solution

The timeout leaves delivery uncertain: the provider may have accepted the email before the response was lost. Record the failure, use a stable idempotency mechanism if supported, and reconcile before unsafe retries.

Check your solution

  • The invoice remains committed.
  • The timeout alone cannot prove the email was unsent.

18. A callback uses a mutable invoice object whose state changes before commit. Propose a safer payload strategy.

Show hint

Distinguish the identifier from a historical snapshot.

Show worked solution

Capture the stable invoice primary key and let the worker reload it when current state is intended. If the historical event matters, persist an explicit snapshot in the outbox during the business transaction.

Check your solution

  • The callback carries a stable identifier.
  • Historical values are persisted when current state is insufficient.

19. A publisher repeatedly fails on one malformed event while new events arrive. Design an operational response.

Show hint

Avoid silent loss and an endless invisible retry loop.

Show worked solution

Record attempt count and failure category, apply bounded retry with backoff, and alert or quarantine the problematic event for investigation. Continue processing independent eligible events where ordering requirements allow it.

Check your solution

  • The failed event remains inspectable.
  • Operators can detect and resolve repeated failure.

20. A team claims captureOnCommitCallbacks proves the broker accepted a message. Explain the evidence gap and add a test.

Show hint

A captured callback can call a fake sender.

Show worked solution

Capture proves registration and, when executed, local callback behavior with its fixture. Add a separate integration test against an isolated broker to verify acceptance, and test recovery from a failed or ambiguous send independently.

Check your solution

  • The unit test does not claim broker acceptance.
  • The integration test uses an isolated broker and checks its result.

Key takeaways

  • on_commit orders a callback after success but does not provide durable delivery.
  • Test commit, rollback, callback failure and duplicate effects separately.
  • Callbacks run only after successful commit of their selected connection.
  • Persist critical intent in the same transaction as the business change.
  • Test duplicate delivery and callback registration at separate boundaries.

Official references