RZ

Preparing your experience

Back to Blog
System Architecture

An Order Saga in Four Languages: Choreography with RabbitMQ and MySQL

November 26, 202613 min read
MicroservicesSaga PatternRabbitMQMySQLArchitecture

Placing an order sounds like one operation: take the money, reserve the stock, create the shipment. Inside one application with one database, a single transaction can cover the database part of that. Give payment, inventory and shipping their own databases and that transaction is gone. smallest-microservice is my small, readable version of the usual answer, the saga: an order pipeline built from four services in four languages, each with its own MySQL database, talking only through RabbitMQ.

It is small enough to read from end to end, which makes it a useful place to look at what a saga needs in real code: who reacts to what, how a failed step is undone, how a redelivered message is kept from doing the work twice, and which failures are still not handled.

Scope note: everything below comes from reading the repository at commit d8aa267. This is not a report of a test run or a benchmark. The repository describes itself as a learning demo, not production code.
Sequence diagram of the order saga across the Node.js order, Python payment, Go inventory and PHP shipping services, each with its own database. Node sends q.order_created to Python. A declined payment returns q.payment_failed to Node. An accepted one sends q.payment_completed to Go. If stock is reserved, Go sends q.stock_reserved to PHP, which sends q.shipment_created to Node and the order is fulfilled. If stock is unavailable, Go sends q.stock_unavailable to Python, which refunds and sends q.payment_refunded to Node, and the order is cancelled.
The full saga and its three endings. Select the diagram to open it at full size.

1. Four services, four databases

ServiceLanguageJobDatabase
OrderNode.js (Express)HTTP API, creates orders, records their final statusorders_db
PaymentPython (pika)Accepts or declines a payment, refunds if stock is unavailablepayments_db
InventoryGoReserves stock or reports it unavailableinventory_db
ShippingPHPCreates the shipment recordshipping_db

There is also a small React and Tailwind web UI that places orders and shows what happened to each one. No service reads or writes another service's database. In this repository that is a rule the code follows, not one the infrastructure enforces: all four connect to MySQL with the same local user.

The business rules are deliberately tiny. The payment "charge" is a row in a table, and any amount above 1000 is declined. The stock table is seeded with three products, one of which, OUT_OF_STOCK, has zero units, so you can trigger the compensation path whenever you like. The small rules keep the attention on the messaging.

2. Choreography: nobody is in charge

A saga replaces one distributed transaction with a sequence of local transactions. Each service commits its own step and announces the result. When a later step fails, earlier steps are not rolled back by the database; the application runs a compensating action instead. There are two common ways to drive the sequence: an orchestrator that tells each participant what to do, or choreography, where each participant reacts to events from the others. This project uses choreography.

So the workflow is not written down in any single file. It is spread across the queues each service subscribes to:

  • Payment declined: q.order_created goes to Python, then q.payment_failed goes back to Node. The order ends as payment_failed.
  • Happy path: q.payment_completed goes to Go, q.stock_reserved to PHP, and q.shipment_created to Node. The order ends as fulfilled.
  • Out of stock: after payment succeeds, Go publishes q.stock_unavailable. Python marks the payment refunded and publishes q.payment_refunded. The order ends as cancelled_out_of_stock.

The gain is that no service knows another service's address, and there is no central component to build. The cost is that to answer "what happens after payment?", you have to find who consumes that queue. With four services that is manageable. It gets harder as the number of steps and branches grows, which is the usual argument for an orchestrator.

3. The queue name is the contract

Messages are published to RabbitMQ's default exchange with the queue name as the routing key, so each event lands in one named queue. The body is plain JSON. There is no schema registry and no shared library: the contract between two services is a queue name plus the fields each side expects. Go is the one service that spells those fields out as a type:

type Message struct {
	OrderID   int     `json:"order_id"`
	ProductID string  `json:"product_id"`
	Quantity  int     `json:"quantity"`
	Amount    float64 `json:"amount"`
	Event     string  `json:"event"`
	CreatedAt string  `json:"created_at"`
}

This has a practical consequence for the API. The payload that starts in Node is passed along by the next services, each adding its own event name and timestamp. If the first message carries a quantity as the string "2", a strictly typed consumer further down cannot decode it, by which point an earlier step has already committed. That is why POST /orders checks types and ranges before it writes anything: product_id must be a string of 1 to 50 characters, quantity a positive integer, and amount a number within the column's range. In a message-driven system, the entry point is the cheapest place to reject bad input, because it is the only place that can still answer the caller with a 400.

Once the input passes, Node inserts the order as pending, publishes order_created and returns 201 without waiting for the rest of the saga. The client has to ask again later with GET /orders/:id.

