Türkçe

TuranBilgi Business Platform

Event-driven Distributed Microservices Architecture

July 2025 – Present

TuranBilgi is an API-first, multi-client business platform built on a domain-oriented microservices architecture. It supports complex business workflows and real-time communication through REST and GraphQL APIs alongside asynchronous event-driven messaging. Its services are designed to evolve and scale independently, with clear domain boundaries that support fault isolation, maintainability, and long-term extensibility.

🧭 Platform Overview & Architectural Focus

TuranBilgi is designed as a unified backend system serving multiple client applications through a shared platform API surface implemented through independently addressable microservices. All business logic, authentication, authorization, and real-time capabilities are centralized within the platform and exposed through a shared API layer. This ensures consistent behavior across all consuming clients while allowing internal services to evolve independently. It is designed around long-term platform sustainability rather than short-term feature delivery. Its architecture emphasizes:

  • API-First Design (GraphQL-First Client Consumption)

    TuranBilgi follows an API-first architecture in which microservices expose well-defined interfaces according to their domain responsibilities. The platform supports both REST and GraphQL where appropriate, while preserving independent service ownership and consistent business rules.

    GraphQL is the preferred default for frontend business operations when flexible data selection, related-entity queries, and structured queries and mutations benefit the application. REST remains a fully supported interface and can be selected whenever it is better suited to a particular operation, integration contract, or resource-access pattern.

    Core Business, Discourse, and Realtime expose both REST and GraphQL APIs. Frontend developers can select the most appropriate interface for each use case and may use both API styles within the same application.

    This is a preference, not an exclusive protocol requirement. It does not require duplicating business logic across REST controllers and GraphQL resolvers: equivalent operations reuse the same underlying application and domain logic, including authorization and validation.

    Other microservices may expose specialized interfaces according to their responsibilities. For example, payment processing uses REST for its transactional API and provider webhooks, while CMS exposes its Payload CMS interfaces and its dedicated authentication endpoint.

    Synchronous request-response operations can use either REST or GraphQL. Long-running workflows, background processing, and inter-service event propagation continue to use the platform's asynchronous messaging architecture, including Kafka and RabbitMQ where appropriate.

  • Event-Driven Communication Model

    TuranBilgi adopts an event-driven architecture for internal coordination, background processing, and state propagation between services. Asynchronous messaging (Kafka & RabbitMQ) enables loose coupling between services, improves resilience, and supports scalable background processing.

    • Kafka is used for internal domain events, workflow continuation, and background processing. It enables replayable event streams, horizontally scalable consumers, and loose coupling between microservices using the outbox pattern.
    • RabbitMQ is intentionally limited to external integrations such as email, SMS, and third-party providers, acting as a resilient boundary for side-effects, retries, and failure isolation.
    • Synchronous REST APIs are used primarily for queries, validation, and administrative interactions, not for long-running or state-changing workflows.

    This clear separation of communication patterns ensures resilience, observability, and long-term maintainability.

  • Service Boundaries & Fault Isolation

    The platform is composed of multiple domain-focused microservices, each owning its data model and execution context. This prevents cascading failures and ensures that issues in one domain (such as discussion, chat, or real-time notification) do not compromise core business functionality.

  • Horizontal Scalability

    All services are designed to be stateless and container-friendly, enabling independent horizontal scaling of Core, Discourse, Real-Time, Payment, and AI components or microservices based on workload characteristics.

  • Polyglot Persistence

    Each service uses the storage technology best suited to its domain:

    • PostgreSQL for transactional and relational data
    • MongoDB for document-oriented and interaction-heavy workloads
    • Redis for caching, coordination, and real-time state management

    This approach optimizes performance while preserving clear data ownership and service autonomy and maintainability.

  • Real-Time Reliability

    WebSocket-based presence, notifications, and messaging are designed to remain consistent and responsive under concurrent load, supporting real-time collaboration and communication use cases at scale.

  • Clean Separation of Concerns

    Authentication, business logic, communication, payments, and intelligence are treated as independently bounded domains. This enables long-term evolution of the platform without cross-service entanglement or architectural rewrites.

  • Platform Evolution Philosophy

    TuranBilgi is intentionally structured for incremental evolution. New services, additional client applications (web, mobile, desktop), and external integrations can be introduced without architectural rewrites or disrupting existing functionality, with preserving platform stability while enabling continuous growth.

🧩 Platform Microservices

TuranBilgi platform consists of several domain microservices, each focused on a specific area of platform functionality while communicating and coordinating through events or synchronous API calls.

  1. ⚙️ Core Business Microservice
  2. 💬 Discourse Microservice
  3. 💳 Payment, Billing & Financial Processing Microservice
  4. 📝 CMS Microservice (Content Management & Administration Layer)
  5. 📡 Real-Time Communication, Notification & Audit Processing Microservice
  6. 🤖 AI Microservice

⚙️ Core Business Microservice

The Core Business microservice is implemented using Node.js (Express.js with TypeScript) and exposes both REST and GraphQL APIs. It serves as the primary orchestration and transactional domain service of the platform, coordinating long-running business workflows, enforcing business rules, and managing the lifecycle of core business entities.

Unlike the other microservices in the Turan Bilgi Platform ecosystem—which are implemented using established frameworks such as NestJS and FastAPI—the Core Business microservice deliberately adopts a custom lightweight application framework built on top of Express.js (with potential future support for Fastify).

This decision was intentional and strategic. The goal is to avoid long-term lock-in to any specific backend framework, while still adopting many of the architectural advantages provided by modern frameworks such as modularity, dependency injection, structured bootstrapping, and strong separation of concerns. By implementing these capabilities in a lightweight custom layer rather than relying on a full framework, the platform retains maximum architectural flexibility and long-term control over its technical ecosystem.

This microservice does not replace domain ownership of other services. Instead, it acts as:

  • The central workflow coordinator
  • The transactional boundary for core business entities
  • The external integration gateway
  • The event translation layer between internal domain events and external side effects

It ensures that domain services remain decoupled from infrastructure and third-party concerns.

Core Responsibilities:

Business Workflow Orchestration

The Core Business microservice supports a collaborative and moderated workflow where users and administrators interact to create, refine, and finalize ideas, projects, contracts, invoices, and support tickets. It manages multi-step, stateful workflows that span multiple domains and user roles:

  1. Idea Management & Discussion:
    • Users or prospective clients submit ideas into the system.
    • Moderator administrators review submissions and may propose refinements or initiate new idea threads.
    • All discussions and refinements are handled via the Discourse microservice, allowing commenting and refining ideas.
    • Collaborative iteration continues until the idea reaches maturity.
  2. Project Creation & Collaboration:
    • Once an idea and its discussion thread are finalized, administrators can create a project and associated applications based on the root idea and the agreed upon discussion thread.
    • Project details and applications are further discussed and refined via the Discourse microservice.
    • Consensus is achieved before progressing to contractual agreement.
  3. Contract Management:
    • After project agreement, contracts are created and managed within the Core Business microservice.
    • Contract terms are discussed between administrators and the associated users via the Discourse microservice.
    • Once agreed, contracts transition to an immutable state, and associated project definitions and obligations become locked and auditable.
  4. Invoice Generation & Payment Coordination:
    • Administrators generate invoices over time based on agreed contract terms.
    • Users pay invoices.
    • Invoice details and payment-related discussions occur via the Discourse microservice.
    • Payment execution and provider-specific integrations are owned exclusively by the Payment microservice, which operates independently and is intentionally isolated for security and compliance reasons.
  5. Support Ticket Management:
    • Users create support tickets within the Core Business microservice.
    • Support administrators review, respond, and resolve tickets.
    • Ticket discussions occur via the Discourse microservice until resolution.
    • Upon resolution, tickets are closed, the resolutions are recorded, and the tickets are archived with immutable records.
Authentication & Account Management

In addition to business workflows, the Core Business microservice is responsible for:

  • User and administrator authentication and authorization
  • Account registration, login, and profile management
  • Email and phone verification
  • Password reset and email change workflows
  • Role-based access control enforcement
  • Account lifecycle management
  • Publishing of internal audit and business related events
Event-Driven Architecture & Transactional Consistency

The Core Business microservice follows a strict event-driven architecture using Apache Kafka as the internal streaming backbone.

Transactional Outbox Pattern (PostgreSQL-Based)

All domain state changes and corresponding event publications are executed atomically using the Transactional Outbox Pattern:

  • Business data and outbox records are written within the same PostgreSQL transaction.
  • If the transaction commits, both state change and event are persisted.
  • If the transaction rolls back, neither is persisted.

A background publisher process reads the outbox table and publishes events to Kafka, guaranteeing:

  • No dual-write problem
  • No lost events
  • Strong consistency between domain state and emitted events
  • Retryable and observable event publishing

This design eliminates the need for MongoDB-based outbox persistence.

Event Translation & External Side Effects

The Core Business microservice acts as the central gateway for external asynchronous integrations, while preserving a fully event-driven internal architecture.

  • All domain microservices emit internal domain events via Kafka using their own outbox patterns.

  • The Core Business microservice is the sole consumer responsible for translating selected domain events into external side effects, such as:

    • Email notifications
    • SMS delivery
    • Third-party integrations
    • Non-domain external integrations

