# SyntricDB as a Sidecar: Zero-Risk Incremental Adoption

Switching your primary production database is high-risk. Engineers rightly hesitate to rip out an existing PostgreSQL or MySQL database that serves core application logic.

The **SyntricDB Sidecar Pattern** provides a **zero-risk, non-invasive integration path**. You keep your existing primary database untouched for core transactional SQL, while deploying SyntricDB as a dedicated **AI Vector Index, Full-Text Search, and Sub-Millisecond Cache Sidecar** right alongside it.

---

## 1. Architecture Overview

```
                         ┌─────────────────────────────┐
                         │   Application Service       │
                         │   (Spring Boot / Node / Python) │
                         └──────────────┬──────────────┘
                                        │
                    ┌───────────────────┴───────────────────┐
                    │ Reads & Writes                        │ Vector Queries & Cache Reads
                    ▼                                       ▼
    ┌───────────────────────────────┐       ┌───────────────────────────────┐
    │ Primary Transactional Database│       │ SyntricDB Sidecar Instance    │
    │ (PostgreSQL / MySQL)          │       │ (HNSW Vectors + RESP Cache)   │
    │ *Handles Core User / Orders*  │       │ *Sub-millisecond Search*      │
    └───────────────┬───────────────┘       └───────────────────────────────┘
                    │
                    │ CDC / Asynchronous Sync (Optional)
                    └───────────────────────────────────────►
```

### Key Advantages of the Sidecar Pattern
1. **Zero Downtime & Zero Risk**: Your primary database remains the single source of truth for ACID business entities. If the sidecar is stopped or restarted, core user operations continue uninterrupted.
2. **Instant Performance Spike**: HNSW SIMD vector searches and key-value cache lookups run at sub-millisecond speeds (<1ms) offloaded entirely from your primary DB CPU/RAM.
3. **No Code Re-architecture**: Your existing ORM and migration scripts (Prisma, Hibernate, SQLAlchemy) remain unmodified.

---

## 2. Typical Sidecar Use Cases

### Use Case A: Offloading AI Vector Search & RAG
* **Primary DB**: Stores user profiles, billing, and document metadata.
* **SyntricDB Sidecar**: Indexes high-dimensional vector embeddings (e.g., 1536-dim OpenAI or 768-dim BGE embeddings) with SQ8 quantization for sub-millisecond similarity retrieval.

### Use Case B: Ultra-Fast Cache & Session Accelerator
* **Primary DB**: Handles transactional SQL queries.
* **SyntricDB Sidecar**: Accepts Redis-compatible `RESP` commands (`GET`, `SET`, `HGETALL`) over port `6379`, providing instant sub-millisecond memory caching for API responses.

---

## 3. Step-by-Step Implementation Guide

### Step 1: Deploy SyntricDB via Docker / Process
Launch SyntricDB as a lightweight container alongside your application:

```bash
docker run -d \
  --name syntricdb-sidecar \
  -p 5432:5432 \
  -p 6379:6379 \
  -v syntric_data:/var/lib/syntricdb/data \
  syntricdb/engine:latest
```

### Step 2: Code Integration (Python Example)

```python
import psycopg2
import redis
import numpy as np

# Primary Database Connection (Untouched Core DB)
primary_db = psycopg2.connect("postgresql://user:pass@primary-db:5432/production")

# SyntricDB Sidecar Connections (Native Protocol Compatibility)
syntric_vector = psycopg2.connect("postgresql://syntric:pass@syntric-sidecar:5432/vectors")
syntric_cache  = redis.Redis(host='syntric-sidecar', port=6379, db=0)

def search_documents(query_text: str, user_id: str):
    # 1. Check SyntricDB Sub-millisecond RESP Cache
    cache_key = f"search:{user_id}:{hash(query_text)}"
    cached_result = syntric_cache.get(cache_key)
    if cached_result:
        return cached_result.decode('utf-8')

    # 2. Convert text to vector embedding
    query_vector = generate_embedding(query_text) # e.g. [0.012, -0.441, ...]

    # 3. Perform Sub-millisecond HNSW SIMD Vector Search in SyntricDB Sidecar
    with syntric_vector.cursor() as cur:
        cur.execute("""
            SELECT id, title, score 
            FROM document_vectors 
            ORDER BY embedding <-> %s::vector 
            LIMIT 5;
        """, (query_vector,))
        results = cur.fetchall()

    # 4. Cache response in SyntricDB RESP Cache for 10 minutes
    syntric_cache.setex(cache_key, 600, str(results))
    return results
```

---

## 4. Asynchronous Data Sync Patterns

To keep the SyntricDB Sidecar populated with vector embeddings from your primary PostgreSQL database, select one of two seamless synchronization strategies:

### Option 1: Dual-Write Application Logic
When inserting a new document into PostgreSQL, asynchronously queue a background worker (e.g., Celery, BullMQ, Spring `@Async`) to generate embeddings and insert into SyntricDB.

### Option 2: Change Data Capture (CDC) Pipeline
SyntricDB natively supports PostgreSQL Logical Replication decoding. Point SyntricDB's CDC connector at your primary Postgres database WAL to automatically sync new records into HNSW vector indexes without writing custom sync code.

---

## 5. Summary & Migration Ladder

```
[Phase 1: Sidecar Cache] ──────► [Phase 2: Vector Indexing] ──────► [Phase 3: Unified Single Engine]
 (Offload Redis cache)            (Offload Pinecone / Search)         (Consolidate & Save 90% Costs)
```

By starting with the **Sidecar Pattern**, your team validates SyntricDB's speed, stability, and zero-downtime reliability in production with zero risk to your primary relational data.
