BM
Bashar ModallalSOFTWARE · AI · SYSTEMS
Backend Engineering

Advanced · Lesson 8 of 12

Software Architecture

Move Slow Work into Background Jobs

A customer buys two notebooks, but checkout stalls while the receipt is emailed. Follow one order through a durable queue and two worker crashes.

A shopkeeper hands over a bag of notebooks while a receipt printer feeds paper into a separate tray.

Mariam orders two notebooks from a stationery shop in Sharjah. The order takes 120 milliseconds to save, but her phone keeps spinning for another eight seconds while the shop generates a PDF and contacts its email provider. She taps Buy again. The clerk now has to answer two separate questions: did the shop accept the order, and did it send the receipt? A single green tick on the checkout screen cannot answer both.

Give the example an order number, SH-481, a total of AED 27, and one receipt in Arabic. The shop's requirement is modest: confirm the purchase as soon as it is durable, then let Mariam see what happened to her receipt. If the email service is down, the clerk should still be able to prepare the notebooks. If a worker crashes, a replacement must know whether to resume, retry, or ask someone to investigate.

Decide what the first response promises

The checkout request owns the work needed to accept the purchase. That includes authenticating the customer, validating the basket, allocating the stock and recording the agreed amount. The receipt must describe this committed sale. PDF rendering, font loading and waiting for the email provider can all happen later. Moving those operations out of the request shortens the time to confirmation. The customer may still wait just as long for her email, and the interface should make that distinction visible.

After commit, return 201 Created for the new order, its stable ID and a link to its receipt status. The page can now say “Order confirmed. Preparing your Arabic receipt.” If there is also an endpoint whose sole purpose is to request preparation of a receipt, 202 Accepted makes sense there while the work is pending. Its response can point to a status resource. A client that requested a file should be able to tell whether it received the file or merely a way to follow its progress. HTTP Semantics, section 15.3.3

Give checkout itself a stable request identifier scoped to the customer. If Mariam's connection drops after commit, the second tap can recover SH-481 instead of creating SH-482. Receipt processing needs its own identity because two deliveries of the same message may reach different workers. For this example the business key is receipt/SH-481/ar/v1. It identifies one edition of one receipt and stays fixed across attempts. A delivery tag issued by a message broker has a much shorter life and cannot play that role.

Store the order and the obligation together

Consider the tempting implementation that saves the order and then publishes a message. The process could stop after the commit and before the publish. The customer owns the notebooks, but there is no worker waiting to send her receipt. Publishing first simply moves the gap: a worker could begin preparing a receipt for a purchase that eventually rolls back. A faster connection to the broker makes both windows shorter without removing either one.

In one database transaction, insert the order, its immutable line amounts, a receipt row in the pending state, and an outbox row. The outbox is a table of committed work that still needs to be announced. Use a unique constraint on the receipt key. Include the key, order ID and schema version in the event; keep the recipient and invoice details under the shop's normal access controls. Commit these rows together. If the stock allocation fails, the transaction rolls back and the relay has nothing to publish. AWS guidance on the transactional outbox

A relay reads the committed event and publishes it to the configured durable receipt queue. Configure persistence and check that the message actually routed to the intended queue. The relay marks the outbox row dispatched after the broker confirms the publish and routing has succeeded. Suppose that confirmation arrives and the relay dies before recording it. On restart the same event may travel twice. That is a recoverable outcome once the consumer can recognize the receipt key. Deleting the outbox row before the publish would give the system no equivalent way to recover a missing message.

Walk one receipt through a worker

At 10:00:00 the order commits with two units at AED 13.50 each. At 10:00:01 a worker receives the key and claims the pending receipt with a guarded update, setting an owner, an expiry and an attempt number. A second worker must respect a live claim. If a claim expires, the replacement reads the existing state and checks what the former worker already did. Every subsequent state update checks the current owner so a delayed worker cannot overwrite a newer result.

Render the document from the saved order lines, currency and locale. Tomorrow's price list has no bearing on today's AED 27 receipt. Store the generated document privately under the receipt identity and retain its digest. Once the bytes are ready, save the exact email request or enough immutable data to reproduce it, including the recipient snapshot and attachment reference. Reusing the same key while silently changing the recipient or regenerating a different PDF undermines any promise about a retry repeating the same operation.