External integrations or side effects are never executed directly inside domain logic. Instead:

  1. Domain services publish intent-based events (e.g., user registered, comment replied, invoice paid).
  2. The Core Business microservice consumes these events.
  3. It applies integration-specific logic or policies.
  4. It enqueues external jobs via RabbitMQ.
  5. Dedicated background workers process these job queues, handling retries, failures, and delivery guarantees without blocking domain workflows.

This design ensures infrastructure concerns never leak into domain services, and consistent handling of external systems.

Implementation Architecture:

Beyond its domain responsibilities, the Core Business microservice is designed with a modular, layered architecture inspired by modern backend frameworks, while remaining framework-agnostic.

Key architectural characteristics include:

Custom Framework Layer

A lightweight internal application framework provides:

  • Structured service bootstrapping
  • Dependency injection
  • Modular service registration
  • Infrastructure lifecycle management
  • Graceful startup and shutdown
  • Structured logging and observability

This internal framework enables the project to maintain framework-level architecture without framework-level lock-in.

Layered Service Architecture

The system follows a strict layered structure:

  • Server Layer
  • Application Middleware Layer
  • Route (Controller) / Resolver Layer
  • Service Layer
  • Repository Layer
  • Database Layer

This design enforces strong separation between:

  • Transport Layer (REST / GraphQL)
  • Business Logic
  • Data Persistence
  • Infrastructure Integrations
Dependency Injection Container

A lightweight dependency injection container manages service lifecycles and dependencies. Services, repositories, infrastructure adapters, and resolvers are registered during application bootstrap, allowing:

  • Lazy instantiation
  • Testability
  • Modular dependency graphs
  • Infrastructure isolation
Structured Application Bootstrapping

Application startup follows a controlled lifecycle:

  1. Infrastructure services initialize (database, cache, messaging).
  2. Domain services and repositories are registered.
  3. API routes and GraphQL resolvers are mounted.
  4. Health checks and observability endpoints are activated.

This structured initialization ensures that all dependencies are validated before the microservice becomes available.

Graceful Shutdown & Connection Management

The service implements graceful shutdown procedures to ensure operational reliability. On shutdown signals:

  • HTTP connections are drained
  • Messaging clients are disconnected
  • Database connections are closed
  • Background processes terminate safely

This prevents resource leaks, partial transactions, and inconsistent system states.

Infrastructure Components:

  • PostgreSQL

    Primary relational database for business-critical transactional data (users, admins, ideas, projects, applications, contracts, invoices, support tickets) and transactional outbox storage. PostgreSQL serves as both the system of record and the event consistency anchor.

  • Redis

    Caching, distributed coordination, rate limiting, session/token optimization, and performance improvements.

  • Kafka

    Internal event streaming backbone for inter-service communication, domain events and audit propagation, and workflow coordination.

  • RabbitMQ

    Used exclusively for asynchronous job processing and external integration queuing, email and SMS dispatch, and retryable side-effect-driven workflows. RabbitMQ is intentionally separated from Kafka to clearly distinguish between Domain events (Kafka) and Infrastructure jobs (RabbitMQ).

Architectural Rationale:

This architecture ensures:

  • Strong transactional guarantees via PostgreSQL-based outbox
  • Clear separation between domain logic and external side effects
  • Strong decoupling between microservices
  • Reliable and observable event publishing
  • No dual-write inconsistencies
  • Clean boundary between domain events and infrastructure jobs
  • Consistent, observable, and retryable external integrations
  • Simplified operational control over third-party dependencies
  • Preservation of domain ownership while enabling coordinated workflows
  • Long-term architectural flexibility by avoiding framework lock-in

💬 Discourse Microservice (Shared Collaboration Layer)

To support structured communication, decision-making, and accountability across all business domains, TuranBilgi includes a dedicated Discourse microservice. This service implements a unified, reusable interaction model that enables threaded discussions, contextual replies, moderation workflows, and historical traceability for all major business entities.

Rather than embedding isolated comment systems within individual services, TuranBilgi centralizes all collaborative interactions into a shared domain layer, ensuring consistency, scalability, and governance.

The microservice is implemented using NestJS with TypeScript and exposes both REST and GraphQL interfaces. It operates in close coordination with the Core Business microservice through an event-driven Saga-based architecture.

Shared Interaction Model:

All major platform entities require structured communication and collaborative workflows:

Entity Purpose Discussion Support
Idea Brainstorming Yes
Support Ticket Problem Solving Yes
Project Coordination Yes
Project App Requirements Analysis Yes
Contract Negotiation Yes
Invoice Billing Questions Yes
Payment Dispute Resolution Yes

These entities share common interaction requirements:

  • Threaded conversations
  • Nested replies
  • Moderation and reporting
  • Edit and deletion history
  • Actor accountability
  • Contextual linking to business entities

This unified design is referred to internally as the Shared Interaction Model.

Core Responsibilities:

The Discourse microservice is implemented using NestJS and provides both REST and GraphQL APIs. It operates independently from the Core Business API and focuses exclusively on collaborative workflows. Key responsibilities include:

  1. Thread & Comment Management
    • Creation and management of discussion threads
    • Hierarchical reply structures
    • Entity-agnostic attachment of discussions
    • Rich metadata support (status, visibility, ownership)
    • Soft deletion and version history
  2. Moderation & Governance
    • User and administrator moderation tools
    • Reporting and review workflows
    • Content visibility control
    • Policy enforcement
    • Abuse detection and escalation pipelines
  3. Accountability & Auditability
    • Immutable activity logs
    • Per-action attribution
    • Historical change tracking
    • Legal and compliance support
  4. API & Developer Interfaces

    The service exposes:

    • REST APIs with OpenAPI (Swagger) documentation
    • GraphQL APIs with Apollo Sandbox support
    • JWT-secured endpoints for client and service access
    • Legal and compliance support

    This dual-interface strategy enables frontend teams to select the most appropriate interaction model for each client application.

Data Management:

The interaction subsystem is optimized for high-volume, write-heavy collaboration workloads.

  • MongoDB is used for:
    • Thread roots
    • Comments and replies
    • Moderation reports
    • Revision histories
    • Event streaming outboxes
  • PostgreSQL (via Core Business Microservice)
    remains the source of truth for business entities.

All discussions are linked to business entities through a generic entity reference model, enabling flexible cross-domain associations without schema coupling.

Event Integration:

The service integrates with the platform’s event-driven infrastructure.

  • Produces Events For:
    • New comments
    • Moderation actions
    • Resolution updates
    • Thread lifecycle changes
  • Consumes Events For:
    • Entity deletion
    • Access revocation
    • User suspension
    • Workflow transitions

This ensures synchronization between business workflows and interaction state.

Architectural Benefits:

The Discourse microservice provides:

  • Centralized collaboration logic
  • Consistent user experience across domains
  • Independent scalability
  • Reduced duplication
  • Strong governance capabilities
  • Simplified compliance auditing
  • Clean domain boundaries

It functions as the platform’s unified collaboration and discourse layer.

💳 Payment, Billing & Financial Processing Microservice

To support secure, scalable, and regulation-compliant financial operations, TuranBilgi includes a dedicated Payment, Billing & Financial Processing microservice. This microservice handles payment intents, billing workflows, PSP integrations, settlement reconciliation, and fraud prevention, isolating financial execution from core business logic and maintaining strong transactional boundaries.

Rather than embedding payment logic directly within the Core Business API, TuranBilgi isolates all monetary processing into a specialized domain service. This separation ensures strong security boundaries, regulatory compliance, independent scalability, and fault isolation for all financial operations.

The microservice is implemented using NestJS with TypeScript and exposes REST APIs for transactional workflows and webhook integrations. It operates in close coordination with the Core Business microservice through an event-driven Saga-based architecture.

Architectural Role:

The Payment microservice functions as the platform’s financial execution and settlement layer. It is responsible for:

  • Orchestrating payment lifecycles
  • Integrating with external payment service providers (PSPs)
  • Ensuring transactional integrity
  • Emitting authoritative payment events
  • Supporting reconciliation and audit workflows

All financial state transitions are managed locally and synchronized with other services via Kafka events, avoiding cross-service database coupling.

Core Responsibilities:

1. Payment Orchestration & Processing

The microservice manages the full lifecycle of invoice payments, including:

  • Creation of payment intents linked to invoices
  • Integration with third-party PSPs (e.g., iyzico)
  • Secure card and wallet payment handling
  • Multi-currency transaction support (TRY, EUR, USD)
  • 3D Secure and fraud-prevention workflows
  • Idempotent payment execution
  • Retry and failure recovery mechanisms

All payment operations are executed within database transactions and coordinated through the outbox pattern to guarantee consistency.

2. External Provider Integration Layer

A dedicated adapter layer abstracts third-party payment providers and normalizes their APIs into a unified internal interface. This layer supports:

  • Provider-specific request/response mapping
  • Signature and webhook verification
  • Error normalization
  • Rate-limit and timeout handling
  • Provider failover strategies
  • Future extensibility for additional PSPs

This design enables seamless migration or multi-provider support without impacting upstream business logic.

3. Webhook & Settlement Processing

The microservice exposes secure webhook endpoints to receive asynchronous confirmations and settlement notifications from PSPs. Key responsibilities include:

  • Cryptographic signature validation
  • Idempotent webhook handling
  • Payment status reconciliation
  • Settlement confirmation processing
  • Dispute and chargeback handling
  • Refund and reversal workflows