4. Redelivery without doing the work twice

All consumers use manual acknowledgements. A message is acked after the handler finishes, so if a consumer dies before that, RabbitMQ delivers it again. That is good for not losing work and bad if the work is "charge the customer".

Payment, inventory and shipping each put a UNIQUE constraint on order_id and insert with a no-op on conflict. This is the payment service:

cursor.execute(
    "INSERT INTO payments (order_id, amount, status) VALUES (%s, %s, %s) "
    "ON DUPLICATE KEY UPDATE status = status",
    (order_id, amount, status),
)
rows_affected = cursor.rowcount

The constraint stops a second row. The row count stops a second event: if it is 0, the handler logs a duplicate, publishes nothing and acks. Without that second check, the database would be safe but the duplicate would still travel down the chain.

There is a portability detail hiding here. The MySQL manual says this statement reports 1 affected row for a new insert, 2 for a changed row and 0 when an existing row is set to its current values. But if the client connects with the CLIENT_FOUND_ROWS flag, that last case reports 1. None of the three connections here asks for that flag. Turn it on while "tidying up" a connection string and the duplicate check silently stops working. If you copy this pattern, test it with your own driver settings.

The refund uses the same idea in a different shape. It is an UPDATE that sets the status to refunded. The second time, nothing changes, the count is 0, and no second payment_refunded event goes out. Node's final status updates are naturally repeatable, since writing fulfilled twice leaves the order fulfilled.

5. The inventory step needs a real transaction

Inventory is the one step where a unique key is not enough. It has to read the stock level, decide, record a reservation and decrement the stock. If those are separate statements, two things can go wrong: two consumers can both read the same stock level and oversell, or a failure between the insert and the update can leave a reservation with no matching decrement. The Go service does all of it in one transaction and locks the stock row with SELECT ... FOR UPDATE. Shortened, with error handling removed:

tx, err := db.Begin()
defer tx.Rollback() // no-op after Commit

err = tx.QueryRow("SELECT available_quantity FROM stock WHERE product_id = ? FOR UPDATE",
    message.ProductID).Scan(&available)

status = "reserved"
if available < message.Quantity {
    status = "released"
}
// INSERT INTO reservations ... ON DUPLICATE KEY UPDATE status = status
// affected == 0: already processed, return without publishing
// status == "reserved": UPDATE stock SET available_quantity = available_quantity - ?
return status, true, tx.Commit()

An unknown product is treated as having zero stock. A refused request is also recorded, with the slightly surprising status released: nothing was ever held, but the row means a redelivered message for that order is recognised as already processed. Only after the commit does the service publish stock_reserved or stock_unavailable.

That "only after the commit" is the right order, and it is also where the biggest gap in the design sits.

6. The gap: commit, then publish

Every service writes to its database and then publishes to RabbitMQ. Those are two systems, and nothing makes the pair atomic. Walk through the payment service:

  1. It receives order_created and commits the payment row.
  2. The process dies before it publishes payment_completed, and so before it acks.
  3. RabbitMQ redelivers order_created.
  4. The insert hits the unique key, the row count is 0, and the handler decides this is a duplicate.
  5. It acks without publishing. Inventory never hears about the order, which stays pending.

The very check that prevents a double charge also swallows the missing event. Idempotent consumers protect against duplicates; they do nothing against loss. These are two different problems, and it is easy to solve the first and assume both are handled.

The standard fix is a transactional outbox: in the same local transaction as the business row, insert the outgoing event into an outbox table, and let a separate relay publish it and mark it as sent. The relay may send an event more than once, which is exactly why the idempotent consumers are still needed. The project does not implement this.

The same gap exists at the front door. If Node inserts an order and then fails to publish, the caller gets an error but the pending row remains. And because POST /orders takes no idempotency key, a client that retries simply creates another order.

7. Durable queues are not a delivery guarantee

The queues are declared durable and messages are published as persistent. The point is that queued messages should survive a broker restart; a durable queue alone does not make its messages persistent, so you need both. Every service that declares a queue also has to declare it with matching settings. RabbitMQ rejects a redeclaration with different properties with PRECONDITION_FAILED, so if you ran an earlier, non-durable version of the project, the README tells you to delete the old queues.

