---
name: saas-architecture-dataflow
description: Design precise architecture and data flow for SaaS, workflows, automations, and AI-enabled systems. Use for system boundaries, C4 views, DFDs, sequences, tenancy, APIs/events, data models, reliability, SLOs, capacity, deployment, and ADRs. استخدمها للتصميم البنيوي لا للتخطيط التجاري العام.
---

# SaaS Architecture and Data Flow

## عقد التشغيل

- **استخدمها عندما:** تحتاج حدود نظام أو multi-tenancy أو تدفق بيانات أو APIs أو events أو ADRs أو SLOs.
- **لا تستخدمها عندما:** المطلوب عصف فكرة أو هوية بصرية أو إصلاح صغير بلا تغيير عقد.
- **تستلم:** النطاق، الأدوار، القيود، مخرجات AI والتجربة، والتكاملات.
- **تملك وتنتج:** boundaries، C4/DFD/sequences، data/API contracts، consistency/failure decisions وADRs.
- **لا تملك:** threat model أو قرار تجربة المستخدم أو السياسة القانونية.
- **بوابة الخروج:** تدفقات قابلة للتشغيل وملاك للبيانات والفشل والحدود.
- **التسليم التالي:** الأمن يراجع المخاطر، وhandbook يثبت العقود والـADRs.

اتبع نموذج المسارات والملكية في `../../shared/references/operating-model.md`.

## المهمة

حوّل المتطلبات إلى معمارية يمكن لفريق مستقل تنفيذها ومراجعتها وتشغيلها. أنت لا ترسم صناديق جميلة؛ أنت توضح المسؤوليات، العقود، البيانات، حدود الثقة، الفشل، والقرارات.

## مبادئ

1. Architecture follows requirements and risks. لا تبدأ بالـ stack.
2. اختر Monolith modular افتراضيًا ما لم تثبت حاجة توزيع مستقلة أو حدود توسع/ملكية/عزل.
3. لا تستخدم Microservices أو Event-driven أو CQRS لمجرد الرواج.
4. اجعل البيانات وملكية السجل system-of-record صريحة.
5. كل تدفق يملك trigger، producer، consumer، contract، authorization، failure behavior، observability وowner.
6. التعددية `multi-tenancy` قرار أمني وبياني وتشغيلي، لا مجرد `tenant_id`.
7. صمم degradation وrecovery وrollback، لا happy path فقط.
8. استخدم diagrams as code ونصوصًا مرافقة؛ الرسم دون semantics غير كافٍ.

## سير العمل

### 1. تثبيت محركات التصميم

استخرج:

- Functional requirements and critical user journeys.
- Experience contracts، accessibility constraints، performance budgets، and NFRs/SLOs.
- data classification/residency/retention.
- tenancy and identity model.
- integrations and contracts.
- traffic/volume/concurrency assumptions.
- cost ceiling and team capability.
- AI components and autonomy.
- threats and regulatory constraints.

اربط كل محرك بـ `NFR/FR/RISK`.

### 2. حدود النظام والسياق

أنشئ C4 System Context:

- الأشخاص/الأدوار.
- النظام محل التصميم.
- الأنظمة الخارجية.
- اتجاهات العلاقة وغرضها ونوع البيانات.
- trust boundaries.

اكتب `architecture/01-system-context.md` مع Mermaid أو PlantUML ونص تفسير.

### 3. Container architecture

حدد applications/services/data stores/queues/object storage/identity/provider boundaries. لكل container:

- responsibility.
- owned data.
- exposed contracts.
- scaling unit.
- deployment unit.
- failure isolation.
- security boundary.
- owner.

لا تستخدم كلمة `service` دون مسؤولية وحدود بيانات.

### 4. Component views عند القيمة

أنشئ Component diagram فقط للمناطق المعقدة أو عالية المخاطر. لا توثق كل class يدويًا. ركز على:

- orchestration.
- policy/authorization.
- billing.
- workflow state machine.
- AI gateway/tool executor.
- integration adapters.
- audit/logging.

### 5. نموذج التعددية والعزل

قارن:

- Pooled app + pooled DB.
- Pooled app + schema/database per tenant.
- Siloed deployment.
- Bridge/hybrid tiers.

حدد:

- tenant resolution and immutable propagation.
- row/object authorization.
- admin/support impersonation controls.
- encryption keys and secrets scope.
- quotas/noisy-neighbor controls.
- backup/restore per tenant.
- data export/deletion.
- cross-tenant analytics boundary.
- migration and tier movement.

سجل القرار في ADR.

### 6. نمذجة البيانات

أنشئ:

- domain entities and ownership.
- logical schema/ERD.
- identifiers and tenant keys.
- lifecycle/state machines.
- invariants and unique constraints.
- audit/history requirements.
- PII/sensitive fields.
- retention/deletion/legal hold.
- migration/backfill strategy.
- cache/index/search derivation and invalidation.

لا تجعل cache أو vector index مصدر الحقيقة.

### 7. فهرس تدفقات البيانات

استخدم `../../shared/templates/data-flow-catalog.md`.

لكل تدفق وثق:

- trigger and correlation ID.
- data classification/minimization.
- AuthN/AuthZ and trust transition.
- contract/version.
- sync/async.
- idempotency/deduplication.
- ordering/consistency.
- timeout/retry/backoff/DLQ.
- partial failure/compensation.
- observability and ownership.

### 8. Sequence and workflow design

أنشئ sequence diagrams لـ:

- signup/login/tenant creation.
- core value workflow.
- admin action.
- billing/payment/refund/webhook.
- failure/retry/rollback.
- AI tool action with approval.
- data deletion/export.

لـ workflows طويلة العمر، حدد state machine، timers، retries، human tasks، cancellation، compensation، وversion migration.

### 9. عقود التكامل

- REST/HTTP: OpenAPI pinned version تدعمها الأدوات الحالية.
- Events/messages: AsyncAPI pinned version عند استخدام event-driven.
- Webhooks: signature، timestamp، replay window، idempotency، retries، endpoint rotation.
- Internal contracts: schemas، compatibility policy، ownership.
- Errors: stable codes، safe messages، correlation IDs.

حدد versioning policy وbackward compatibility وdeprecation.

### 10. الاتساق والمعاملات

اختر صراحة:

- strong vs eventual consistency.
- transaction boundary.
- outbox/inbox when crossing database-message boundary.
- saga/compensation للعمليات الموزعة.
- idempotent consumers.
- reconciliation jobs.

لا تستخدم distributed transaction أو saga دون شرح الفشل الذي تعالجه.

### 11. الاعتمادية والأداء والسعة

حدد:

- user-facing SLI/SLO/error budget.
- RTO/RPO.
- workload model and peak assumptions.
- bottlenecks and scaling unit.
- backpressure/load shedding/throttling.
- caching strategy and invalidation.
- dependency timeout/retry/circuit breaker.
- graceful degradation.
- backup restore tests and disaster scenarios.
- cost model per tenant/transaction/AI outcome.

### 12. النشر والبيئات

أنشئ Deployment view:

- dev/test/staging/prod isolation.
- network zones and egress.
- secrets/KMS.
- CI/CD and artifact provenance.
- migrations and rollback.
- feature flags/canary/blue-green where justified.
- observability pipeline.
- regional/data residency choices.

### 13. سجل القرارات

استخدم `../../shared/templates/adr-template.md` لكل قرار مرتفع الكلفة أو الخطر:

- tenant isolation.
- monolith vs services.
- sync vs async.
- database/storage.
- workflow engine.
- AI provider/gateway.
- auth model.
- eventing.
- deployment topology.

## المخرجات الإلزامية

```text
architecture/
├── 00-design-drivers.md
├── 01-system-context.md
├── 02-container-view.md
├── 03-component-views/
├── 04-tenancy-and-identity.md
├── 05-data-model-and-lifecycle.md
├── 06-data-flow-catalog.md
├── 07-sequence-and-state-diagrams.md
├── 08-api-event-webhook-contracts.md
├── 09-consistency-and-transactions.md
├── 10-reliability-performance-capacity.md
├── 11-deployment-and-environments.md
├── 12-observability.md
└── decisions/ADR-*.md
```

## مراجعة ذاتية إلزامية

قبل التسليم، أجب:

- أين مصدر الحقيقة لكل كيان؟
- كيف يُمنع عبور Tenant؟
- ماذا يحدث إذا تكرر الطلب أو الحدث؟
- ماذا يحدث إذا نجحت خطوة وفشلت التالية؟
- كيف نحذف أو نستعيد بيانات Tenant واحد؟
- كيف نراقب النتيجة لا صحة الخادم فقط؟
- ما أكبر تكلفة تشغيل غير ظاهرة؟
- ما القرار الذي يصعب الرجوع عنه ولماذا اتخذ الآن؟

## تعريف النجاح

- كل عنصر معماري له مسؤولية وعقد ومالك.
- الرسوم والنص والجداول لا تتعارض.
- توجد مسارات فشل واسترداد واختبارات، لا happy path فقط.
- التعددية والصلاحيات والبيانات موضحة من البداية.
- يمكن تحويل العقود إلى اختبارات آلية أو Schemas.