Webhook processing pipelines are isolated from public APIs to prevent external interference with transactional state.

4. Financial Event Production & Saga Coordination

The Payment microservice participates in distributed business workflows using event-driven Saga choreography. It emits domain events such as:

  • PaymentInitiated
  • PaymentPending
  • PaymentConfirmed
  • PaymentFailed
  • PaymentRefunded
  • SettlementCompleted

These events are published via the MongoDB Outbox and Kafka pipeline and consumed by the Core Business and Real-Time services to update invoice states, trigger notifications, and generate audit records. No direct database access between services is permitted, preserving domain isolation.

5. Reconciliation & Reporting Subsystem

To ensure long-term financial accuracy and regulatory compliance, the microservice includes automated reconciliation pipelines. These processes support:

  • Daily PSP settlement comparison
  • Invoice-to-payment matching
  • Currency conversion validation
  • Discrepancy detection
  • Manual adjustment workflows
  • Financial report generation

This subsystem provides resilience against message loss, provider outages, and partial failures.

6. Fraud Prevention & Compliance Support

The payment service incorporates security and compliance controls, including:

  • Velocity and anomaly detection
  • Duplicate transaction suppression
  • Risk-based payment scoring
  • Audit trail generation
  • MASAK and AML alignment support
  • GDPR and KVKK–compliant data handling

Sensitive card data is never stored within platform databases and is handled exclusively by certified PSPs.

API & Integration Interfaces:

The Payment microservice exposes specialized APIs optimized for transactional reliability.

Supported Interfaces
  • REST APIs for payment creation and management
  • Secure webhook endpoints for provider callbacks
  • Internal service APIs for invoice validation
  • JWT and mutual-authenticated service endpoints

GraphQL is intentionally excluded from payment execution paths to reduce complexity and ensure deterministic transactional behavior.

Data Management:

The microservice maintains its own isolated relational database optimized for financial workloads.

  • PostgreSQL is used for:
    • Payment records
    • Provider references
    • Settlement records
    • Reconciliation logs
    • Adjustment entries
  • MongoDB is used for:
    • Event outboxes
    • Integration logs
    • Webhook payload archives

All monetary records are immutable and append-only, ensuring auditability and traceability.

Event Integration:

The microservice is tightly integrated with TuranBilgi’s event-driven infrastructure.

  • Produces Events For:
    • Payment lifecycle transitions
    • Settlement confirmations
    • Refunds and reversals
    • Dispute resolutions
  • Consumes Events For:
    • Invoice creation
    • Invoice cancellation
    • User account status changes
    • Contract lifecycle updates

This bidirectional integration enables consistent financial synchronization across distributed domains.

Distributed Reliability & Consistency:

To guarantee financial correctness in a distributed environment, the Payment microservice employs:

  • Transactional outbox pattern
  • Exactly-once event publishing
  • Idempotent command handling
  • Optimistic locking
  • Compensating actions for failed workflows
  • Automated reconciliation jobs

These mechanisms ensure consistency without requiring distributed transactions.

Architectural Benefits:

The Payment, Billing & Financial Processing microservice provides:

  • Strong financial domain isolation
  • Enhanced security boundaries
  • Regulatory compliance readiness
  • Independent scalability
  • Provider-agnostic payment abstraction
  • Fault-tolerant transaction processing
  • Long-term auditability
  • Reduced operational risk

It functions as the platform’s dedicated financial execution and settlement authority while remaining loosely coupled to core business workflows.

📝 CMS Microservice (Content Management & Administration Layer)

TuranBilgi includes a dedicated Content Management System (CMS) microservice for managing platform content and providing a controlled administrative interface. The CMS is implemented using Payload CMS on top of Next.js and TypeScript, with PostgreSQL as its persistent data store.

The CMS is intentionally separated from the Core Business microservice. It owns content-management concerns such as posts, media, and the CMS administrative interface, while Core remains the authoritative source for administrator identity, authentication, authorization, and account lifecycle management.

This separation prevents the CMS from becoming a second identity system and allows the administrative interface to evolve independently from the platform's core microservice.

Architectural Role

The CMS microservice functions as the platform's:

  • Content management layer
  • Administrative content interface
  • Media management layer
  • CMS-specific administrator projection
  • Payload session and administrative UI layer

It does not become the authoritative owner of administrator identities or credentials.

The architectural ownership boundary is therefore:


          TuranBilgi Platform

             ┌───────────┐
             │   Core    │
             │ Business  │
             └─────┬─────┘
                   │
        Identity / Authentication
        Authorization / Admin Roles
                   │
                   ▼
             ┌───────────┐
             │    CMS    │
             │  Payload  │
             └─────┬─────┘
                   │
     ┌─────────────┼─────────────┐
     ▼             ▼             ▼
  Users          Posts         Media
 Projection     Content       Assets

    

The CMS therefore owns CMS data, while Core owns identity and business authority.

Core Responsibilities

The CMS microservice provides the following capabilities:

  1. Content Management

    The CMS provides administrative management of platform content through Payload CMS.

    Current content collections include:

    • Posts
    • Media
    • Users

    Posts represent managed platform content, while Media provides centralized management of uploaded content and assets.

  2. Administrative Interface

    Payload provides the CMS administration interface through the platform's administrative web application.

    The CMS exposes the administrative interface independently from the Core Business API, allowing CMS functionality and presentation to evolve without coupling the Core service to a specific CMS implementation.

  3. CMS User Projection

    The CMS maintains a local Users collection containing a projection of Core administrator identity.

    Each CMS user contains:

    • coreUserId — authoritative Core administrator identifier
    • email — administrator email address
    • role — CMS authorization role

    These fields are read-only from the CMS administration interface.

    CMS users are therefore not independently created or managed as administrator identities. They are synchronized from Core when an administrator establishes a CMS session.

  4. CMS Authorization

    CMS access is explicitly restricted to administrator roles defined by Core.

    The current CMS role model, inherited from Core microservice, includes:

    • SUPER_ADMIN
    • ADMIN
    • MANAGER
    • ACCOUNTANT
    • SUPPORT
    • MODERATOR
    • CONTENT_MANAGER

    CMS access is granted only when the authenticated Core administrator possesses one of these recognized roles.

    User-management capabilities are further restricted to SUPER_ADMIN and ADMIN, while content-management capabilities can be assigned to SUPER_ADMIN, ADMIN, and CONTENT_MANAGER roles.

Authentication Architecture

The CMS deliberately does not authenticate administrator passwords itself.

Instead, authentication follows a two-stage trust model:


Browser
   │
   │ 1. Authenticate CMS client
   ▼
Core Business API
   │
   │ Client token
   │
   │ 2. Authenticate administrator
   ▼
Core Business API
   │
   │ Core Access Token
   ▼
Browser
   │
   │ 3. Exchange Core token
   ▼
  CMS
   │
   │ Verify Core token
   │ Check administrator role
   │ Synchronize CMS user projection
   │ Create Payload session
   ▼
Payload CMS Session Cookie

    

The administrator password is submitted directly from the browser to Core. It is never transmitted to the CMS service.

The resulting Core access token is then presented to the CMS, which cryptographically verifies the token and validates the administrator's role before establishing a normal Payload CMS session.

This produces a clear security boundary:


Core
 ├── Administrator credentials
 ├── Administrator identity
 ├── Authentication
 ├── Authoritative roles
 └── Account lifecycle
             │
             │ verified Core access token
             ▼
CMS
 ├── CMS user projection
 ├── CMS authorization
 ├── Payload session
 └── Content administration

    

Core-Authoritative Authentication Flow

The CMS login process consists of three logical stages.

1. CMS Client Authentication

The CMS browser client first authenticates itself with Core using the registered TuranBilgi CMS web client identifier.

The client identifier is intentionally public and identifies the registered CMS client. It is not a secret credential.

Core returns a client authentication token that permits the browser to perform the administrator authentication request.

2. Administrator Authentication

The browser submits the administrator's email address and password directly to Core using the client token.

Core performs the authoritative administrator authentication and returns a signed Core access token containing the authenticated actor and its authoritative role.

The CMS never receives the administrator password.

3. CMS Session Establishment

The browser sends the Core access token to the CMS.

The CMS:

  1. Verifies the Core access token cryptographically.
  2. Validates its issuer and audience.
  3. Validates the token type and version.
  4. Validates the administrator actor.
  5. Validates the administrator's Core role.
  6. Creates or updates the corresponding local CMS user projection.
  7. Creates a normal Payload CMS session.
  8. Returns the Payload authentication cookie to the browser.

The browser can then operate normally within the Payload administration interface.

This approach combines centralized identity authority with local CMS session management without requiring the CMS to maintain a second administrator password database.

Token Verification

The CMS verifies Core access tokens using the platform's internal JWT trust configuration.

The token is expected to contain:

  • Core-issued identity
  • Administrator actor information
  • Administrator Core user ID
  • Administrator email
  • Authoritative CMS role
  • Token type and version
  • Subject
  • Issuer
  • Audience

The CMS additionally validates that the token subject corresponds to the expected Core actor identity.

Consequently, possessing a syntactically valid JWT is not sufficient for CMS access. The token must represent a valid Core administrator and contain a role recognized by the CMS authorization model.

Payload Authentication Integration

Payload's normal local username/password authentication strategy is disabled for the CMS administrator collection.

