Architecture

Use an Outbox Pattern for Reliable PHP Background Events

Keep database changes and event publication consistent when a PHP application must notify workers or external systems.

Overview

A common failure occurs when an application commits a database change and then fails before publishing the event that should notify another service. Reversing the order is also unsafe: the event may be published even though the database transaction later rolls back.

Write the event in the same transaction

The transactional outbox pattern stores the business change and an event record in one database transaction. A separate worker reads unpublished events and delivers them.

START TRANSACTION;

UPDATE orders
SET status = 'confirmed'
WHERE id = ?;

INSERT INTO outbox_events (event_type, aggregate_id, payload, created_at)
VALUES ('order.confirmed', ?, ?, CURRENT_TIMESTAMP);

COMMIT;

The order update and outbox insert either commit together or roll back together, assuming both tables use a transactional engine such as InnoDB.

Deliver at least once

A worker claims pending rows, sends the event and marks it delivered. A crash can occur after delivery but before marking the row complete, so the event may be delivered again. Consumers must therefore be idempotent and use a stable event ID.

Manage retries

Track attempts, next retry time and the last error category. Use bounded exponential backoff and move repeatedly failing events to a review state. Avoid retry loops that overwhelm a failing downstream service.

Keep payloads intentional

Store the minimum data needed by the consumer. Consider storing identifiers and letting consumers fetch current state when that better matches the consistency requirements. Version event payloads and avoid including secrets or unnecessary personal data.

Checklist

  • Insert outbox events in the business transaction.
  • Use a transactional storage engine.
  • Give every event a stable unique ID.
  • Assume delivery can happen more than once.
  • Make consumers idempotent.
  • Add retry limits and operational visibility.

References

Transactional Outbox Pattern · MySQL InnoDB Transactions

Share this page Help other developers discover this resource.