الانتقال إلى المحتوى
Software ArchitectureMicroservices· 9 دقائق للقراءة

الـ save وبعده publish مش atomic: مشكلة الـ dual write والـ outbox pattern

مفيش transaction بتغطي الداتابيز والـ broker مع بعض، فأي فشل بين الكتابتين بيضيّع events من غير صوت. اعمل commit للـ event مع الداتا وخلّي relay ينشره.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
محتويات المقال

عميلة بتسأل الـ support ليه الـ order اللي دفعته ماتشحنش. داتابيز الـ Orders فيها الـ order، والـ Payments خصمت من الكارت، والـ Shipping عمرها ما سمعت عنه. الدليل الوحيد التوقيت: الـ instance اللي حفظته اتقفلت في deploy بعدها بلحظة. ومفيش log بيقول إن event ضاع، لأن السطر اللي كان هينشره، أو يفشل بصوت عالي، ماتنفّذش أصلًا.

الفكرة الغلط الشائعة

الفكرة بتقول إن الحفظ في الداتابيز وبعده نشر event كفاية، لأن الـ calls الاتنين تقريبًا دايمًا بينجحوا. ولو الـ broker وقع، حد هياخد باله من الـ errors.

ده شكل أغلب النسخ الأولى، وبيعدّي كل الـ tests. الفجوة بين الـ calls صغيرة جدًا، وفي الـ development مفيش حاجة بتقع جواها. والـ guide بتاع Microsoft للـ microservices نفسه بيعرض الشكل ده الأول، مع تحذير صريح إنه "a simplified example that does not take atomicity into account." ووقوع الـ broker فعلًا بيطلّع exceptions. المشكلة في التوقيت: بعد الـ commit، الـ exception بتقول للمستخدم إن order اتعمل فعلًا فشل.

اللي بيحصل فعلًا

كتابتين من غير transaction مشتركة

بوست Gunnar Morling على Debezium بيسمّي السبب الأساسي: "we cannot have one shared transaction that would span the service’s database as well as Apache Kafka, as the latter doesn’t support to be enlisted in distributed (XA) transactions." ده اسمه ، وكل ترتيب ليه طريقة فشل:

  • احفظ وبعدين انشر: crash أو deploy أو وقوع للـ broker في النص بيضيّع الـ event. والـ outbox guide بتاع Microsoft بيذكر أعطال الـ network ووقوع خدمة الرسايل ووقوع الـ host، وبيحذّر إن "Lost events can cause data inconsistencies across the application."
  • انشر وبعدين احفظ، أو انشر جوه الـ transaction: زي ما Chris Richardson بيقول، "There’s no guarantee that the transaction will commit." فالـ consumers بيتصرفوا على order مش موجود. ومقال الـ domain events والـ integration events بيشرح الحالة دي بالتفصيل.
  • انشر والـ acknowledgment يضيع: الـ broker عنده الرسالة، والـ caller شايف error فبيعيد، وبقوا اتنين.

و"تقريبًا دايمًا" مش هي المهمة. الفجوة مفتوحة في كل request، ولما تضرب، النتيجة صامتة ودايمة: مفيش retry، لأن محدش فاكر إن فيه event كان المفروض يتنشر.

طب ليه مش distributed transaction؟

الـ pattern بتاع Richardson بيستبعدها في سطر: "The database and/or the message broker might not support 2PC. Also, it’s often undesirable to couple the service to both the database and the message broker." و Kafka، زي ما شفنا، مش بتدعمها أصلًا. والـ guide بتاع Microsoft بينصح ضدها كمان، "for the reasons described by the CAP theorem": الـ commit اللي محتاج السيستمين شغالين بيفشل لما أي واحد فيهم يقع.

اكتب مرة واحدة، وطلّع التانية منها

إجابة Morling إنك "only modify one of the two resources (the database or Apache Kafka) and drive the update of the second one based on that, in an eventually consistent manner." ممكن تكتب في الـ broker بس والـ service تستهلك الـ events بتاعتها، بس ساعتها هتخسر الـ "read your own write" للداتا بتاعتها. أو تستخدم event sourcing كامل، واللي الـ guide بتاع Microsoft بيقول إنه محتاج تعيد بنا أغلب السيستم. أو تكتب في الداتابيز بس، بـ : تخزّن الرسالة "in the database as part of the transaction that updates the business entities. A separate process then sends the messages to the message broker." والنتيجة بكلام Richardson: "Messages are guaranteed to be sent if and only if the database transaction commits".

الـ relay: polling ولا الـ transaction log