Instead, the CMS uses a custom authentication strategy and session mechanism integrated with Core.

Payload remains responsible for:

  • CMS session management
  • Session cookies
  • Administrative UI authentication state
  • CMS user representation
  • CMS authorization hooks

Core remains responsible for:

  • Administrator credentials
  • Administrator authentication
  • Administrator identity
  • Authoritative administrator roles
  • Account lifecycle

This creates a clean separation between identity authority and application-specific session management.

Data Management

The CMS maintains its own PostgreSQL database and does not directly access Core's database.

The CMS database contains CMS-owned data such as:

  • CMS user projections
  • Posts
  • Media metadata
  • Payload-managed system data
  • CMS migrations

The Users collection is deliberately limited to the information required by the CMS. Core remains the authoritative source for the corresponding administrator identity.

No cross-service database access is required.


Core PostgreSQL
      │
      │ Core API / signed token
      ▼
     CMS
      │
      ▼
CMS PostgreSQL

    

This preserves the platform's microservice data-ownership boundary.

API & Integration Interfaces

The CMS exposes Payload's application interfaces and its own authentication endpoint.

These include:

  • Payload administrative interface
  • Payload REST APIs
  • Payload GraphQL API
  • GraphQL Playground
  • CMS-specific REST authentication endpoint
  • Internal communication with Core

The CMS-specific administrator login endpoint acts as the trust boundary between Core authentication and Payload session establishment.

The CMS therefore does not duplicate Core's authentication API. Instead, it performs a controlled token exchange from Core identity to a CMS-local session.

Future Event-Driven Integration

As the platform's event-driven architecture evolves, the CMS microservice is expected to integrate with the platform's Kafka-based event streaming infrastructure.

The future CMS event architecture will have two complementary responsibilities:

  1. Publish CMS domain and content events
  2. Consume authoritative administrator lifecycle events from Core

This will allow the CMS to participate in the platform-wide asynchronous event architecture without introducing direct database coupling between microservices.

The future architecture is expected to look like:


                       Kafka
                        │
          ┌─────────────┼─────────────┐
          │                           │
          ▼                           ▼
  bilgi.admin.event          System-wide Topics
          │                           ▲
          │                           │
          ▼                           │
         CMS                         CMS
    Kafka Consumer              Outbox Worker
          │                           │
          ▼                           │
   CMS PostgreSQL                     │
          │                           │
          │                           │
          └──────────────┐    ┌───────┘
                         │    │
                         ▼    ▼
                      CMS Domain
                        Events
                         │
                         ▼
                  bilgi.audit.logs
                         │
                         ▼
                     Realtime
                         │
                         ▼
                 MongoDB Audit Log

    
CMS Kafka Outbox

CMS content changes should be integrated with Kafka through an outbox pattern rather than publishing directly from application request handlers.

When a CMS transaction changes business-relevant content, the corresponding event is recorded in a CMS outbox within the same PostgreSQL transaction.

A dedicated CMS outbox worker then publishes pending events to Kafka.

Conceptually:


CMS Request
    │
    ▼
CMS PostgreSQL Transaction
    ├── Update CMS data
    └── Insert Outbox Event
              │
              ▼
        CMS Outbox Worker
              │
              ▼
            Kafka

    

This provides reliable event publication and avoids the failure mode where CMS data is successfully committed but the corresponding Kafka event is lost.

The outbox worker should be designed for idempotent processing, retry handling, and safe recovery after failures.

Audit Events

One important consumer of CMS events will be the platform audit system.

The CMS outbox worker will publish relevant content-management events to the platform's bilgi.audit.logs topic.

The Realtime microservice will consume these events and persist the resulting audit records in its own MongoDB database.

This preserves service ownership:


CMS
 └── owns CMS content and produces content events

Realtime
 └── owns audit-log persistence and MongoDB audit records

    

CMS therefore does not write directly to the Realtime database or to the audit-log MongoDB.

For example, future CMS events could represent operations such as:


CMS_POST_CREATED
CMS_POST_UPDATED
CMS_POST_DELETED
CMS_MEDIA_CREATED
CMS_MEDIA_UPDATED
CMS_MEDIA_DELETED
CMS_USER_SESSION_CREATED
CMS_ADMIN_ACCESS_DENIED

The exact event taxonomy can evolve with the platform's audit requirements.

System-Wide Events

The CMS outbox worker may also publish selected CMS domain events to other system-wide Kafka topics.

These events can subsequently be consumed independently by other TuranBilgi microservices.

For example:


              CMS
               │
         CMS Outbox
               │
               ▼
             Kafka
      ┌────────┼─────────┐
      ▼        ▼         ▼
  Audit      Search    Other
  Events     Events    Consumers
      │
      ▼
   Realtime

    

This allows future integrations to be added without modifying the CMS request path for every new consumer.

The CMS therefore becomes a normal participant in the platform's event-driven architecture rather than a special-case content service.

Core Administrator Event Consumption

The CMS will also become a Kafka consumer of the Core microservice's bilgi.admin.event topic.

This topic is authoritative for administrator lifecycle changes originating in Core.

The CMS consumer will use these events to keep its local Users projection synchronized with Core.

Conceptually:


Core
 │
 │ Administrator lifecycle event
 ▼
Kafka
 │
 │ bilgi.admin.event
 ▼
CMS Kafka Consumer
 │
 ├── Update CMS Users projection
 ├── Create/update/remove local user
 └── Invalidate affected CMS sessions

    

Relevant Core administrator events may include:

  • Administrator created
  • Administrator updated
  • Administrator role changed
  • Administrator blocked
  • Administrator unblocked
  • Administrator removed
  • Administrator account status changed

The exact event names and payload contracts remain owned by Core.

User Projection Synchronization

When Core changes administrator information, the CMS consumer updates the corresponding local Users document using coreUserId as the stable external identity.

For example:


Core administrator
       │
       │ bilgi.admin.event
       ▼
CMS consumer
       │
       ▼
Users.coreUserId
       │
       ├── email
       ├── role
       └── account state

    

The CMS therefore does not need to periodically query Core merely to discover administrator changes.

The event stream becomes the normal synchronization mechanism.

Session Invalidation

Administrator lifecycle events are also important for active CMS sessions.

If Core reports that an administrator has:

  • been blocked,
  • been removed,
  • lost CMS access,
  • or had their role changed such that they are no longer authorized to access CMS,

the CMS must invalidate the corresponding active Payload session(s).

The intended flow is:


Core
 │
 │ ADMIN_BLOCKED / ADMIN_REMOVED /
 │ ADMIN_ROLE_CHANGED
 ▼
Kafka
 │
 │ bilgi.admin.event
 ▼
CMS Consumer
 │
 ├── Update Users projection
 │
 └── Invalidate affected Payload session(s)
          │
          ▼
       Browser
          │
          ▼
    CMS access denied /
       re-login

    

This is important because a Payload session may otherwise remain valid after the authoritative Core account state has changed.

The Core event therefore acts as a revocation signal for the CMS-local session layer.

For role changes, the CMS should evaluate the new authoritative role against its current access policy. If the administrator no longer has CMS access, active sessions must be terminated. If the administrator retains CMS access but receives different permissions, the local user projection and authorization state must be updated accordingly.

Event-Driven Security Boundary

The resulting architecture preserves Core's authority even after the introduction of Kafka.


 ┌─────────────────────────┐
 │           Core          │
 │                         │
 │ Identity Authority      │
 │ Authentication          │
 │ Administrator Roles     │
 │ Account Lifecycle       │
 └────────────┬────────────┘
              │
      bilgi.admin.event
              │
              ▼
         ┌─────────┐
         │  Kafka  │
         └────┬────┘
              │
              ▼
 ┌─────────────────────────┐
 │          CMS            │
 │                         │
 │ User Projection         │
 │ Payload Sessions        │
 │ Content                 │
 │ Media                   │
 │ CMS Domain Events       │
 └────────────┬────────────┘
              │
         CMS Outbox
              │
              ▼
         ┌─────────┐
         │  Kafka  │
         └────┬────┘
              │
       bilgi.audit.logs
              │
              ▼
       ┌────────────┐
       │  Realtime  │
       │            │
       │ Audit      │
       │ Persistence│
       └─────┬──────┘
             │
             ▼
           MongoDB

    

Kafka therefore acts as the asynchronous integration layer, while PostgreSQL remains the transactional source of truth for CMS-owned data and Core remains the authoritative source of administrator identity.

Content & Media Ownership

Content managed through the CMS remains owned by the CMS domain.

For example:


CMS
 ├── Posts
 ├── Media
 └── CMS Users

    

while business entities remain owned by Core:


Core
 ├── Users / Administrators
 ├── Ideas
 ├── Projects
 ├── Applications
 ├── Contracts
 ├── Invoices
 └── Support Tickets

    

The CMS can therefore manage presentation-oriented and editorial content without assuming ownership of core business entities.

Architectural Benefits

The CMS microservice provides:

  • Centralized content management
  • Independent CMS evolution
  • Clear data ownership
  • Separation of identity from content management
  • No duplicate administrator password store
  • Core-authoritative authentication and authorization
  • Local Payload session management
  • Independent CMS database
  • Controlled administrative access
  • Reusable content and media management
  • Clean integration with the existing microservice architecture
  • Future Kafka-based asynchronous integration
  • Reliable CMS event publication through the outbox pattern
  • Centralized audit-event delivery through bilgi.audit.logs
  • Event-driven synchronization of Core administrator state
  • Immediate CMS session invalidation following authoritative administrator changes

