نمط Saga للمعاملات الموزّعة
تعلّم كيفية الحفاظ على اتساق البيانات بين الخدمات المصغّرة دون معاملات موزّعة، باستخدام نمط Saga مع التنسيق اللامركزي والمركزي.
نمط Saga للمعاملات الموزّعة درس مجاني في System Design Basics for Backend Developers على CoddyKit. هذا هو الدرس 4 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في System Design Basics for Backend Developers، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة System Design Basics for Backend Developers 4 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
The Distributed Transaction Problem
In a monolith, one database transaction can update everything atomically. In microservices, each service owns its own database, so a single classic transaction across them is impractical.
How do you keep data consistent when an operation spans multiple services?
Why Not Two-Phase Commit?
Two-phase commit (2PC) can coordinate a distributed transaction, but it locks resources across services and blocks if the coordinator fails. It scales poorly and hurts availability — usually the wrong fit for microservices.
Enter the Saga
A Saga breaks a business transaction into a sequence of local transactions, one per service. Each step publishes an event or sends a command to trigger the next.
There is no global lock — consistency is achieved over time.
Compensating Transactions
If a later step fails, the saga cannot roll back like a database. Instead it runs compensating transactions that semantically undo the earlier steps.
- Order placed -> compensate by cancelling order
- Payment charged -> compensate by refunding
An Order Saga
Consider placing an order: reserve inventory, charge payment, schedule shipping. If payment fails, you compensate by releasing the inventory.
steps = ['reserve_inventory', 'charge_payment', 'schedule_shipping']
compensations = ['release_inventory', 'refund_payment', 'cancel_shipping']
done = []
for i, step in enumerate(steps):
ok = step != 'charge_payment'
if not ok:
print('FAILED at', step)
for j in reversed(range(len(done))):
print('compensate:', compensations[j])
break
done.append(step)
print('ok:', step)Choreography
In choreography, there is no central coordinator. Each service listens for events and reacts by doing its work and emitting the next event. It is decentralized and loosely coupled.
OrderCreated -> (Inventory) -> InventoryReserved
InventoryReserved -> (Payment) -> PaymentCharged
PaymentCharged -> (Shipping) -> OrderShippedChoreography Trade-offs
Choreography is simple for short flows but the overall logic is scattered across services. With many steps it becomes hard to understand and risks cyclic event dependencies.
Orchestration
In orchestration, a central orchestrator tells each service what to do and tracks progress. The workflow lives in one place, making complex sagas easier to reason about and monitor.
Orchestrator:
-> Inventory.reserve()
-> Payment.charge()
-> Shipping.schedule()
on failure -> run compensations in reverseIdempotency Is Mandatory
Messages can be delivered more than once, so every saga step and compensation must be idempotent. Use an idempotency key so re-processing the same message has no extra effect.
Eventual Consistency
Sagas give eventual consistency, not immediate. There is a window where the system is partially updated. Design the UI and business rules to tolerate this — for example, an order shown as PENDING until confirmed.
Choosing an Approach
Use choreography for simple flows with few participants, and orchestration when the workflow is complex or needs central visibility. Either way, make steps idempotent and define a compensation for every action.
Quick Check
Test your understanding of the Saga pattern.
Recap
You learned how microservices stay consistent without distributed transactions:
- Sagas chain local transactions with compensations for failures
- Choreography is decentralized; orchestration is centralized
- Steps must be idempotent against duplicate delivery
- The result is eventual consistency, which the design must tolerate
الأسئلة الشائعة
هل درس «نمط Saga للمعاملات الموزّعة» مجاني؟
نعم — نص درس «نمط Saga للمعاملات الموزّعة» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة System Design Basics for Backend Developers، انتقل إلى CoddyKit PRO. تتضمن دورة System Design Basics for Backend Developers 4 دروس في المجموع.
ماذا ستتعلم في «نمط Saga للمعاملات الموزّعة»؟
تعلّم كيفية الحفاظ على اتساق البيانات بين الخدمات المصغّرة دون معاملات موزّعة، باستخدام نمط Saga مع التنسيق اللامركزي والمركزي. تتمرن على System Design Basics for Backend Developers مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ System Design Basics for Backend Developers؟
لا تُشترط خبرة سابقة. System Design Basics for Backend Developers على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 4 من أصل 4.
كم من الوقت يستغرق درس «نمط Saga للمعاملات الموزّعة»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس System Design Basics for Backend Developers هذا؟
نعم. كل درس في System Design Basics for Backend Developers يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- تفكيك التطبيقات الأحادية
- اكتشاف الخدمات وسجلّها
- أنماط الاتصال بين الخدمات
- نمط Saga للمعاملات الموزّعة