الـ process المنفصلة دي، الـ relay، ليها طريقتين. الـ polling publisher بيعمل query على الـ outbox للصفوف اللي ماتنشرتش: "Works with any SQL database"، بس "Tricky to publish events in order". والـ change data capture المبني على الـ log، زي ما Debezium بيعمل، بيقرا الـ transaction log بتاع الداتابيز بدل كده؛ و Morling بيقول إن "As opposed to any polling-based approach, event capture happens with a very low overhead in near-realtime." وفي الحالتين الترتيب مهم: الـ outbox guide بتاع Microsoft بيأكد إن OrderCreated لازم يطلع قبل OrderUpdated، و Debezium بيستخدم id الـ aggregate كـ key للرسايل، فكل events الـ order الواحد بتروح نفس الـ partition وبالترتيب.

الحل: transaction واحدة، وبعدها relay

C# PlaceOrder.cs
public sealed class PlaceOrder(ShopDb db, IMessageBus bus){    public async Task HandleAsync(Order order, CancellationToken ct)    {        db.Orders.Add(order);        await db.SaveChangesAsync(ct); // committed        // A crash, deploy or broker outage here: the order exists,        // and no other service will ever hear about it        await bus.PublishAsync(new OrderPlaced(order.Id, order.Total), ct);    }}

دلوقتي الـ order والرسالة بتاعته بيتعملهم commit مع بعض أو مفيش حاجة خالص. والنشر شغل الـ relay:

C# OutboxRelay.cs
using Microsoft.EntityFrameworkCore;public sealed class OutboxRelay(ShopDb db, IMessageBus bus){    public async Task PublishPendingAsync(CancellationToken ct)    {        var pending = await db.Outbox.Where(m => m.PublishedAt == null)            .OrderBy(m => m.Sequence) // the order they were written in            .Take(100).ToListAsync(ct);        foreach (var m in pending)        {            await bus.PublishAsync(m.Id, m.Type, m.Payload, ct);            // A crash here publishes this row again on the next run            m.PublishedAt = DateTime.UtcNow;            await db.SaveChangesAsync(ct);        }    }}

الـ comment ده هو الصفقة اللي بتقبلها. Richardson بيقول إن الـ relay "might, for example, crash after publishing a message but before recording the fact that it has done so. When it restarts, it will then publish the message again." فالتوصيل بيبقى at least once، وعشان كده كل رسالة شايلة id صف الـ outbox: الـ consumers بيسجّلوه وبيتخطّوا التكرار، زي ما المقال اللي فات عن الـ idempotent consumers بيوضّح. ومقال الـ domain events بيوضّح التوصيل ده في .NET.

الطريقةإيه اللي ممكن يبوظ
احفظ وبعدين انشرcrash في النص بيضيّع الـ event من غير صوت
انشر وبعدين احفظالحفظ يفشل والـ consumers يتصرفوا على داتا مش موجودة
distributed transactionغالبًا مش مدعومة، وبتربط السيستمين، وبتفشل لما أي واحد يقع
outbox مع polling relayتكرار، فالـ consumers يشيلوه؛ والترتيب محتاج اهتمام؛ و latency بسيطة زيادة
outbox مع capture من الـ logتكرار برضه، وكمان tooling خاص بالداتابيز لازم تشغّله

تطبقها إزاي في مشروعك

  1. لاقي الـ dual writesدوّر على نشر للـ broker، و emails، وتحديثات cache، و HTTP calls بتشتغل بعد SaveChangesAsync على طول أو جوه transaction.
  2. ضيف outbox tableخزّن id و type و payload و sequence number في نفس الداتابيز اللي فيها داتا الـ business.
  3. اكتب في transaction واحدة، وانشر لوحدكضيف الرسالة مع التغيير في SaveChangesAsync واحدة، وشغّل relay واحد بينشر الصفوف المستنية بالترتيب.
  4. خلّي الـ consumers idempotentاستخدم id صف الـ outbox كـ message id، وخلّي كل consumer يسجّل الـ ids اللي عالجها.

الخلاصة

  • الحفظ وبعده النشر dual write: مفيش transaction بتغطي الاتنين، فالفشل بينهم بيعدّي في صمت.
  • كل ترتيب بيفشل في حتة: events ضايعة، أو events عن داتا عملت rollback، أو تكرار.
  • الـ distributed transactions غالبًا مش متاحة أو مش مرغوبة؛ اكتب مرة واحدة وطلّع الكتابة التانية منها.
  • صف الـ outbox اللي بيتعمله commit مع التغيير بيضمن إن الرسالة تتنشر لو، وبس لو، التغيير اتعمله commit.
  • الـ relay بيوصّل at least once، فالـ consumers لازم يشيلوا التكرار بالـ message id.

📚 المصادر

  1. Pattern: Transactional outbox — Chris Richardson, microservices.io
  2. Pattern: Polling publisher — Chris Richardson, microservices.io
  3. Reliable Microservices Data Exchange With the Outbox Pattern — Gunnar Morling, Debezium blog (2019)
  4. Implement the Transactional Outbox pattern by using Azure Cosmos DB — Azure Architecture Center, Microsoft Learn
  5. Subscribing to events — .NET Microservices e-book, Microsoft Learn

التعليقات (0)