Most importantly, the architecture avoids turning Payload CMS into a second identity authority.

Core answers the question "Who is this administrator and what is this administrator allowed to do?"

CMS answers the question "What CMS content and administrative functionality can this authenticated administrator manage?"

Kafka answers the question "How do these independently owned services reliably react to changes occurring elsewhere in the platform?"

This separation preserves the platform's central identity model while allowing the CMS to remain a self-contained, independently deployable microservice and, when required, a fully integrated participant in TuranBilgi's event-driven architecture.

📡 Real-Time Communication, Notification & Audit Processing Microservice

A dedicated NestJS and Socket.IO–based microservice is responsible for managing all real-time communication, notification delivery, and centralized audit projections across the distributed platform, ensuring responsive client experiences and operational traceability. The service maintains persistent WebSocket connections and exposes REST and GraphQL APIs to support scalable, low-latency client interactions.

Rather than acting as a centralized event authority, this microservice operates as a specialized consumer and processor within a federated, domain-driven event architecture. Each domain service owns its own event production and outbox mechanisms, while this service focuses on real-time delivery, notification orchestration, and audit aggregation.

Core Responsibilities:

1. Real-Time Chat & Collaboration System

The microservice provides a full-featured, managed chat and collaboration subsystem supporting both private and room-based communication.

Administrative & Management APIs

Through REST and GraphQL interfaces, administrators can:

  • Create and manage chat rooms
  • Assign and manage room administrators
  • Add, remove, and manage room members
  • Moderate and manage room messages
  • Control access and visibility based on business rules

These management capabilities enable controlled, enterprise-grade collaboration environments.

Messaging Features

The chat subsystem supports:

  • Private one-to-one messaging
  • Room-based group messaging
  • Real-time typing indicators
  • Message delivery and read/seen acknowledgments
  • Private message deletion
  • Global (moderator-level) message deletion
  • Message lifecycle management

All messaging operations are synchronized across distributed gateways using Kafka and Redis to ensure consistency and fault tolerance.

2. Notification Management System

The platform implements a flexible, event-driven notification system supporting both manual and automated workflows. This microservice acts as the primary notification orchestration and delivery engine, consuming domain events emitted by distributed services and transforming them into user-facing notifications.

Notification Types
  • Channel Notifications
    Broadcast notifications delivered to system channels, teams, or workspaces
  • Private Notifications
    Direct, user-targeted notifications
Notification Creation Modes

A. Manual (Admin-Driven)
Administrators can:

  • Create draft notifications
  • Schedule publication
  • Publish immediately
  • Target specific channels or users

B. System-Generated (Event-Driven)
Distributed domain services emit notification-related events via their own MongoDB Outbox and Kafka publishing mechanisms for business events such as:

  • Invoice generation
  • Payment events
  • Support ticket updates
  • Workflow state transitions
  • System alerts

These events are published to Kafka by the originating services and consumed by the notification processors for delivery.

Notification Interaction Tracking

The notification subsystem supports:

  • Read and acknowledgment events for private notifications
  • Channel-level read tracking
  • Delivery status monitoring
  • Per-user notification state synchronization

This enables accurate notification lifecycle management and user engagement tracking.

3. Centralized Audit Log Aggregation via Event Streaming

This microservice serves as the centralized audit projection and compliance authority for the Turan Bilgi platform.

All domain microservices emit standardized audit events as part of their own transactional workflows using the MongoDB Outbox pattern. These events are reliably published to Kafka through service-local outbox processors, ensuring atomicity, durability, and failure isolation without cross-service coupling.

The Realtime microservice acts as the sole consumer and persistence owner of audit events. It consumes audit-related Kafka topics, validates and enriches incoming events, and persists them into an immutable, append-only audit log store.

Core responsibilities include:
  • Collection of internal audit events via MongoDB Outbox
  • Reliable publishing of internal audit events through Kafka outbox workers
  • Consumption of audit events from Kafka topics published by all domain microservices
  • Schema validation, normalization, and enrichment of audit records
  • Idempotent, ordered, and append-only persistence in MongoDB
  • Long-term retention, archiving, and replay support
  • Centralized audit visibility for regulatory, compliance, and forensic use cases

This design enforces clear ownership boundaries: domain services are responsible only for emitting audit intent, while audit persistence, retention, and compliance guarantees are centralized. The approach preserves domain autonomy, avoids distributed transactions, and enables scalable, fault-tolerant audit processing through event-driven architecture.

Distributed Scalability & Coordination:

To support multi-instance deployments and horizontal scaling:

  • Apache Kafka serves as the shared event streaming backbone for inter-service communication, enabling reliable, ordered, and replayable message delivery such as chat, notification, and audit workloads. Kafka enables multiple gateway instances to publish and consume chat and notification events reliably across the cluster.
  • Redis provides distributed coordination for:
    • WebSocket gateway synchronization
    • Room membership management
    • Duplicate event suppression
    • Shared session and state management
    • Caching of low-change system and actor data

This infrastructure enables independent scaling of producers and consumers while maintaining platform-wide consistency, or ensuring consistent behavior across clusters.

Architectural Benefits:

This microservice is designed to scale independently from core business and discourse microservices and provides:

  • Low-latency and governed real-time communication environments
  • Event-driven notification orchestration
  • Reliable private and multi-channel notification pipelines
  • Centralized, compliant audit projections
  • Loose coupling between domains
  • High system observability, traceability and compliance support
  • Independent deployment and horizontally scalable real-time infrastructure
  • Fault-tolerant event consumption pipelines

It functions as the platform’s real-time delivery and compliance projection layer, rather than as a centralized event authority.

🤖 AI Microservice (Intelligent Extension Layer)

To support advanced intelligence, automation, and knowledge-driven features, TuranBilgi includes an optional AI Microservice that extends the platform’s capabilities into natural language understanding, semantic search, content summarization, and assisted workflows.

The AI microservice is developed using Python and built on the FastAPI framework, enabling high-performance asynchronous processing and scalable API-driven intelligence services. This service operates as an independent extension layer within the microservice architecture, allowing AI capabilities to evolve separately from the core business services.

Purpose

The AI microservice is designed as a loosely coupled, language-agnostic intelligence layer that consumes business events (such as idea creation, discussion updates, and support ticket changes) and produces knowledge artifacts that enhance user experience and platform insight. It does not replace existing services but augments them with machine-assisted intelligence.

By isolating AI workloads into a dedicated Python-based service, TuranBilgi ensures:

  • Clear separation between business logic and computational intelligence
  • Independent scaling of AI-intensive operations
  • Flexibility to integrate machine learning models, vector databases, and NLP pipelines
  • Clean API-based communication with other microservices

This architecture enables TuranBilgi to progressively introduce intelligent features without compromising the stability or modularity of the core platform.

Key Responsibilities

The AI microservice provides:

  1. Semantic Embedding Generation — Creating vector representations of text content from discussions, tickets, and ideas for similarity search and retrieval.
  2. Content Summarization — Producing concise summaries of long discussion threads or support histories to improve readability and decision-making.
  3. Semantic Search & Matching — Enabling users and services to find related content using meaning-based search queries (not just keyword matching).
  4. RAG-style Assistant Responses — Combining retrieved content with language models to answer questions in context (e.g., “What are the main issues in idea X?”).
  5. Optional Moderation Support — Assisting with detection of content quality issues or policy violations. (Future expansion)

Architecture Integration

The AI microservice operates independently from the other microservices but integrates through the platform’s event infrastructure:

  • Consumes Domain Events (e.g., new idea created, discussion updated) for embedding and indexing.
  • Publishes AI-derived Events (e.g., summary available, related content recommendations).
  • Stores Embeddings & Metadata in a search-optimized store (such as PostgreSQL with vector indexing) separate from other services’ databases.
  • Exposes REST + gRPC Endpoints for other services or clients to request intelligent capabilities.

This separation maintains microservice boundaries, avoids direct coupling to the database store of other microservices, and enables independent scaling of AI workloads.

Benefits

Adding the AI microservice to the platform enables:

  • Faster insights over large amounts of text content
  • Smarter search and discovery of related ideas and discussion context
  • Enhanced user productivity through summarization and assisted content navigation
  • Foundation for future AI-driven workflows such as predictive recommendations and automated scoring

Future-Ready Approach

While the core platform handles transactional and collaboration workloads, the AI microservice is designed for extensibility into:

  • Hybrid retrieval-augmented generation (RAG)
  • Local model hosting and fine-tuning
  • Intelligent workflow orchestration (see TuranUlak Integration)
  • Graph-based reasoning over business entities

This aligns with TuranBilgi’s long-term extensibility goals while preserving clear service boundaries.

🔐 Security & Authentication

TuranBilgi adopts a shared JWT-based authentication model across all microservices to ensure consistent and secure identity propagation throughout the system.

The Core Business service acts as the primary identity authority, issuing signed JWT access tokens after successful authentication. Client applications include these tokens in subsequent requests to other microservices, which independently validate the token signature and claims without requiring centralized session storage.

This approach provides:

  • Stateless authentication across services
  • Clear separation between authentication (identity verification) and authorization (role- and claim-based access control)
  • Secure service-to-service communication using trusted token validation
  • Simplified identity propagation across distributed workflows

