> ## Documentation Index
> Fetch the complete documentation index at: https://docs.privetag.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Architecture

> Technical architecture of the PriveTag B2A Platform

# Architecture

Understanding the technical architecture of PriveTag B2A Platform.

## System Overview

```mermaid theme={null}
graph TB
    subgraph "AI Agents"
        ChatGPT[ChatGPT]
        Claude[Claude]
        LangChain[LangChain Apps]
        Custom[Custom Agents]
    end

    subgraph "PriveTag B2A Platform"
        subgraph "API Gateway"
            APIGW[API Gateway]
            Auth[Auth & Rate Limiting]
        end

        subgraph "Core Services"
            Recommend[Recommendation Engine]
            Booking[Booking Service]
            Inventory[Inventory Hub]
        end

        subgraph "Data Layer"
            Context[Context Pipeline]
            GT[Ground Truth Engine]
            Cache[Redis Cache]
        end

        subgraph "Storage"
            PG[(PostgreSQL)]
            S3[(Object Storage)]
        end
    end

    subgraph "External"
        Weather[Weather API]
        Venues[Venue Partners]
        ExtAPI[Activity APIs]
    end

    ChatGPT --> APIGW
    Claude --> APIGW
    LangChain --> APIGW
    Custom --> APIGW

    APIGW --> Auth
    Auth --> Recommend
    Auth --> Booking
    Auth --> Inventory

    Recommend --> Context
    Recommend --> GT
    Recommend --> Cache

    Booking --> Inventory
    Booking --> PG

    Context --> Weather
    Inventory --> Venues
    Inventory --> ExtAPI

    GT --> PG
    Context --> PG
    Booking --> S3
```

## Component Details

### API Gateway

The entry point for all AI agent requests:

| Feature         | Technology | Description                          |
| --------------- | ---------- | ------------------------------------ |
| Load Balancing  | AWS ALB    | Distributes traffic across instances |
| SSL Termination | CloudFront | Handles HTTPS                        |
| Rate Limiting   | Redis      | Per-key rate limiting                |
| Authentication  | Custom     | API key validation                   |

### Recommendation Engine

Processes recommendation requests:

```mermaid theme={null}
graph LR
    A[Request] --> B[Validate]
    B --> C[Enrich Context]
    C --> D[Query Ground Truth]
    D --> E[Score Activities]
    E --> F[Rank & Filter]
    F --> G[Response]
```

**Key Technologies:**

* **Language**: TypeScript (Node.js)
* **ML Model**: Custom scoring algorithm
* **Cache**: Redis for hot data

### Booking Service

Handles booking creation and voucher delivery:

| Step        | Description         | SLA      |
| ----------- | ------------------- | -------- |
| Validation  | Check availability  | \< 100ms |
| Reservation | Lock inventory      | \< 200ms |
| Payment     | Process if required | \< 2s    |
| Voucher     | Generate QR + PDF   | \< 500ms |
| Email       | Send to user        | \< 30s   |

### Inventory Hub

Aggregates availability from multiple sources:

```mermaid theme={null}
graph TD
    IH[Inventory Hub]

    subgraph "Priority 1"
        CV[Commission Venues]
    end

    subgraph "Priority 2"
        K[Klook API]
    end

    subgraph "Priority 3"
        V[Viator API]
    end

    subgraph "Priority 4"
        GYG[GetYourGuide API]
        KK[KKday API]
    end

    CV --> IH
    K --> IH
    V --> IH
    GYG --> IH
    KK --> IH
```

**Inventory Priority:**

1. Direct venue partnerships (highest margin)
2. Klook (good coverage, fast API)
3. Viator (extensive catalog)
4. GetYourGuide / KKday (backup)

### Ground Truth Engine

Processes and stores verified visit data:

```sql theme={null}
-- Ground Truth Schema
CREATE TABLE ground_truth (
    id UUID PRIMARY KEY,
    booking_id UUID REFERENCES bookings(id),
    context_log_id UUID REFERENCES context_logs(id),
    activity_id UUID REFERENCES activities(id),
    verified_at TIMESTAMP NOT NULL,
    verification_method VARCHAR(20),
    user_profile JSONB,
    created_at TIMESTAMP DEFAULT NOW()
);

-- Index for efficient lookups
CREATE INDEX idx_gt_profile ON ground_truth
    USING GIN (user_profile);
```

## Data Flow

### Recommendation Flow

```mermaid theme={null}
sequenceDiagram
    participant Agent as AI Agent
    participant GW as API Gateway
    participant RE as Recommend Engine
    participant CP as Context Pipeline
    participant GT as Ground Truth
    participant Cache as Redis

    Agent->>GW: POST /recommend
    GW->>GW: Validate API Key
    GW->>RE: Forward Request

    RE->>Cache: Check context cache
    alt Cache Hit
        Cache-->>RE: Cached context
    else Cache Miss
        RE->>CP: Enrich context
        CP-->>RE: Enriched data
        RE->>Cache: Store context
    end

    RE->>GT: Query similar profiles
    GT-->>RE: Historical visit data

    RE->>RE: Score & Rank activities
    RE-->>GW: Recommendations + log_id
    GW-->>Agent: Response
```

### Booking Flow