For this example assume the chosen email provider accepts a client idempotency key and offers a lookup by that key. Send the saved request using the receipt key. On acceptance, save the provider's reference and the time in the receipt record. Commit that state change before acknowledging the delivery to the broker. A customer can now see that the shop handed the receipt to its provider. A separate authenticated delivery event can later establish that the recipient's mail server accepted it. Even that event does not prove Mariam opened the message.

Evidence on hand What the interface can say
Order and receipt request committed Order confirmed. Receipt in preparation.
Private PDF available Receipt ready to download.
Provider accepted the email request Receipt submitted for email delivery.
Provider reported a permanent bounce Email could not be delivered. Your receipt is available here.

Place the acknowledgment after durable progress

A publisher confirmation tells the relay what happened between the relay and broker. A consumer acknowledgment tells the broker it can retire a particular delivery. Neither reports what the email provider did. With manual consumer acknowledgments an unacknowledged delivery can be redelivered after a worker loses its connection. Acknowledge on the channel that received it. The receipt record allows the new worker to interpret the redelivery even if the original delivery tag no longer means anything. RabbitMQ confirms and consumer acknowledgments

Suppose the provider accepts the request at 10:00:05 and returns reference M-731. The worker loses power before it saves that reference. Locally the row still looks unfinished. Another worker that treats “no reference” as proof of “never sent” risks emailing a second receipt. After the lease expires, the replacement looks up the same key. If it finds M-731, it records acceptance and acknowledges its delivery. If a lookup cannot resolve the outcome, it can safely resend identical input only within the provider's documented idempotency guarantees.

Those guarantees belong to a particular endpoint and may expire. Some providers support neither lookup nor duplicate suppression. For them a lost response can leave a genuinely ambiguous outcome: retrying may duplicate mail, while suppressing the retry may leave the customer without a message. Record the uncertainty, keep the PDF accessible, and route the case to review when the product requires a single send. An application's unique database constraint can eliminate a duplicate local receipt while doing nothing to deduplicate an external email.

Choose when a retry earns another attempt

Distinguish temporary overload from an invalid recipient. For an illustrative policy, allow four total send attempts. After a definite temporary rejection, schedule waits of roughly ten seconds, one minute and five minutes, with jitter and respect for any longer delay the provider specifies. Persist the next eligible time. If the broker delivery is acknowledged while a retry is needed, commit a durable retry obligation first. Otherwise the queue can look empty while the receipt sits in a state that no worker will ever revisit.

A permanent address error needs a different path. Stop the automatic sends, preserve the downloadable document, and give the customer a way to correct the address. A deliberate send to a new address is a new operation with a new key. Keep the original receipt and its history. Conversely, changing keys on every network timeout defeats the duplicate protection you were counting on. Log the order ID, receipt key, attempt and outcome; the PDF contents and the full address are unnecessary for measuring worker health.

Watch the age of the oldest pending receipt as well as queue depth. A queue of fifty fresh receipts after a promotion and one receipt stuck for two hours call for different actions. Measure elapsed time from order commit to PDF readiness and provider acceptance separately. If PDF time is steady while provider acceptance slows, adding rendering workers may only increase pressure on the provider. Limit concurrency at that boundary and use the status page to give the customer a useful answer during the delay.

اقرأ الدرس بالعربية

Exercise: disconnect the worker twice

Use a private test order for AED 27 and a fake provider that records calls by business key. First disconnect the worker immediately after provider acceptance and before the local commit. After recovery, disconnect it a second time just after the local commit but before the broker acknowledgment. What should the next worker do, and what should Mariam see?

Answer. The first replacement recovers the accepted provider reference by key and commits it locally. The second replacement sees that durable result and acknowledges the redelivery without another send. Check that one order, one PDF digest and one accepted provider operation remain, even though several deliveries occurred. The order stays confirmed throughout. The receipt page offers the PDF once ready and reports email submission once backed by evidence. If no delivery event has arrived, the last state you can honestly display is submission to the provider.

YOUR TAKE

What did you think?

Choose one reaction for this article.

Was this useful?

A cookie helps limit repeat responses. Your feedback is private.

Share this noteLinkedIn ↗X ↗Email ↗

Keep exploring.

Software Architecture9 min read

Sessions and Order Ownership

Follow two customers on a shared tablet. Scope receipt reads and pickup-branch changes to the signed-in customer, then test both the response and stored orders.

Read article ↗