JWT expiration policies and claim validation mechanisms enforce time-bound access while preserving scalability and performance.

This model balances strong security guarantees with operational simplicity, avoiding the need for centralized session management or complex gateway-level token orchestration.

🧪 Testing Strategy & Quality Assurance

TuranBilgi follows a structured, multi-layered testing strategy designed to ensure reliability, security, and long-term scalability across its distributed microservice architecture.

Testing is implemented using modern, ecosystem-appropriate frameworks (such as Jest, Vitest, SuperTest, MSW, and language-native testing tools) depending on service requirements. This layered testing strategy supports safe refactoring, reduces regression risk, and ensures consistent behavior in a distributed environment.

Testing Layers

All services follow clearly defined validation layers to ensure correctness, resilience, and predictable system behavior. The testing strategy includes:

  • Unit Testing — validates isolated business logic, domain rules, and service-level functionality.
  • Integration Testing — verifies interactions between APIs, databases, caches, and message brokers.
  • End-to-End (E2E) Testing — validates complete user and system flows across REST, GraphQL, and real-time WebSocket interfaces.
  • API Contract Testing — ensures backward compatibility and stable inter-service communication.
  • External Dependency Mocking — isolates third-party integrations for deterministic testing.
  • Code Coverage Enforcement in CI — prevents untested code from entering production branches.

Backend Microservices (Node.js)

  • NestJS microservices are tested using Jest and SuperTest for unit and integration testing.
  • Express.js or Fastify microservices are tested using Vitest, enabling fast and modern TypeScript-based testing.
  • External services are mocked using MSW where required.

AI Microservice (FastAPI – Python)

The AI microservice is tested using:

  • Pytest
  • httpx for async endpoint testing
  • pytest-asyncio
  • coverage.py for coverage enforcement

Test Environment Architecture

Testing environments are fully isolated from production and are provisioned using containerized infrastructure. They include:

  • Environment-specific configuration files (e.g., .env.test)
  • Dockerized test databases (e.g., PostgreSQL, MongoDB, Redis)
  • Dockerized message brokers (RabbitMQ, Kafka)
  • Mocked or sandboxed external services
  • Containerized test execution within CI pipelines

Integration tests run against real, isolated service dependencies to accurately simulate production interactions without impacting live systems. Unit tests mock messaging clients, while integration tests validate real message flows against isolated broker instances. This ensures realistic validation of event-driven communication without impacting production systems. This approach ensures deterministic, reproducible results across local development and continuous integration (CI) environments.

CI Pipeline Strategy

Each microservice runs automated tests in the CI pipeline on:

  • Pull requests
  • Merge to main branches
  • Release candidates

Pipelines enforce:

  • Test execution
  • Coverage thresholds
  • Linting and static analysis
  • Build validation

No service can be deployed unless it passes all automated quality gates.

Security Validation

Security is integrated into the testing lifecycle through:

  • Dependency vulnerability scanning
  • Input validation and schema testing
  • Authentication and authorization flow testing
  • Rate-limiting and abuse-case testing
  • Secure configuration validation

This ensures resilience against common attack vectors and misconfigurations.

Why This Testing Strategy

This testing strategy was chosen to:

  • Maintain strict service isolation in a microservice architecture
  • Allow independent evolution of services
  • Support long-term scalability
  • Ensure production-grade reliability
  • Minimize regression risks during feature expansion

By aligning testing tools with each technology stack (NestJS, Express/Fastify, FastAPI), TuranBilgi achieves both architectural clarity and operational stability. This approach balances developer velocity with strict quality controls, enabling rapid innovation without compromising system stability.

🐳 Containerization, Deployment & Orchestration

The entire ecosystem is containerized under the TuranOrdo Infrastructure Platform. This includes the Core Business, Discourse, Real-Time, CMS, Payment, and AI microservices, PostgreSQL, MongoDB, Redis, Apache Kafka, RabbitMQ, reverse proxies (Nginx), and all the observability & monitoring tools. This setup enables fast, repeatable deployments on any Linux VPS while providing a strong foundation for future orchestration with Kubernetes or other container platforms, while remaining fully operational with Docker Compose or Docker Swarm.

Orchestration Strategy & Migration Path

TuranBilgi is intentionally designed with orchestration portability in mind. While the platform currently operates efficiently using Docker Compose or Docker Swarm, its container boundaries, stateless service design, externalized configuration, and volume management patterns ensure a smooth migration path to Kubernetes when scaling requirements justify it.

Phase 1 — Docker Compose (Current / Early Stage)

Ideal for:

  • Single-node or small multi-node deployments
  • Low-to-medium traffic environments
  • Cost-sensitive VPS infrastructure
  • Rapid development and controlled environments

Benefits:

  • Minimal operational overhead
  • Simpler networking model
  • Lower infrastructure complexity
  • Easier debugging and deployment workflows

At this stage, Kubernetes would add unnecessary operational weight.

Phase 2 — Docker Swarm (Optional Intermediate Stage)

Suitable when:

  • Running multiple nodes
  • Needing simple clustering
  • Basic rolling updates and service replication are required
  • Traffic begins to grow but remains predictable

Swarm provides:

  • Native service replication
  • Overlay networking
  • Basic load balancing
  • Rolling deployments

However, Swarm remains simpler than Kubernetes and is often sufficient for medium-scale production workloads.

Phase 3 — Kubernetes (When It Becomes Necessary)

Migration to Kubernetes becomes justified when TuranBilgi experiences one or more of the following:

  • Multi-node horizontal scaling across regions
  • Auto-scaling requirements (HPA based on CPU, memory, or custom metrics)
  • Complex rolling deployments or canary releases
  • Blue/green deployments at scale
  • Infrastructure spanning multiple data centers or cloud providers
  • Need for advanced workload scheduling policies
  • Team growth requiring stronger DevOps separation of concerns
  • Platform-level SLA commitments

Kubernetes introduces production-grade orchestration capabilities such as:

  • Horizontal Pod Autoscaling (HPA)
  • Self-healing workloads
  • Advanced rollout strategies
  • StatefulSets for databases and brokers
  • Native secret management
  • Network policies
  • Infrastructure abstraction
The migration can be executed incrementally:
  1. Ensure all services:

    • Are fully stateless (except databases/brokers)
    • Use environment-based configuration
    • Store state only in volumes or external systems
  2. Convert Docker Compose services into:

    • Kubernetes Deployments
    • Services (ClusterIP)
    • Ingress resources
    • ConfigMaps & Secrets
  3. Migrate infrastructure components:

    • PostgreSQL → StatefulSet
    • MongoDB → StatefulSet
    • Kafka/RabbitMQ → Operator-based deployment
  4. Introduce:

    • Horizontal Pod Autoscalers
    • Liveness and readiness probes
    • Resource limits and requests
  5. Gradually transition traffic from VPS deployment to Kubernetes cluster.

Because TuranBilgi already enforces clean container boundaries, this migration would be structural rather than architectural. Infrastructure evolution does not require service redesign, preserving long-term architectural stability.

Strategic Deployment Path for TuranBilgi

Current Stage:

  • Docker Compose or Swarm is fully sufficient.
  • No service mesh required.
  • Reverse proxy + TLS termination + strong JWT validation is enough.

Scaling Stage (Future):

  • Migrate to Kubernetes when horizontal scaling or advanced rollout strategies become necessary.
  • Introduce service mesh only if internal zero-trust networking or complex traffic management becomes mandatory.

TuranBilgi’s architecture is intentionally modular and container-native, ensuring that orchestration upgrades can occur without redesigning core services.

Architectural Philosophy

TuranBilgi prioritizes:

  • Operational clarity over complexity
  • Incremental scalability over premature optimization
  • Container portability over vendor lock-in
  • Observability-first design
  • Measured adoption of advanced infrastructure patterns

This approach ensures that infrastructure evolves in response to real operational needs rather than theoretical scalability assumptions.

💾 Backup & Disaster Recovery

Backup Strategy

To ensure data durability and disaster recovery, TuranBilgi implements automated backup pipelines for critical data stores:

  • Automated database backups are performed for PostgreSQL and MongoDB via scheduled backup containers, producing timestamped, compressed dumps.
  • Backups are pushed off the primary VPS to remote object storage (e.g., Backblaze B2 using rclone or similar tooling), ensuring safety in the event of server failure, data corruption, or infrastructure incidents. Backups are encrypted in transit and can be encrypted at rest to ensure confidentiality of sensitive data.
  • Retention policies and cleanup procedures manage local storage, while periodic restore testing procedures (e.g., test restores to temporary containers) validate the correctness and integrity of backup artifacts.

These mechanisms guarantee that production data remains protected, restorable, and resilient against operational faults or disasters.

📊 Observability

Observability & Monitoring tools