```mermaid theme={null}
sequenceDiagram
    participant Agent as AI Agent
    participant GW as API Gateway
    participant BS as Booking Service
    participant IH as Inventory Hub
    participant Email as Email Service
    participant User as User

    Agent->>GW: POST /execute_booking
    GW->>BS: Create booking

    BS->>IH: Check & Reserve inventory
    alt Available
        IH-->>BS: Reserved
        BS->>BS: Generate voucher
        BS->>Email: Send voucher
        Email->>User: Voucher email
        BS-->>GW: Success + booking_id
    else Unavailable
        IH-->>BS: Not available
        BS-->>GW: Error: INVENTORY_EXHAUSTED
    end

    GW-->>Agent: Response
```

## Database Schema

### Core Tables

```mermaid theme={null}
erDiagram
    API_KEYS ||--o{ CONTEXT_LOGS : creates
    CONTEXT_LOGS ||--o{ BOOKINGS : leads_to
    BOOKINGS ||--o| GROUND_TRUTH : verifies
    ACTIVITIES ||--o{ BOOKINGS : booked_in

    API_KEYS {
        uuid id PK
        string api_key_hash
        string client_name
        string[] endpoints
        int daily_quota
        timestamp created_at
    }

    CONTEXT_LOGS {
        uuid id PK
        uuid api_key_id FK
        jsonb user_profile
        jsonb location
        jsonb enriched_context
        uuid[] recommended_activities
        timestamp created_at
    }

    BOOKINGS {
        uuid id PK
        uuid context_log_id FK
        uuid activity_id FK
        string user_email
        date booking_date
        int num_guests
        decimal total_price
        string status
        timestamp created_at
    }

    ACTIVITIES {
        uuid id PK
        string title
        string category
        string city
        decimal price
        string currency
        boolean is_active
    }

    GROUND_TRUTH {
        uuid id PK
        uuid booking_id FK
        uuid context_log_id FK
        timestamp verified_at
        string verification_method
        jsonb user_profile
    }
```

## Caching Strategy

### Cache Layers

| Layer             | TTL      | Data                |
| ----------------- | -------- | ------------------- |
| L1: Request       | 1 min    | API responses       |
| L2: Context       | 15 min   | Weather, enrichment |
| L3: GT Aggregates | 1 hour   | Ground truth scores |
| L4: Static        | 24 hours | Activity metadata   |

### Cache Keys

```
# Context cache
context:{city}:{weather_hash} → enriched context

# Ground Truth aggregates
gt:{travel_type}:{city}:{category} → activity scores

# Inventory
inventory:{activity_id}:{date} → availability
```

## Scalability

### Horizontal Scaling

```mermaid theme={null}
graph TB
    LB[Load Balancer]

    subgraph "API Servers (Auto-scaling)"
        API1[API Server 1]
        API2[API Server 2]
        API3[API Server N]
    end

    subgraph "Workers (Auto-scaling)"
        W1[Worker 1]
        W2[Worker 2]
        W3[Worker N]
    end

    subgraph "Shared Resources"
        Redis[(Redis Cluster)]
        PG[(PostgreSQL)]
        SQS[Job Queue]
    end

    LB --> API1
    LB --> API2
    LB --> API3

    API1 --> Redis
    API2 --> Redis
    API3 --> Redis

    API1 --> SQS
    SQS --> W1
    SQS --> W2
    SQS --> W3

    W1 --> PG
    W2 --> PG
    W3 --> PG
```

### Performance Targets

| Metric               | Target   | Current |
| -------------------- | -------- | ------- |
| API Latency (p50)    | \< 100ms | 85ms    |
| API Latency (p99)    | \< 500ms | 350ms   |
| Booking Success Rate | > 99%    | 99.2%   |
| Uptime               | 99.9%    | 99.95%  |
| Ground Truth Rate    | > 80%    | 85%     |

## Security

### API Security

* **Authentication**: API key in `x-api-key` header
* **Rate Limiting**: Per-key limits
* **IP Allowlisting**: Optional for enterprise
* **Encryption**: TLS 1.3 for all connections

### Data Security

* **At Rest**: AES-256 encryption
* **In Transit**: TLS 1.3
* **PII Handling**: Anonymization for ML
* **Retention**: Configurable per client

## Monitoring

### Key Metrics

```mermaid theme={null}
graph LR
    subgraph "Application"
        A1[Request Rate]
        A2[Error Rate]
        A3[Latency]
    end

    subgraph "Business"
        B1[Bookings/hour]
        B2[Verification Rate]
        B3[Revenue]
    end

    subgraph "Infrastructure"
        I1[CPU/Memory]
        I2[Database Connections]
        I3[Cache Hit Rate]
    end
```

### Alerting

| Alert            | Threshold | Action       |
| ---------------- | --------- | ------------ |
| Error Rate       | > 1%      | Page on-call |
| Latency p99      | > 1s      | Investigate  |
| Booking Failures | > 5/min   | Escalate     |
| Database CPU     | > 80%     | Scale up     |

## Next Steps

<CardGroup cols={2}>
  <Card title="Quickstart" icon="rocket" href="/introduction/quickstart">
    Get started with the API
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference/b2a/overview">
    Explore endpoints
  </Card>
</CardGroup>
