title: How to store something to a database and publish a message to a bus in one transaction?
body: <p>I've read a lot of blogs and books about event driven messaging between microservices or bounded contexts to share state or react to events. Most examples implement a command handler like the following snippet. Which is actually a simplified snippet from the book '<a href="https://www.wiley.com/en-nl/Patterns%2C+Principles%2C+and+Practices+of+Domain+Driven+Design-p-9781118714690" rel="nofollow noreferrer">Patterns, Principles, and Practices of Domain-Driven Design</a>'.</p>
  <pre class="lang-cs prettyprint-override"><code>public void Handle(PlaceOrder message)
  {
      var orderId = Database.SaveOrder(
          message.ProductIds, message.UserId, message.ShippingTypeId
      );
      // what if something goes wrong here?
      var orderCreatedEvent = new OrderCreated
      {
          OrderId = orderId,
          UserId = message.UserId,
          ProductIds = message.ProductIds,
          ShippingTypeId = message.ShippingTypeId,
          TimeStamp = DateTime.Now,
          Amount = CalculateCostOf(message.ProductIds)
      };
      Bus.Publish(orderCreatedEvent);
  }
  </code></pre>
  <p>The snippet seems incomplete since storing the order could succeed without sending the message. I know I could use the <a href="https://docs.microsoft.com/en-us/dotnet/architecture/microservices/multi-container-microservice-net-applications/subscribe-events#publishing-events-through-the-event-bus" rel="nofollow noreferrer">transaction outbox pattern</a>, which adds additional cost of storing messages in a table and to have a worker periodically check the table and send missed messages. Another approach is using event sourcing, but that seems like overkill just to solve the issue of reliable messaging. So I'm wondering if there are alternatives such as a transaction which works on the bus and the database together? Or should the <code>Database.SaveOrder()</code> be idempotent somehow so I could always repeat the whole procedure?</p>