TuranBilgi adopts a comprehensive observability and monitoring strategy to provide deep visibility into system behavior, performance, and reliability across its distributed landscape. Observability goes beyond basic monitoring by correlating metrics, logs, and error events to enable rapid diagnosis and root cause analysis in complex deployments.
The observability platform includes:

  • Metrics Collection & Alerting:

    A containerized Prometheus stack collects metrics from services, databases, brokers, and runtime resources (CPU, memory, request latencies, consumer lag, queue depths, etc.). Alerts are configured for critical thresholds (e.g., error rates, slowdowns, resource saturation) to notify stakeholders automatically.

  • Dashboarding & Visualization:

    Grafana is used to visualize time-series metrics and create operational dashboards that display key indicators such as API performance, Kafka consumer health, RabbitMQ queue statistics, and WebSocket connection trends, turning raw telemetry into actionable insight.

  • Error Tracking:

    Sentry captures exceptions, stack traces, and contextual request metadata from all services, enabling quick identification of issues in production and correlating failures with release versions and service flows.

  • Distributed Tracing (Optional / Extensible):

    OpenTelemetry-based tracing can be integrated to visualize cross-service request flows and event-driven interactions, providing deeper insight into distributed transactions.

  • Log Aggregation (Optional / Extensible):

    For centralized log analysis and search, a logging stack (e.g., Loki with Promtail or a full ELK stack) ingests and indexes logs from all containers. Correlating logs with metrics and traces helps answer not only what is happening, but why it is happening — critical for distributed systems and complex workflows.

Together, these components provide a unified observability surface that enhances operational confidence, reduces time to resolution, and supports continuous performance optimization as the platform evolves.

🌐 Service Connectivity & Topology

API Gateway Strategy: Direct Microservice Access

TuranBilgi currently uses a direct client-to-microservice API topology. Frontend applications access the required microservices through their respective configured service URLs rather than through a dedicated centralized API gateway or unified API facade.

The client configuration identifies each service independently, including Core, Discourse, Realtime, and CMS. This allows each microservice to retain its own API contract and domain boundary, while shared frontend packages centralize service URL configuration and common API-client behavior.

The absence of a dedicated API gateway is an intentional architectural decision, not a prohibition against introducing one in the future.

Architectural Rationale

  • Service autonomy: Clients address the service responsible for the relevant domain operation.
  • Limited infrastructure complexity: The platform avoids introducing an additional gateway component before its benefits justify the operational overhead.
  • Transport flexibility: Clients can use REST or GraphQL independently for each supported service, without requiring a centralized GraphQL gateway.
  • Infrastructure portability: Application code should not depend on a particular reverse-proxy or API-gateway implementation.
  • Independent security enforcement: Each microservice remains responsible for enforcing its applicable authentication, authorization, and input-validation requirements.

Infrastructure-level ingress, reverse proxying, hostname routing, and TLS termination are separate concerns from introducing a centralized API gateway. An infrastructure proxy may provide these capabilities without becoming a unified application-facing API contract.

Conditions for Introducing an API Gateway

A centralized API gateway may be introduced when concrete requirements justify it, such as:

  • Centralized rate limiting, request policies, or API access controls across multiple services.
  • A requirement to expose a common API hostname or conceal internal service topology.
  • Centralized API-level analytics or policy enforcement that cannot be adequately provided by the existing infrastructure.
  • A need for common routing and lifecycle policies across a growing set of externally exposed services.
  • Operational or organizational requirements that justify the additional component.

Having multiple frontend applications or microservices alone does not automatically require a dedicated API gateway.

Gateway Migration and Vendor Independence

If a gateway is introduced or replaced in the future, gateway-specific routing and policy configuration should remain isolated from application and domain logic.

The platform should preserve stable service URLs and API contracts wherever practical. A gateway migration may require translating provider-specific configuration, middleware, routing rules, DNS settings, TLS configuration, and deployment definitions, but should not ordinarily require changes to business logic or frontend code when the externally visible interfaces remain compatible.

The goal is not to eliminate infrastructure migration work. It is to contain that work within the infrastructure layer and avoid unnecessary coupling to any particular gateway product.

A dedicated API gateway remains an optional architectural extension rather than a mandatory component of the TuranBilgi platform.

Service Mesh Considerations (Consul Connect / Istio)

Service meshes provide:

  • Mutual TLS (mTLS) between services
  • Fine-grained traffic routing
  • Circuit breaking
  • Distributed tracing injection
  • Service-to-service policy enforcement
  • Observability at network layer

However, they introduce:

  • Significant operational complexity
  • Additional resource consumption
  • Steeper debugging difficulty
  • Learning curve and maintenance overhead

When a Service Mesh Is NOT Necessary

For TuranBilgi, a service mesh is not required when:

  • Running in Docker Compose or Swarm
  • Deploying on a single-node or small cluster
  • Service-to-service communication remains simple
  • mTLS can be handled at the gateway or via internal TLS
  • Observability is already handled via Prometheus + Grafana + Sentry
  • Traffic policies are not highly complex

In early and mid-stage deployments, adding Istio or Consul Connect would be architectural overengineering.

When a Service Mesh Becomes Justified

For TuranBilgi, a service mesh may become beneficial if:

  • TuranBilgi scales to large multi-node Kubernetes clusters
  • Zero-trust internal networking becomes mandatory
  • Strong internal mTLS enforcement is required
  • Advanced traffic shaping (A/B testing, canary per-route) is required
  • Platform SLAs demand granular failure isolation
  • Multi-team ownership requires traffic-level governance

At that stage:

  • Istio offers powerful traffic control and ecosystem maturity.
  • Consul Connect provides lighter-weight service mesh capabilities with simpler operational footprint.

Strategic Deployment Path for TuranBilgi

Current Stage:

  • Docker Compose or Swarm is fully sufficient.
  • No service mesh required.
  • Reverse proxy + TLS termination + strong JWT validation is enough.

Scaling Stage (Future):

  • Migrate to Kubernetes when horizontal scaling or advanced rollout strategies become necessary.
  • Introduce service mesh only if internal zero-trust networking or complex traffic management becomes mandatory.

TuranBilgi’s architecture is intentionally modular and container-native, ensuring that orchestration upgrades can occur without redesigning core services.

TuranUlak Integration (Planned)

TuranUlak is a proposed AI agentic workflow platform for the Turan ecosystem. Its first domain pack targets software engineering, the service TuranBilgi delivers to clients. This integration is planned and optional. It is not implemented, it depends on the validation results described in the TuranUlak documentation, and TuranBilgi continues to operate fully without it.

Ownership Boundary

TuranBilgi remains the system of record for ideas, projects, contracts, invoices, and support tickets, and remains the identity authority. TuranUlak owns workflow execution, agent processing, and workflow artifacts. The two are independent systems (bilgi and ulak) under TuranOrdo, which keeps them isolated by default. Workflow-run status is held as an auxiliary projection by the AI microservice and does not change Core's data model.

Integration Architecture


 Core / Discourse
        │  internal domain events (Kafka)
        ▼
 AI Microservice (bilgi/ai)
        │  contract: bilgi-to-ulak
        │  authenticated HTTPS, event envelope
        ▼
 TuranUlak (ulak/integration-consumer)
        │  workflow execution, agents, verification
        ▼
 TuranUlak results
        │  contract: ulak-to-bilgi (callback)
        ▼
 AI Microservice (bilgi/ai)
        │  validation, AI-derived events
        ▼
 Core · Discourse · Realtime · Admin Panel

    

TuranUlak never accesses TuranBilgi's Kafka topics, databases, or identity infrastructure. Communication is authorized only through explicit integration contracts, as described in the TuranOrdo inter-system communication design.

Role of the AI Microservice

  • Intake adapter: maps internal Core and Discourse events to authorized integration events and prepares minimal, validated workflow requests.
  • Knowledge provider: supplies summarization, semantic search, and retrieval so agents receive relevant project context without direct access to TuranBilgi data stores.
  • Results bridge: receives callbacks, validates results, and publishes AI-derived events for Core, Discourse, Realtime, and the Admin Panel.

Integration Contracts (Proposed)

ContractDirectionAuthorized events or operations
bilgi-to-ulak bilgi/ai → ulak/integration-consumer project.specification.approved, support.ticket.created
ulak-to-bilgi ulak/integration-consumer → bilgi/ai Workflow status changes, approval requests, artifact-ready notifications (event names to be defined)

Payloads use TuranOrdo's versioned event envelope (event_id, event_type, event_version, source_system, correlation_id, occurred_at, data). The listed event names are illustrative. Core does not currently document a project.specification.approved event, so the AI microservice would derive it from Core's existing business events, such as an agreed contract and its locked project definition. Exact mappings remain owned by Core.

Mapping to Business Workflows

TuranBilgi workflowTuranUlak workflowResult in TuranBilgi
Project application requirements discussion (Discourse) Clarify: draft brief and acceptance criteria AI-labeled draft for administrator review
Contract agreed, project definitions locked Baseline, then architect, implement, verify, preview Progress, preview links, and approval requests in the Admin Panel
Support ticket created Triage, reproduce, propose fix Analysis shown to support administrators as an internal note
Invoice and payment Not applicable Payment microservice stays isolated from agents

Governance Controls

  • Per-project opt-in: AI-assisted workflows are disabled by default and enabled per project by an administrator, subject to client agreement.
  • Human approval: approvals are made by TuranBilgi administrators. Role mapping will be defined using the existing Core role model.
  • Attribution: AI-generated content is clearly labeled and attributed to a system actor, never to a human user.
  • Audit: requests, approvals, and results are published as audit events to bilgi.audit.logs and persisted by the Realtime microservice.
  • Data minimization: only information needed for a workflow crosses the boundary, preferably as references, and no payment, invoice, or credential data is shared.