Durability still leaves holes:

  • No publisher confirms. A service does not wait for the broker to confirm that it took responsibility for a message. See RabbitMQ's page on acknowledgements and confirms.
  • Failed handlers drop the message. On an error, consumers nack without requeueing, and the project configures no dead-letter exchange. On queues set up as this code declares them, with no broker policy adding one, the message is discarded. This avoids an endless redelivery loop for a poison message, but a short database outage is treated the same way as a malformed payload.
  • No prefetch limit. No consumer sets a prefetch count, so unless the broker is configured with a default, nothing caps how many unacknowledged messages it may push to a consumer.
  • No reconnect logic. The README says to restart all services after RabbitMQ restarts. The Node API can keep running without a broker connection, in which case new orders return 500 but still leave a pending row. The PHP consumer also holds one long-lived MySQL connection and needs a restart if MySQL closes it.

8. Only one thing gets compensated

Compensation is the part of a saga that replaces rollback, and here there is exactly one compensating action: unavailable stock triggers a refund. A declined payment needs no undo, because nothing happened before it.

Shipping has no failure event. If the PHP service cannot create the shipment, the message is dropped, the payment stays completed, the stock stays reserved and the order stays pending. Nothing releases a successful reservation. There are also no timeouts, so no component notices that an order has been pending too long. A more complete version would publish a shipment_failed event that makes inventory release the stock and payment refund, plus a sweeper for orders that stop moving. In a choreographed saga, every new failure mode means deciding which services must react to it, and nothing in the system tells you when you have forgotten one.

9. Making the invisible visible

Choreography is hard to follow while it runs, because the story of one order is split across four sets of logs. To show it in one place, each publish of a saga event is followed by a small audit message to q.saga_events that names the order, the event, the queue and the source service. Node consumes it, works out the destination service from the queue name, stores a row in saga_events and serves it at GET /orders/:id/events. In the web UI you can expand an order to see its timeline; while the order is pending, the UI polls once a second.

The events are sorted by occurred_at, set by the publishing service with millisecond precision in the database, with the row id as a tie-breaker. Insertion order is not reliable here, because audit messages from different services can reach Node in a different order from the one in which things happened.

It is worth being clear about what this timeline is. It is for display only; the saga does not depend on it. The audit message is a second, separate publish, so it can go missing even when the saga event went through, and a redelivered audit message can be recorded twice. Its timestamp is taken after the saga event has already been sent, by the clock of whichever service sent it, so treat the order as a helpful view and not as proof of causality. It is not an event store.

10. What I would not copy into production

Besides the messaging gaps above, the setup is for a local machine only. Connection settings, including default credentials, are hardcoded. The API has no authentication. The repository has no automated tests. There is no product catalogue or price check, and no payment provider. Do not expose it to a network you do not control. The README has a known limitations section that covers most of these points.

To read or run it, you need RabbitMQ, MySQL, Node.js, Python 3, Go and PHP with Composer; the README lists the versions, extensions, schema files and start order. It is released under the MIT License. A good reading order is the Node service, then Python, Go and PHP, following one queue at a time.

What I would take from this

  • Idempotency and delivery are separate problems. A unique key handles the message that arrives twice. It does not help with the message that was never sent.
  • Use a local transaction wherever you still can. A saga is for crossing service boundaries. Inside one service, the stock check and the decrement belong in one transaction.
  • Validate before the first commit. Once an event is in flight, there is no caller left to send an error to.
  • List the failure paths, not only the happy path. For each step, ask what undoes the earlier ones, and what happens if nothing ever answers.
  • State the limits in the repository. A small demo is more useful when a reader knows which parts are safe to copy.

References

  1. smallest-microservice repository: github.com/jmrashed/smallest-microservice
  2. README, with setup steps and known limitations: README.md
  3. Order service and its schema: node-producer/index.js, schema.sql
  4. Payment service: python-relay/relay.py
  5. Inventory service and its schema: go-relay/main.go, schema.sql
  6. Shipping service: php-consumer/consumer.php
  7. Saga timeline in the web UI: OrderTimeline.tsx, useOrderEvents.ts
  8. Chris Richardson, Saga pattern: microservices.io
  9. Chris Richardson, Transactional outbox pattern: microservices.io
  10. RabbitMQ, work queues tutorial (acknowledgements, durability, default exchange): rabbitmq.com
  11. RabbitMQ, consumer acknowledgements and publisher confirms: rabbitmq.com/docs/confirms
  12. RabbitMQ, dead letter exchanges: rabbitmq.com/docs/dlx
  13. RabbitMQ, consumer prefetch: rabbitmq.com/docs/consumer-prefetch
  14. MySQL 8.4 manual, INSERT ... ON DUPLICATE KEY UPDATE: dev.mysql.com
  15. MySQL 8.4 manual, locking reads: dev.mysql.com

Found this useful? Explore more articles on System Architecture.

All articles