Why is the Outbox pattern needed when sending an email after creating an order? What does it store?
sobes.tech AI
Answer from AI
The Outbox pattern is used to ensure reliable and atomic message delivery (e.g., email) after creating an order, especially in distributed systems. The main challenge is to guarantee that the email is sent exactly once, even if the service crashes or a failure occurs.
Instead of sending the email immediately, information about the event (e.g., email data) is recorded in a separate table — Outbox. This operation occurs within the same transaction as the order creation, ensuring data consistency.
A separate process or service periodically reads entries from the Outbox, sends the email, and marks the record as processed. This approach ensures reliability and fault tolerance.
The Outbox table stores:
- Event identifier
- Event type (e.g., "OrderCreated")
- Data for sending (payload), such as email, template, parameters
- Processing status (e.g., "pending", "sent")
- Metadata (creation time, sending time, etc.)
Example structure of an Outbox record:
CREATE TABLE outbox (
id UUID PRIMARY KEY,
event_type VARCHAR(255),
payload JSONB,
status VARCHAR(50) DEFAULT 'pending',
created_at TIMESTAMP,
processed_at TIMESTAMP
);