Security and Identity

  • Core remains the identity authority. TuranUlak receives a service identity and an initiating-actor reference for audit, never user passwords or administrator tokens.
  • Each contract uses dedicated identities and narrowly scoped permissions, with internal TLS and, where enabled, mutual TLS.
  • Callbacks are authenticated and validated, and network reachability alone never authorizes communication.

Reliability and Failure Isolation

  • No TuranBilgi business workflow waits on TuranUlak. If it is unavailable, requests are retried and the platform continues normally.
  • Delivery is at-least-once. TuranUlak processes requests idempotently by event_id, and the AI microservice does the same for callbacks.
  • Retries use backoff with dead-letter handling, and correlation identifiers link every request, workflow run, and callback.

Testing

Following TuranBilgi's testing strategy, TuranUlak is treated as an external dependency. It is mocked in unit and integration tests, and both contracts are covered by API contract tests so that changes on either side do not break the other.

Adoption Phases

  1. Shadow mode: TuranUlak runs alongside human work and commits nothing. Results are visible to administrators only.
  2. Draft with approvals: TuranUlak produces drafts that administrators approve.
  3. Approve-to-commit: considered only after measured validation of the platform.
  4. Managed event integration: the HTTPS transport may be replaced by TuranOrdo's managed event integration once available, without changing the contracts.

🚀 Future Architectural Extensions

TuranBilgi is designed to evolve incrementally without requiring premature adoption of additional architectural patterns. Serverless execution and Micro-Frontend architecture are potential future extensions rather than mandatory components or committed milestones in the platform roadmap.

Their adoption will depend on demonstrated workload characteristics, development-team organization, operational requirements, and the benefits they provide relative to their additional complexity.

1. Serverless & Function-Based Workloads

Serverless execution may be considered for selected workloads that benefit from event-triggered execution, intermittent demand, or automatic scaling without requiring dedicated, continuously running application instances.

Potential use cases include:

  • Lightweight event handlers and asynchronous processing tasks.
  • Scheduled jobs and periodic maintenance operations.
  • Webhook adapters and selected external integration handlers.
  • Bursty workloads whose execution characteristics benefit from demand-driven resource allocation.
  • Selected AI inference workloads when model initialization, execution limits, resource requirements, latency, and cost make serverless execution appropriate.

Serverless execution does not necessarily mean abandoning containerization. Depending on deployment requirements, it may be implemented through a managed cloud platform or a self-hosted function execution environment.

Existing containerized microservices remain the default when they are better suited to persistent connections, predictable sustained workloads, specialized resource requirements, or long-running processing. Serverless adoption must also preserve reliable event delivery, idempotent processing, security, observability, and appropriate retry behavior.

The objective is to select the most appropriate execution model for each workload rather than replace the platform's container-based architecture wholesale.

2. Micro-Frontend Architecture

Micro-Frontends may be considered when independently developed and deployed portions of a web application need stronger release autonomy, separate technical ownership, or distinct development and delivery lifecycles.

Potential application areas include Chat, Notifications, and AI Assistant functionality within a larger client application, provided these areas develop sufficiently independent requirements and release cycles.

Micro-Frontends are not synonymous with having multiple client applications. TuranBilgi's Site, User, Admin, and Mobile applications are separate client applications; introducing Micro-Frontends would instead involve decomposing one of the web applications into independently managed frontend modules.

The existing modular frontend architecture, shared workspace packages, and monorepo-based development workflow remain the default approach. Micro-Frontends may be introduced when the benefits of independent development and deployment justify the additional integration, dependency-management, testing, user-interface consistency, and operational complexity.

Adoption Principles

Neither Serverless nor Micro-Frontend architecture is required solely because the platform or its feature set grows.

Each pattern will be evaluated against concrete requirements and introduced only when its benefits justify the resulting complexity. Where adopted, the implementation should preserve clear ownership boundaries, security, observability, and portability wherever practical.

This approach allows TuranBilgi to extend its architecture selectively while retaining a stable foundation based on domain-focused microservices, containerized deployment, and modular client applications.

💻 Client Applications

TuranBilgi is a multi-client platform, designed to serve different user experiences through a shared backend infrastructure.

The TuranBilgi frontend ecosystem consists of multiple client applications designed to provide a seamless user experience across web and mobile platforms. These applications interact with the TuranBilgi backend platform to deliver real-time, secure, and reliable services. The TuranBilgi frontend or client applications form a cohesive ecosystem that complements the backend platform. They provide secure, scalable, and maintainable access to services for different types of users—administrators, end-users, and the general public—across web and mobile devices.

Client applications include:

  • Admin Panel, to be built with Vite + React, for internal system management and operational workflows
  • End-user Web Application, to be built with Vite + React, providing interactive user experiences
  • End-user Mobile Application, to be built with React Native, enabling cross-platform mobile access
  • Public Website, to be built with Next.js (React), providing interactive and SEO-friendly user experiences to be focused on marketing and informational content

All client applications consume the same TuranBilgi APIs (REST, GraphQL, and WebSockets), ensuring:

  • Shared authentication and authorization
  • Consistent business logic
  • Unified real-time behavior across web, mobile, and desktop platforms

Marketing & Informational Website

  • Built with Next.js
  • Focused on SEO and delivering information about TuranBilgi services
  • Offers a public-facing interface that explains platform capabilities
  • Server-side rendering ensures fast loading times and search engine visibility

User Client Application

  • React-based web application for end-users
  • Handles user authentication, token management, and session control
  • Offers intuitive UI for user interactions with TuranBilgi services
  • Includes automated handling of secure API communications with the backend

Admin Dashboard

  • Built as a React web application
  • Provides internal administrative tools and reporting interfaces
  • Role-based access ensures only authorized users can access sensitive functions
  • Integrates securely with the backend services for management and monitoring

Mobile Application:

TuranBilgi Mobile App

  • Developed using React Native, targeting both iOS and Android platforms
  • Provides mobile-first access to TuranBilgi services
  • Features secure authentication and offline-friendly functionalities
  • Shares core logic with web applications when possible, ensuring consistency across platforms
  • Designed for scalability and easy updates through over-the-air deployment

Design Principles:

The frontend applications were developed with the following key principles:

  • Modularity – Each frontend application (web and mobile) is developed as a self-contained module, enabling independent updates, testing, and deployment.
  • Scalability – The architecture supports adding new features and client applications without major refactoring.
  • Maintainability – Clear project structure, consistent coding standards, shared components, and centralized configuration and type definitions across apps reduce duplication and improve long-term maintainability.
  • Security – Secure handling and transmission of authentication tokens to the backend, enabling the platform to recognize user types, roles, and permissions.
  • Performance – Optimized rendering, lazy loading, and efficient API usage ensure fast, responsive experiences on web and mobile.
  • Cross-platform consistency – Shared design patterns and UI components maintain a consistent user experience across the website, React Native mobile app, and any other client applications.
  • Reliability – Centralized error handling and graceful fallback mechanisms ensure stable operation under varying network conditions.
  • User Experience – Responsive, intuitive interfaces for both desktop and mobile users
  • Extensibility – APIs and services are designed to be easily consumed by new client apps, including web, mobile, and potential future platforms.

Technology Stack:

  • Web: React, Next.js, Vite, TypeScript
  • Mobile: React Native, Expo / Native modules, TypeScript
  • State & Data Management: Shared services and API clients for consistent backend communication
  • Build & Deployment: Monorepo structure with TurboRepo and pnpm workspaces for dependency management and builds

📈 Commercialization & Ecosystem Development

TuranBilgi is part of a broader technology ecosystem under development, alongside TuranOrdo, TuranTulpar, TuranUlak, TuranPazar, TuranOkul, and potential future Turan products. These names represent product and technology brands rather than separate legal entities.

Ecosystem Development Strategy

TuranBilgi serves as a business application platform within this ecosystem, while also providing a practical environment for validating the infrastructure, distributed-system patterns, and operational capabilities developed through TuranOrdo and related technologies.

The long-term objective is to develop reliable, reusable technology products that can support both the Turan ecosystem's own applications and the needs of external organizations.

Commercial development may encompass software licensing, infrastructure products, business applications, integrations, and other services as individual products mature and market opportunities are validated.

Future Investment and Financing

As the technology ecosystem matures, future development may be supported through external financing at the operating-company level rather than through separate investment arrangements for individual product brands.

The intended approach is to establish an appropriate corporate and intellectual-property structure before pursuing formal investment opportunities. Financing arrangements, company structure, and capital allocation would depend on product maturity, commercial validation, jurisdiction, and applicable legal requirements.

The potential investment model, funding stages, financing approaches, and intended use of capital are described in the TuranOrdo infrastructure documentation. This broader strategy concerns the Turan technology ecosystem and does not constitute a separate investment offering for TuranBilgi.

Development Principles

The commercialization strategy follows three principles:

  • Technical validation before expansion: Continue developing and validating products through real-world use before committing to significant expansion.
  • Portfolio-level investment: Allocate future funding according to the needs and commercial potential of the broader technology portfolio.
  • Sustainable product development: Prioritize reliability, maintainability, customer value, and commercially viable products over growth for its own sake.

Important Notice

This section describes a potential future commercialization and financing strategy. No investment is being solicited through this documentation, and no future financing arrangement should be considered established or committed.

Any future investment opportunity would be subject to an appropriate legal and corporate structure, applicable laws and regulations, and the relevant transaction documentation. Potential investors should conduct independent due diligence and obtain qualified professional advice.