Transactional Outbox for order confirmations
An order was saved, then the Worker stopped before sending its confirmation. If the job was saved with the order, the next Worker can pick it up and send it.
Save the order and job together
- Checkout saves the order
- Begin transaction → insert
order-42and outbox jobconfirm:order-42→ commit → report that the order was saved - The Worker sends the confirmation
- Read a committed
pendingjob → send its work and order IDs → receiver records confirmation → Worker marksdoneafter a successful reply
The outbox is the application's table of work to send. A rollback discards the order and its job together. A successful commit records the order and the pending job. The confirmation is sent later.
Resume when the Worker restarts
If the Worker stops before sending, confirm:order-42 stays pending. A new Worker reads the committed job and sends it with the same work ID. With a target such as notifications.confirm, CoAkka Runtime delivers the call and returns its delivery outcome. The application owns the outbox and sets its state based on the receiver's reply.
| When did the Worker stop? | What remains? | What does the next Worker do? |
|---|---|---|
| Before sending | The order is saved, the job is pending, and no confirmation exists. |
Read the job and send it with its stored ID. |
After the receiver commits, before marking done |
The job is still pending. The receiver already committed the confirmation. |
Resend with the same ID. The receiver returns success for the existing confirmation. |
After marking done |
The job is complete. | Skip it when scanning for pending work. |
After a timeout, the Worker may not know whether the receiver made the change. Keep the job, inspect the failure, and reuse the work ID on a retry. Each attempt can have a different request ID. Look up timeouts and Deadletters.
Prevent duplicate confirmations
The receiver enforces a unique constraint on work ID confirm:order-42. Here the confirmation row also records that the work was processed. If the receipt is stored in a separate table, commit the receipt and business update in one transaction. Return success after commit. If the same work is already recorded, return success without inserting another confirmation.
When sending through an email provider
A database transaction protects writes to that database. If the provider supports idempotency keys, reuse the same key and check how long it applies. If acceptance is uncertain, check the delivery status when the provider exposes it. Without either capability, a retry can send another email.
When running multiple Workers
Claim each job for a limited time in a short transaction, then send it. Only the Worker holding the claim can mark the job complete. After expiry, another Worker can claim it. Keep receiver deduplication because the old Worker may have sent just before the claim expired.
Run two Worker exits locally
The local trial uses Python and two temporary SQLite databases. A Worker process simulates a call to the receiver by writing to the second database. Copy the file below, then run it.
Python code · save the order, stop the Worker, and resume
"""Run both outbox recovery cases locally with two SQLite databases."""
from contextlib import closing, contextmanager
import os
from pathlib import Path
import sqlite3
import subprocess
import sys
from tempfile import TemporaryDirectory
WORKER_STOPPED = 75
@contextmanager
def transaction(path):
with closing(sqlite3.connect(path)) as db:
with db:
yield db
def create_tables(root):
with transaction(root / "checkout.db") as db:
db.execute("CREATE TABLE orders (order_id TEXT PRIMARY KEY)")
db.execute("""
CREATE TABLE outbox (
work_id TEXT PRIMARY KEY,
order_id TEXT NOT NULL,
state TEXT NOT NULL DEFAULT 'pending'
)
""")
with transaction(root / "notifications.db") as db:
db.execute("""
CREATE TABLE confirmations (
work_id TEXT PRIMARY KEY,
order_id TEXT NOT NULL
)
""")
def save_order(root, order_id):
# Commit the order and the work to publish it together.
with transaction(root / "checkout.db") as db:
db.execute("INSERT INTO orders VALUES (?)", (order_id,))
db.execute(
"INSERT INTO outbox (work_id, order_id) VALUES (?, ?)",
(f"confirm:{order_id}", order_id),
)
def accept_confirmation(root, work_id, order_id):
with transaction(root / "notifications.db") as db:
# This row is both the customer's confirmation and the deduplication record.
db.execute(
"""INSERT INTO confirmations VALUES (?, ?)
ON CONFLICT(work_id) DO NOTHING""",
(work_id, order_id),
)
saved_order = db.execute(
"SELECT order_id FROM confirmations WHERE work_id = ?", (work_id,)
).fetchone()
if saved_order != (order_id,):
raise ValueError("Work ID was already used for a different order")
# The receiver returns success only after its transaction has committed.
def dispatch_one(root, stop_at):
with transaction(root / "checkout.db") as db:
job = db.execute("""
SELECT work_id, order_id FROM outbox
WHERE state = 'pending' ORDER BY work_id LIMIT 1
""").fetchone()
if job is None:
return
# Exit the Worker process without running any further application code.
if stop_at == "before-send":
os._exit(WORKER_STOPPED)
work_id, order_id = job
accept_confirmation(root, work_id, order_id)
if stop_at == "after-receive":
os._exit(WORKER_STOPPED)
with transaction(root / "checkout.db") as db:
db.execute("UPDATE outbox SET state = 'done' WHERE work_id = ?", (work_id,))
def run_worker(root, stop_at, expected_exit):
result = subprocess.run(
[sys.executable, str(Path(__file__).resolve()), "--worker", str(root), stop_at],
timeout=10,
check=False,
)
if result.returncode != expected_exit:
raise RuntimeError(f"Worker exited with {result.returncode}, expected {expected_exit}")
def check_state(root, order_id, expected_state, expected_count):
with transaction(root / "checkout.db") as db:
saved = db.execute("""
SELECT outbox.state FROM orders JOIN outbox USING (order_id)
WHERE orders.order_id = ?
""", (order_id,)).fetchone()
with transaction(root / "notifications.db") as db:
count, = db.execute(
"SELECT COUNT(*) FROM confirmations WHERE order_id = ?", (order_id,)
).fetchone()
if saved != (expected_state,) or count != expected_count:
raise RuntimeError(f"{order_id}: unexpected outbox state {saved}, confirmations={count}")
def run_demo():
with TemporaryDirectory(prefix="coakka-outbox-") as directory:
root = Path(directory)
create_tables(root)
save_order(root, "order-42")
run_worker(root, "before-send", WORKER_STOPPED)
check_state(root, "order-42", "pending", 0)
print("order-42: worker stopped before send, pending, confirmations=0")
run_worker(root, "none", 0)
check_state(root, "order-42", "done", 1)
print("order-42: worker resumed, done, confirmations=1")
save_order(root, "order-43")
run_worker(root, "after-receive", WORKER_STOPPED)
check_state(root, "order-43", "pending", 1)
print("order-43: receiver committed, worker stopped, pending, confirmations=1")
run_worker(root, "none", 0)
check_state(root, "order-43", "done", 1)
print("order-43: same work ID retried, done, confirmations=1")
if __name__ == "__main__":
if len(sys.argv) == 4 and sys.argv[1] == "--worker":
dispatch_one(Path(sys.argv[2]), sys.argv[3])
elif len(sys.argv) == 1:
run_demo()
else:
raise SystemExit("Usage: python3 transactional_outbox.py")
python3 transactional_outbox.py
Expected result
order-42: worker stopped before send, pending, confirmations=0 order-42: worker resumed, done, confirmations=1 order-43: receiver committed, worker stopped, pending, confirmations=1 order-43: same work ID retried, done, confirmations=1
Order order-42 has one confirmation after the next Worker sends it. Order order-43 still has one after resending with the same work ID. The script removes both temporary databases when it exits.