The order has been successfully written to the database, but the “publish order” event failed. The page displays “purchase successful,” but the warehouse system receives no tasks. Conversely, if the event is published first and then the database is updated, the warehouse might process an order that doesn’t actually exist. This isn’t due to insufficient retry attempts, but rather a lack of shared transactions between the two systems.
The goal of the transaction mailbox is quite simple: to keep both “the business change has occurred” and “the need to notify someone about this” together in a single, reliable location, and then to allow an independent process to deliver the notification. It doesn’t guarantee that the message will only be delivered once, but it does ensure that undelivered notifications can be found and recovered.
Incorporate the Intended Delivery into Business Transactions
When creating an order, a corresponding message record is also inserted, containing at least the following information: event identifier, aggregation identifier, event type, payload, creation time, and delivery status. Both insertions are performed within a single database transaction. If the transaction fails, neither record exists. If the transaction succeeds, even if the application subsequently exits, the event is still persisted and awaits processing.
BEGIN;
INSERT INTO orders (id, status) VALUES ($1, 'created');
INSERT INTO outbox (id, aggregate_id, event_type, payload)
VALUES ($2, $1, 'order.created', $3);
COMMIT;
The event payload should not simply copy entire user profile rows. Consumers only need the product and quantity information, and should not broadcast contact phone numbers, addresses, and payment information along with it. The payload should have a version, and subscribers should not rely on all fields from the sender’s database table.
The fact that the order creation event description has been submitted is established. The payload fields are determined by the consumer task, and the entire “orders” row is not copied. There are two versions of the event: one explains the structure of the fields, and the other explains the order of changes to the order. Consumers parse based on the supported event version. If an unknown version is encountered, it enters a diagnostic failure state instead of arbitrarily ignoring the fields and continuing to process. The schema validation format and business validation confirm the status transition is reasonable.
The event ID is determined when a business transaction is created, and subsequent deliveries and retransmissions use the same ID. Duplicate event removal relies on this stable identity. When a payload is corrected, there should be a rule to determine if it still belongs to the same event: correcting encoding errors may retain the identity, while changing business facts typically requires a new correction event. Silently overwriting historical payloads would make it impossible for consumers to perform duplicate removal and auditing.
The inbox and order must be within a genuine transactional boundary. Separate database connections or independent services each starting a transaction do not constitute a shared, atomic transaction. Asynchronous sending within ORM hooks does not equate to a persistent intent. Verify the actual relationship between transaction commit and data persistence. Fault tolerance testing can halt between two writes to verify that both are rolled back together. Pattern names cannot substitute for actual data guarantees.
Still encountering a crash window after successful submission
The sender reads un-sent events and sends them to the messaging system. Once the system confirms receipt, the sender marks the event as delivered. If the messaging system has already received the event, but the previous process has crashed, the next scan will re-send it. This issue cannot be resolved by “marking before sending” because that would re-introduce the possibility of message loss.
Therefore, consumers must accept at least one delivery attempt. Using event identifiers as the basis for deduplication, the “processed record indicator” and “execute local business changes” are placed within the same transaction. Writing the deduplication indicator first, followed by the action, may result in permanent loss of processing if there is a failure; writing the indicator first, followed by the action, may result in repeated execution if there is a failure. The atomic boundary remains the core principle.
If consumers still need to call third-party interfaces, the problem of crossing boundaries reappears. The third party’s idempotency key, the consumer’s own inbox, or the ability to query the status of operations, could all be part of the recovery solution. Don’t expand the local database’s deduplication guarantee to encompass the entire system’s “exactly once” guarantee.
After a consumer receives an event, it attempts to insert a processing identifier and perform local state changes within the same database transaction. A unique constraint conflict indicates that a processing operation already exists, and either returns the existing result or confirms the operation without re-executing it. The event identifier should be associated with the consumer’s name or operation scope to prevent a single consumer’s deduplication from incorrectly blocking a legitimate consumer. The idempotent table is not a universal switch shared across the entire organization.
If external notifications are required, you can create a local “sent” inbox and use it recursively with reliable boundaries. If the vendor supports idempotent calls, you can also bind the same event identity. Increasing the boundaries will increase latency and operational costs, so the decision should be based on the actual task requirements. At least one delivery does not guarantee that the business process is complete, and long-term failures still require reconciliation and manual recovery. The system provides recoverable facts, but does not claim that network side effects naturally occur only once.
When merging in a non-deterministic order, version checking can reject outdated events or wait for missing ranges, but the specific strategy depends on whether the event contains complete state information. If an incremental event is missing a range, it may not be possible to continue; a full-state event may be acceptable with an updated version. Do not ignore all missing ranges simply because there is a version field. Record the last applied version and the missing range to provide a recovery or replay path, so the consumer knows how to recover.
Competitive Bidding Requires a Contract and Recovery
Multiple submitters can batch retrieve records to improve throughput. In relational database solutions, row locks are often used, along with SKIP LOCKED to skip rows being retrieved by other processes. Retrieval and sending should be separated to avoid holding long transactions during external network requests.
The records can be configured to specify pickup times and lease expiration dates. After a process exits, expired leases allow other processes to take over. The lease duration should cover normal delivery delays, but not extend to the point where recovery from a failure takes half a day. If a large batch is processed at once, the records will queue in memory until the lease expires.
The lease does not eliminate duplicate sending; even after a process is paused, it may continue to deliver. Event deduplication is essential, and the lease primarily helps control concurrency and recovery speed. By keeping track of the number of attempts and the last error classification for each event, it’s easier to distinguish between temporary network issues and permanent incompatibility with the payload.
The delivery system selects a limited number of records based on short transactions and writes the received identity. The network communication is performed outside the transaction. After successful confirmation, the status is updated based on the event and the received identity, avoiding the overwriting of new execution results by expired executors. The lease protection scheduling coordination does not eliminate duplicate messages already received by the message system. Consumer deduplication remains essential, and external side effects also use stable operation identifiers.
The batch size is determined by the sending delay and the lease duration. A large batch is initially retrieved, but the lease may expire before the second instance retrieves the remaining records. Reducing the batch size or controlled renewal can improve the situation, but renewal also requires verification of the holder. Avoid keeping all records in a continuously active state, and do not set the expiration date to “infinite” to avoid repetition. By observing the age of the oldest records and the retrieval delay, you can identify when the recovery mechanism is stalled.
The error classification distinguishes between temporary network failures, vendor throttling, misconfigured authentication, and incompatible payloads. Retrying consumes a limited budget and includes fallback mechanisms. After permanently isolating the error, a fix must be implemented at the entry point. Repeatedly sending authentication failures (e.g., 10,000 times) typically only increases costs without significantly improving the chances of success. Successful confirmation should be based on the actual promises made by the message system, not on assuming that the socket has already processed the message.
The order must be defined by business requirements.
Regarding order creation and order cancellation when delivery is reversed, can the consumer reject the old event through the order version? If not, it is necessary to ensure the correct order of the aggregated events and clearly define how queue partitioning, delivery concurrency, and retries work together.
Global ordering is usually unnecessary and can limit throughput. Most businesses actually require a consistent order within the same order and account. By assigning a monotonic version number to aggregated allocation requests, the consumer can track the last accepted version and identify gaps and inconsistencies. However, the decision of how to handle or recover from these gaps remains a business-specific choice.
Do not consider chronological order as a strict protocol. Variations in time precision, multiple events for the same transaction, and differences in clock synchronization across multiple nodes can all lead to unstable ordering. Database-assigned sequence numbers or aggregated versions are more suitable for interpreting causality.
Dead Leads Aren’t Trash Bins
Events that repeatedly fail need to be isolated to prevent a faulty payload from blocking the normal queue. After isolation, the event identifier, error reason, initial failure time, and the associated business object are retained, providing a path for replaying the event after it has been fixed. Manual replay must also use the original event identifier to avoid bypassing the fix.
One of the most important metrics to monitor is the age of the oldest undelivered events, rather than just the queue length. A queue of ten undelivered events could have been waiting for several hours, while a queue of one thousand undelivered events could simply represent a momentary spike. Setting an age threshold and correlating it with the business-allowed delay is crucial for meaningful alerts.
The event cleanup process requires confirmation of the audit and replay window, and the consumer deduplication record retention period must cover potential historical re-delivery events. If the sender’s mailbox is retained for one year and deduplication is only retained for one day, the replay of old events could lead to duplicate business. The policies of both sides should be jointly designed, not just to optimize the size of the sender’s database. When the payload contains personal data, both the storage, messaging system, and consumer copy have privacy responsibilities.
Initially, the system displays the event’s identity, errors, and business status, using the original ID instead of creating a new event. After fixing the issue, the final processing results and queue age are checked. It’s important to verify that the delivery mechanism didn’t produce any errors.
The reconciliation process involves checking the relationship between orders and the events they should generate, and also checking the relationship between events and consumer states. This helps identify cases where business operations were initiated but lacked the necessary intent, or where events remained incomplete for an extended period.
Both reconciliation methods are necessary to establish different boundaries and ensure complete verification.
Different ways to define and handle events: publishing vs. processing
The “Message delivered” status typically indicates that the messaging system has received the message according to its protocol, but it does not guarantee that all recipients have processed it. If the page needs to display business completion, it should query the corresponding business status instead of simply declaring that the warehouse has shipped. Monitoring should separately record delivery delays and consumer processing delays, as they have different denominators and responsibilities.
Reducing queue length may simply mean that events are being isolated, and not necessarily that tasks are being completed. Monitoring dead-letter counts, the age of the oldest unprocessed events, and business reconciliation together can help avoid the “normal queue clearing” masking a large number of failures. After recovery, check the final status of the consumer for the specific event and verify that replaying was successful, not that a new fact was created. Clearly understanding the completion semantics is crucial to truly address the double-write issue, rather than simply transferring the problem to another hidden queue.
Verifying Actual Atomic Boundaries Using Four Stop Points
The first scenario involves stopping after inserting an order but before inserting an event. In this case, the transaction should be rolled back, but this condition is not met.
The second scenario involves stopping after submitting a transaction and the application returning to its previous state. Both the order and the event have been persisted, and the delivery receiver can continue.
The third scenario involves stopping after the message system confirms the message but before the sender marks it as sent. The event may be re-sent.
The fourth scenario involves stopping after the consumer has locally submitted the message but before the message has been confirmed. The consumer may receive the message again, but the local deduplication ensures that the changes are not repeated.
The four scenarios together cover the two persistence boundaries and the intermediate confirmation window.
Testing with synthetic orders, controlled message confirmation, and real database transactions, verifying actual records. A process that doesn’t throw an exception cannot prove that the order and event are part of a single transaction. Automatic ORM commits or connections from different sources can invalidate this assumption. The consumer’s processing identifier and business updates also require a true shared transaction. External notifications are not guaranteed by this transaction and should be handled with a reliable delivery or vendor idempotency protocol.
The possibility of message duplication is not necessarily a failure in itself. The real failure lies in the inability to detect and address the side effects of duplication, such as missed or repeated messages. Instead of simply counting the number of messages sent, the process should verify the existence of orders, the intended delivery address, the semantic meaning of the confirmation message, and the final status of the consumer. Receiving a confirmation typically only means that the message system has accepted the message according to its protocol, but it does not necessarily mean that the shipment has been completed. The user interface should query the actual business status, rather than directly treating the delivery status as a fulfillment result.
Aggregation order must match consumer processing capabilities
The order creation and cancellation events occur in a specific sequence. The consumer receives the cancellation notification and then creates a new order. If the event represents an incremental action, failing to create the order may pose a security risk. If the event includes complete and versioned data, the consumer may opt for the newer state and reject the older version. The selection should be based on the event semantics, and should not ignore all out-of-order events simply because a “version” field exists. For each type of event, define how to handle the missing creation, read, and upgrade actions, ensuring that no event is permanently stalled due to an unknown order.
Queue partitioning and sending concurrency affect the same aggregation order, but retrying an old message may cause later messages to arrive first. The sending end’s ordering cannot guarantee the consumer’s order. The consumer saves the last applied version and necessary gap states, checking for duplicates, old versions, and discontinuous versions. Global ordering typically over-constrains throughput, and whether the order within the aggregation is necessary depends on the business causality. Timestamps can be sorted and displayed, but should not be treated as absolute causality numbers.
Event Pattern Version Description Payload Structure, Aggregated Version Description Business Progress, these should not be combined into a single number. Structural upgrades should use consumer compatibility or explicit migration. Old events may still be delivered within the replay window. Unknown structures should be isolated and reported, and important actions should not be performed after losing fields. The sender retains factual information and can interpret historical payloads at any time, without relying on the current table structure of the sending database.
How to Avoid Network Holding Locks in Short Transactions
The delivery agent retrieves a limited number of records and registers the execution identity within short transactions. Only after submission does it send a network request. After sending, the status is updated based on events and the identity of the recipient. The old lease executor does not cover the new status. Even after the lease expires, old messages may still be sent, so de-duplication is essential. The barrier only ensures that the boundary is valid during actual verification. We cannot claim that a message is only sent once solely because of mutual exclusion.
Large batches can lead to the latter half of the process being queued in memory until the lease expires, after which a new executor reclaims it. The budget is determined by factors such as message delay, concurrency, and lease duration, with necessary lease renewal verification. Upstream rate limiting and authentication errors are categorized separately, and failures are not immediately retried. Scanning and cleanup strategies affect database load, and cannot be used to mask slow networks by simply increasing the number of senders.
Observe the oldest messages awaiting delivery, the duration of delays, the number of retries, and the number of messages in isolation. A decreasing queue length may simply indicate a large number of messages entering the dead-letter queue, and does not necessarily mean that the business process is complete. Confirm the specific persistence and confirmation guarantees of the message system; successful socket writes do not equate to reliable reception. The metrics include a limited number of event types and consumer categories, with specific event IDs stored in a controlled log, preventing the creation of an infinite number of dimensions.
Fixing “Dead Accounts” Cannot Secretly Create New Business Identities
An incorrect payload format can be fixed by converting and replaying the original event. However, any modification of the original payload must be subject to an audit policy. If the fix changes the business facts, the event must be independently corrected, rather than overwriting the historical record, which would make it difficult for consumers to reconcile. Manual tools should first display the original identity, failure category, and current business status, along with authorization and confirmation. Events cannot be replaced with new IDs by simply copying them to bypass existing records.
The consumer deduplication retention period covers message re-delivery, re-sending from the inbox, and manual recovery, with the longest window of time. The sending end retains old events for one year, while the receiving end deletes them after one day. Re-sending will generate additional business actions. The policies of both sides work together, with the permanent business table storing the operation identity when necessary, and the short-term deduplication table only caching the results. The process cleans up without removing pending delivery obligations, and unknown states are retained for reconciliation paths.
Minimizing Payload to Reduce Responsibility for Copies After Broadcasting
Warehouse tasks may require product and quantity information, while notification tasks may require a separate contact information record. The entire order details should not be broadcast to all subscribers. The task payload, access control, and message storage must all be consistent. Event encryption transmission does not reduce the range of data already received by the recipient. Legitimate technical delivery does not imply the right to permanently retain data. Published information can use necessary business identifiers, and private fields can be obtained through independent authorization interfaces.
The logs and dead-letter queues may also display payloads. Error handling should redact and restrict permissions. Test dummy email addresses, tokens, and addresses to ensure that unnecessary fields do not appear in events, tracking, and public error reports. Data format validation can only check the form, while privacy requirements require explicit permission for field projection. When adding consumers, verify whether the same event capability is truly needed.
The “mailbox” mode can also be implemented by capturing changes in log files, rather than polling tables. The collector relies on database log retention, read positions, and downstream confirmation. It requires verifying where to resume after a restart and how to detect gaps when logs have been cleared. This reduces some polling costs and does not automatically provide a single, cross-system solution. The choice of method depends on the capabilities of the database and the responsibilities of operations. Event identity and consumer deduplication are still retained.
Regarding the table polling scheme, when clearing delivered records, avoid overlapping with reconciliation and replay windows, and control the length of transactions in bulk operations. The index design should cover both scanning and sequential processing, but the actual execution plan and write costs need to be measured, and you cannot guarantee a fixed time based solely on adding status indexes. When the oldest event age is abnormal, first confirm whether scanning, retrieval, or sending is blocked, and avoid blindly starting more instances.
Complete Business Chain Verification, Not Just Process Health
Verify that the submitted order has the intended purpose, and then verify that the intended purpose has been reliably delivered to the consumer. Different findings reveal different omissions; a single empty order does not prove that the system has not lost an item. After recovery, confirm that the oldest age and business status have reached the target, and clearly define the subsequent responsibilities for the incident. When testing the system without actual messages, only state the executable scenarios, and do not fabricate a guarantee that the entire system will work perfectly once.
Fault Injection Acceptance Testing
After submitting a business, the application should be stopped, but the event should still be deliverable. After receiving a message confirmation, the sender should be terminated before the status update, and the consumer should correctly deduplicate. If a payload fails continuously, other events should continue to proceed. Finally, verify the database order with the consumer’s processing results to prove that the system can find missing items, rather than simply keeping the process running.
Expand disaster recovery samples: Back up the database to a specific point in time, but the messaging system and consumers are not synchronized to revert. The events that are recovered and ready to be delivered may have already been processed, so re-sending still uses the original event identity. The de-duplication of consumers cannot only exist in the sending library that was reverted together. Also, check whether the new business identifiers created after recovery conflict with the old facts. The recovery point difference is an independent window, so first list what each system retains, then decide on the scope of re-sending. Do not equate recovering the database with recovering the entire business timeline.