Skip to content
Santekno.com | Level Up Your Engineering Skills
EN
📖 0%
01 Dec 2026 · 21 min read ·Article 100 / 208
Go

Golang LLM Integration: Santekno Shop Bridge to AI Features

A bridge article from Santekno Shop to Topic 6 AI Features. pgvector is ready, architecture hooks are available, API design for AI features, and a preview of semantic search + chatbot integration.

IH
Ihsan Arif
Writer at Santekno · Backend Engineer

Santekno Shop is now production-ready. But we didn’t just build a store — we built a platform that’s AI-ready from day one. This closing article of Part 4 is a bridge: a recap of what’s been built, why everything was designed to be AI-friendly, and a concrete preview of the golang LLM integration we’ll build in Topic 6.

The key to AI integration here is the additive approach: adding without rebuilding. The embedding column already exists, the LLMClient interface just needs an implementation, and Clean Architecture ensures the Topic 5 code doesn’t need to be touched.


20.01 Santekno Shop: Complete Recap

Before stepping into AI, let’s map out everything built in Topic 5. The summary below groups it into four parts, from planning to the production baseline.

text
 1TOPIC 5 - EVERYTHING THAT'S BEEN BUILT:
 2
 3PART 1 - PLANNING & SPEC:
 4  [x] Event storming + 5 bounded contexts
 5  [x] 7 spec features, 29 Acceptance Criteria
 6  [x] ADRs: int64 cents, nil/nil not-found, optimistic locking, outbox
 7  [x] Modular monolith + Clean Architecture
 8  [x] DB schema + PostgreSQL extensions (uuid, pg_trgm, unaccent, vector)
 9  [x] OpenAPI 3.0 spec + Prism mock server
10  [x] CLAUDE.md + initial CI pipeline
11
12PART 2 - CORE SERVICES:
13  [x] Skeleton: domain entities, repo interfaces, usecase stubs
14  [x] User Service: bcrypt 12, JWT HS256, Redis rate limiting
15  [x] Product Service: tsvector full-text search, optimistic stock lock
16  [x] Order Service: atomic PlaceOrder + CancelOrder + outbox pattern
17  [x] Payment Service: HMAC webhook + idempotency + atomic flows
18  [x] Notification Service: Kafka consumer + email template + DLQ
19
20PART 3 - INFRASTRUCTURE:
21  [x] Database: 20+ indexes, auto-update triggers, pg_stat_statements
22  [x] Kafka: idempotent producer, outbox worker, consumer group
23  [x] Redis: cache-aside, singleflight stampede prevention, circuit breaker
24  [x] API Gateway: middleware stack, rate limiting, security headers
25  [x] Docker: ~21MB scratch image + K8s + HPA + zero-downtime rolling
26
27PART 4 - PRODUCTION BASELINE:
28  [x] Testing: unit (150+), integration (50+), E2E (20)
29  [x] CI/CD: 5-stage pipeline + AI code review + specify audit gate
30  [x] Observability: Prometheus + Grafana + OpenTelemetry + Zap
31  [x] Performance: k6 baseline, pprof profiling, benchmarks
32  [x] Bridge: AI-ready architecture (this article)

The key point: each part builds a foundation that makes AI integration an addition, not a teardown — that’s exactly what we’ll prove in the next section.


20.02 AI-Readiness Checklist

The “AI-ready” claim must be proven, not merely sloganized. The checklist below verifies readiness across five areas: database, architecture, API, observability, and performance baseline.

text
 1SANTEKNO SHOP AI READINESS:
 2
 3DATABASE:
 4  [x] pgvector extension installed
 5  [x] embedding VECTOR(1536) column on the products table (empty, ready to fill)
 6  [x] Schema supports: metadata enrichment, category taxonomy
 7  [x] IVFFlat index schema already commented out (just CREATE it)
 8
 9ARCHITECTURE:
10  [x] Clean Architecture: domain layer has ZERO external imports
11  [x] Repository interfaces: easy to add an AI-powered implementation
12  [x] Event system: AI can publish events like any other service
13  [x] Outbox pattern: even AI actions can be in an atomic transaction
14
15API:
16  [x] OpenAPI spec: easy to add new AI endpoints
17  [x] JWT middleware: AI features can be protected with the same token
18  [x] Rate limiting: can be per-endpoint for AI endpoints (more expensive)
19
20OBSERVABILITY:
21  [x] Structured logging: AI calls are easy to trace
22  [x] Prometheus metrics: easy to add LLM latency, token usage metrics
23  [x] OpenTelemetry: distributed trace from HTTP -> LLM -> pgvector
24
25PERFORMANCE BASELINE:
26  [x] Non-AI baseline established: can measure AI overhead clearly
27  [x] k6 tests: can extend to include AI endpoints

Every checkmark above is a “hook” already in place — so adding AI in Topic 6 doesn’t require a big migration, only filling in what’s already prepared.


The foundation of semantic search is the embedding column that already exists but is still empty. The preview code below shows how Topic 6 fills that column and runs a similarity search with cosine distance.

go
 1// Currently in the products table:
 2// embedding VECTOR(1536)  <- column exists, but empty
 3
 4// Topic 6 Article 5 will add:
 5// - A pipeline to generate embeddings from product name + description
 6// - Batch embedding update for existing products
 7// - Real-time embedding update when a product is updated
 8
 9// Preview of Topic 6 code:
10func (r *ProductRepository) UpdateEmbedding(ctx context.Context, productID string, embedding []float32) error {
11    _, err := r.db.Exec(ctx,
12        `UPDATE products SET embedding = $1::vector WHERE id = $2`,
13        pgvector.NewVector(embedding), productID,
14    )
15    return err
16}
17
18// Semantic search query:
19func (r *ProductRepository) SemanticSearch(ctx context.Context, queryEmbedding []float32, limit int) ([]*Product, error) {
20    rows, err := r.db.Query(ctx,
21        `SELECT id, name, price_idr, stock
22         FROM products
23         WHERE is_active = true
24           AND embedding IS NOT NULL
25         ORDER BY embedding <=> $1::vector  -- cosine distance
26         LIMIT $2`,
27        pgvector.NewVector(queryEmbedding), limit,
28    )
29    // ... scan rows
30}
31
32// Hybrid search (semantic + keyword):
33// ORDER BY (embedding <=> $1::vector) * 0.7 +
34//          (1 - ts_rank(search_vector, plainto_tsquery($2))) * 0.3

Because the column has existed from the start, migration cost is zero — Topic 6 only needs to fill in values and add an index, without changing the schema already running in production.


20.04 New Endpoints in Topic 6

New AI features need new endpoints, and our OpenAPI spec is easy to extend. The spec fragment below defines three endpoints: semantic search, chat support, and recommendations.

yaml
 1# OpenAPI spec extensions for Topic 6
 2
 3paths:
 4  /api/v1/products/search/semantic:
 5    post:
 6      summary: Semantic product search
 7      description: |
 8        Search products using a natural language query.
 9        The query is converted to an embedding, then a similarity search runs in pgvector.
10      requestBody:
11        content:
12          application/json:
13            schema:
14              type: object
15              properties:
16                query:
17                  type: string
18                  example: "comfortable shoes for a morning run"
19                limit:
20                  type: integer
21                  default: 10
22      responses:
23        '200':
24          description: Semantically relevant products
25
26  /api/v1/chat/support:
27    post:
28      summary: AI customer support chat
29      description: |
30        Chat with an AI assistant for FAQ, product questions, order status.
31        Backed by RAG with the product catalog + FAQ documents.
32      requestBody:
33        content:
34          application/json:
35            schema:
36              type: object
37              properties:
38                message:
39                  type: string
40                session_id:
41                  type: string
42      responses:
43        '200':
44          description: AI response (streaming via SSE)
45
46  /api/v1/recommendations:
47    get:
48      summary: AI product recommendations
49      description: Personalized recommendations based on order history + embeddings
50      security:
51        - bearerAuth: []

These three endpoints are additive to the existing spec — consistent with the SDD principle where API design always precedes implementation.


20.05 AI Feature Interface Design

Per the SDD principle, we define the interface before the implementation. The declarations below establish the Embedder, LLMClient, and ProductRecommender contracts in the domain layer.

go
 1// Before Topic 6 implements the AI features,
 2// we define their interfaces first (per the SDD principle)
 3
 4// internal/domain/ai/embedder.go
 5package ai
 6
 7import "context"
 8
 9//go:generate mockgen -destination=../../../testutil/mock/embedder_mock.go -package=mock -source=embedder.go
10
11// Embedder: convert text to an embedding vector
12type Embedder interface {
13    EmbedText(ctx context.Context, text string) ([]float32, error)
14    EmbedBatch(ctx context.Context, texts []string) ([][]float32, error)
15}
16
17// internal/domain/ai/llm.go
18type ChatMessage struct {
19    Role    string // "user" | "assistant" | "system"
20    Content string
21}
22
23type LLMClient interface {
24    Chat(ctx context.Context, messages []ChatMessage) (string, error)
25    ChatStream(ctx context.Context, messages []ChatMessage) (<-chan string, error)
26}
27
28// internal/domain/ai/product_recommender.go
29type Recommendation struct {
30    Product   *product.Product
31    Score     float32
32    Reason    string
33}
34
35type ProductRecommender interface {
36    Recommend(ctx context.Context, userID string, limit int) ([]Recommendation, error)
37}

Because the interface sits in the domain layer that’s free of external dependencies, use cases can use it without caring about the provider behind it — this is what makes AI easy to mock and test.


20.06 Provider-Agnostic LLM Interface

An interface alone isn’t enough; we need an implementation that can be swapped between providers. The OpenAIClient example below implements LLMClient, and the container wiring selects the provider based on configuration.

go
 1// internal/infrastructure/llm/openai/client.go (Topic 6)
 2
 3type OpenAIClient struct {
 4    client *openai.Client
 5    model  string
 6}
 7
 8func (c *OpenAIClient) Chat(ctx context.Context, messages []ai.ChatMessage) (string, error) {
 9    // Convert from domain types to OpenAI types
10    oaiMessages := make([]openai.ChatCompletionMessage, len(messages))
11    for i, m := range messages {
12        oaiMessages[i] = openai.ChatCompletionMessage{
13            Role: m.Role, Content: m.Content,
14        }
15    }
16
17    resp, err := c.client.CreateChatCompletion(ctx, openai.ChatCompletionRequest{
18        Model:    c.model,
19        Messages: oaiMessages,
20    })
21    if err != nil {
22        return "", fmt.Errorf("openai.Chat: %w", err)
23    }
24
25    return resp.Choices[0].Message.Content, nil
26}
27
28// internal/infrastructure/llm/anthropic/client.go (Topic 6)
29type AnthropicClient struct { /* ... */ }
30func (c *AnthropicClient) Chat( /* ... */ ) (string, error) { /* ... */ }
31
32// Container wiring: inject based on config
33// cfg.LLM.Provider = "openai" -> openai.NewClient(cfg.OpenAI.APIKey)
34// cfg.LLM.Provider = "anthropic" -> anthropic.NewClient(cfg.Anthropic.APIKey)

With this pattern, switching providers is just a matter of changing config — the use case that calls LLMClient doesn’t change a single line, and we’re free of vendor lock-in.


20.07 Customer Support Chatbot Architecture

The chat support feature uses the RAG pattern that combines retrieval and generation. The flow diagram below traces a single user question from handler to streaming response, while also marking the Topic 5 code being reused.

text
 1TOPIC 6 - AI Customer Support (RAG Pattern):
 2
 3User: "Where is my order #12345?"
 4
 5Flow:
 6  1. ChatHandler receives the message
 7  2. RAGUseCase:
 8     a. Embed query -> vector
 9     b. Similarity search on FAQ docs -> top 3 chunks
10     c. Get order status from OrderRepository
11     d. Build context: [system prompt] + [FAQ chunks] + [order info] + [user message]
12  3. LLMClient.Chat(ctx, messages)
13  4. Stream response via SSE to the client
14
15Architecture:
16  ChatHandler -> ChatUseCase -> [LLMClient, FAQRepository, OrderRepository]
17  FAQRepository -> pgvector (semantic search over FAQ documents)
18  LLMClient -> OpenAI/Claude (provider-agnostic via interface)
19
20Existing code that's reused:
21  [x] OrderRepository.GetByID (fetch order status)
22  [x] UserRepository.GetByID (personalize the greeting)
23  [x] JWT middleware (protected chat endpoint)
24  [x] Rate limiting middleware (LLM calls are expensive!)
25  [x] Prometheus metrics (track token usage + latency)

Notice that the majority of components are Topic 5 code being reused — the chatbot only adds RAG orchestration on top of a proven foundation.


20.08 Product Embedding Pipeline

Before semantic search works, every product must have an embedding. The use case below fetches products that aren’t yet embedded, processes them in a batch, then updates the database.

go
 1// Topic 6 will add this use case:
 2
 3// internal/usecase/ai/generate_product_embeddings.go
 4type GenerateProductEmbeddingsUseCase struct {
 5    productRepo domainProduct.Repository
 6    embedder    ai.Embedder
 7}
 8
 9func (uc *GenerateProductEmbeddingsUseCase) Execute(ctx context.Context) error {
10    // Fetch products that don't have an embedding yet
11    products, err := uc.productRepo.ListWithoutEmbedding(ctx, 100)
12    if err != nil {
13        return err
14    }
15
16    // Batch embed
17    texts := make([]string, len(products))
18    for i, p := range products {
19        texts[i] = p.Name + ". " + p.Description
20    }
21
22    embeddings, err := uc.embedder.EmbedBatch(ctx, texts)
23    if err != nil {
24        return err
25    }
26
27    // Update DB
28    for i, p := range products {
29        uc.productRepo.UpdateEmbedding(ctx, p.ID.String(), embeddings[i])
30    }
31
32    return nil
33}
34
35// Run as:
36// 1. One-time migration: embed all existing products
37// 2. Background job: embed new products after they're created
38// 3. Re-index: re-embed if the model changes

This pipeline is designed for three scenarios at once — the initial migration, a periodic job for new products, and a re-index when the embedding model changes — so no product is left behind.


20.09 Spec Update for AI Features

Every AI feature still obeys the SDD discipline: starting from a spec and acceptance criteria. The spec addition below defines two new features along with their measurable ACs.

yaml
 1# spec.yaml - additions for Topic 6
 2
 3features:
 4  # Existing features (already covered 90/100)
 5  - name: user-registration
 6  - name: product-catalog
 7  # ... existing features ...
 8
 9  # NEW: AI features (Topic 6)
10  - name: semantic-product-search
11    description: "Search products using natural language"
12    acceptance_criteria:
13      - id: AC1
14        description: "natural language query -> relevant products ordered by similarity"
15      - id: AC2
16        description: "query embedding generated via OpenAI text-embedding-ada-002"
17      - id: AC3
18        description: "hybrid search: semantic + keyword, weighted 70/30"
19      - id: AC4
20        description: "response time P95 < 2s (LLM call included)"
21
22  - name: ai-customer-support
23    description: "Chat with AI for FAQ and order support"
24    acceptance_criteria:
25      - id: AC1
26        description: "user can ask about order status via chat"
27      - id: AC2
28        description: "response uses context from FAQ RAG"
29      - id: AC3
30        description: "streaming response via SSE"
31      - id: AC4
32        description: "token usage tracked and alerted if it exceeds budget"

ACs like “P95 < 2s” and “token usage tracked” ensure AI features have verifiable pass criteria — not just “the AI works.”


20.10 Cost Monitoring for AI Features

Unlike ordinary features, an LLM has a per-call cost that must be monitored. The Prometheus metric definitions below track request count, tokens, latency, and cost in rupiah.

go
 1// Topic 6 will add LLM cost metrics
 2
 3var (
 4    LLMRequestsTotal = promauto.NewCounterVec(prometheus.CounterOpts{
 5        Namespace: "santekno",
 6        Subsystem: "llm",
 7        Name:      "requests_total",
 8    }, []string{"provider", "model", "feature"})
 9
10    LLMTokensUsed = promauto.NewCounterVec(prometheus.CounterOpts{
11        Namespace: "santekno",
12        Subsystem: "llm",
13        Name:      "tokens_used_total",
14    }, []string{"provider", "model", "type"}) // type: input/output
15
16    LLMLatency = promauto.NewHistogramVec(prometheus.HistogramOpts{
17        Namespace: "santekno",
18        Subsystem: "llm",
19        Name:      "request_duration_seconds",
20        Buckets:   []float64{0.5, 1, 2, 5, 10, 30},
21    }, []string{"provider", "feature"})
22
23    LLMCostIDR = promauto.NewCounterVec(prometheus.CounterOpts{
24        Namespace: "santekno",
25        Subsystem: "llm",
26        Name:      "cost_idr_total",
27    }, []string{"provider", "feature"})
28)
29
30// Alert: LLM cost > Rp 1,000,000 / day
31// Alert: LLM latency P99 > 10 seconds
32// Alert: LLM error rate > 5%

With cost metrics from the start, the team can set budget alerts and prevent the API bill from ballooning unnoticed — a trap AI features in production often fall into.


20.11 Rate Limiting for AI Endpoints

Because every AI call has a cost, its endpoints need stricter rate limits. The config below compares ordinary endpoint limits with AI endpoint limits.

go
 1// AI endpoints need stricter rate limits (cost per call)
 2
 3// delivery/http/middleware/rate_limit.go
 4var rateLimits = map[string]RateLimitConfig{
 5    // Existing endpoints
 6    "/api/v1/auth/login":    {Max: 5,   Window: 900},   // 5/15min
 7    "/api/v1/orders":        {Max: 20,  Window: 60},    // 20/min
 8
 9    // AI endpoints (stricter)
10    "/api/v1/products/search/semantic": {Max: 10, Window: 60},   // 10/min per user
11    "/api/v1/chat/support":             {Max: 5,  Window: 60},   // 5/min per user
12    "/api/v1/recommendations":          {Max: 20, Window: 60},   // 20/min per user
13}

A limit of 5 chats/minute per user protects the budget while also preventing abuse — and because the rate limiting middleware already exists in Topic 5, we only need to add new rules.


20.12 AI Feature Flags

AI features should be rolled out gradually, not all at once. The feature flags below control the activation and sampling rate of each feature, with gate middleware that blocks the endpoint when a flag is off.

go
 1// Feature flags for gradual rollout of AI features
 2
 3// config/features.go
 4type AIFeatureFlags struct {
 5    SemanticSearchEnabled      bool    `env:"FEATURE_SEMANTIC_SEARCH"`
 6    SemanticSearchSamplingRate float64 `env:"FEATURE_SEMANTIC_SEARCH_RATE" envDefault:"0.1"` // 10%
 7    ChatSupportEnabled         bool    `env:"FEATURE_CHAT_SUPPORT"`
 8    RecommendationsEnabled     bool    `env:"FEATURE_RECOMMENDATIONS"`
 9}
10
11// Middleware: check the feature flag before processing
12func AIFeatureGate(flags *AIFeatureFlags) echo.MiddlewareFunc {
13    return func(next echo.HandlerFunc) echo.HandlerFunc {
14        return func(c echo.Context) error {
15            path := c.Path()
16            if strings.Contains(path, "/semantic") && !flags.SemanticSearchEnabled {
17                return c.JSON(404, map[string]string{"error": "FEATURE_NOT_AVAILABLE"})
18            }
19            if strings.Contains(path, "/chat") && !flags.ChatSupportEnabled {
20                return c.JSON(404, map[string]string{"error": "FEATURE_NOT_AVAILABLE"})
21            }
22            return next(c)
23        }
24    }
25}
26
27// Sampling rate for A/B test:
28// 10% users -> semantic search
29// 90% users -> regular keyword search
30// Measure: conversion rate, session duration, bounce rate

Flags and sampling rates enable a measurable A/B test: we can open semantic search to 10% of users first, compare conversion, then expand if the result is positive.


20.13 What Topic 6 Will Build

To make expectations clear, here’s the complete map of Topic 6’s 20 articles. The list is grouped from LLM fundamentals to production AI.

text
 1TOPIC 6 - LLM-POWERED APPLICATIONS:
 2
 3Articles 01-05: LLM Fundamentals
 4  -> Provider abstraction (OpenAI, Claude, Gemini)
 5  -> Streaming responses (SSE, WebSocket)
 6  -> Context management + token counting
 7  -> Prompt templates with Go text/template
 8  -> Error handling: retry, fallback, timeout
 9
10Articles 06-10: Semantic Search (extend Santekno Shop)
11  -> Generate embeddings for 1000 products
12  -> pgvector IVFFlat index (already prepared in Article 11)
13  -> Hybrid search: semantic + keyword
14  -> Re-ranking to improve accuracy
15  -> Benchmark: keyword vs semantic search quality
16
17Articles 11-15: RAG Customer Support
18  -> FAQ document ingestion pipeline
19  -> Chunking strategy (recursive, semantic)
20  -> Retrieval + ranking
21  -> LLM response generation with context
22  -> Streaming via SSE
23
24Articles 16-20: Production AI
25  -> Token budget management
26  -> Cost monitoring + alerting
27  -> Prompt version control
28  -> Evaluation: RAGAS, LLM-as-judge
29  -> A/B testing AI vs non-AI features

Each group of articles extends the same Santekno Shop, not a throwaway example — so you learn AI in the context of a real production application.


20.14 End-State Architecture: Topic 5 + 6

To see the final picture, the diagram below unites the Topic 5 services with the new AI services in Topic 6. The AI nodes are marked separately to show their additive nature.

MERMAID
graph TD
    Client[Client Browser/App]
    GW[API Gateway<br/>Echo + Middleware Stack]
    Auth[User Service<br/>JWT + bcrypt + Redis]
    Product[Product Service<br/>tsvector + pgvector]
    Order[Order Service<br/>Atomic + Outbox]
    Payment[Payment Service<br/>HMAC + Idempotency]
    Notif[Notification Service<br/>Kafka Consumer]

    AI[AI Services<br/>NEW: Topic 6]
    Embed[Embedding Pipeline<br/>OpenAI + pgvector]
    Chat[Support Chatbot<br/>RAG + LLM]
    Rec[Recommender<br/>Collaborative + Semantic]

    Client --> GW
    GW --> Auth
    GW --> Product
    GW --> Order
    GW --> Payment
    GW --> AI

    AI --> Embed
    AI --> Chat
    AI --> Rec
    Embed --> Product
    Chat --> Order
    Chat --> Product

    style AI fill:#f0f4ff,stroke:#4f6ef7
    style Embed fill:#f0f4ff,stroke:#4f6ef7
    style Chat fill:#f0f4ff,stroke:#4f6ef7
    style Rec fill:#f0f4ff,stroke:#4f6ef7

This diagram makes clear the AI Services sit alongside the other services behind the same gateway — reusing auth, rate limiting, and observability without a parallel architecture.


20.15 Metrics That Should Rise After AI Features

AI features must impact the business, not just the technology. The comparison below records the Topic 5 baseline metrics and the targets expected once AI is live.

text
 1BEFORE (Topic 5 Baseline):
 2  Search CTR:         3.2% (keyword search)
 3  Add-to-cart rate:   8.1% (from search result)
 4  Avg. session time:  3.2 minutes
 5  Support tickets:    45/day (human agent needed)
 6
 7EXPECTED AFTER (Topic 6 AI Features):
 8  Search CTR:         12-18% (semantic = more relevant)
 9  Add-to-cart rate:   15-22% (better match = higher conversion)
10  Avg. session time:  5+ minutes (chat support keeps users engaged)
11  Support tickets:    < 20/day (AI handles 60%+ of FAQ queries)
12
13Measurement:
14  -> Feature flag A/B test: 50% keyword vs 50% semantic
15  -> Track via Grafana custom metrics
16  -> Evaluate after 2 weeks in production

A target like CTR rising to 12-18% gives a success benchmark testable via A/B test — if the number doesn’t rise, the AC feature isn’t considered passing.


20.16 Migration Plan: Embedding Existing Products

After deployment, the 1000 old products need to be embedded in one pass. The migration script below counts the total products, triggers the embedding job, then monitors its progress.

bash
 1# One-time migration after deploying Topic 6
 2
 3# 1. Deploy Topic 6 code (embedding pipeline)
 4# 2. Run the embedding job (background, non-blocking)
 5
 6# Migration script:
 7cat > scripts/embed_products.sh << 'EOF'
 8#!/bin/bash
 9echo "Starting product embedding migration..."
10
11# Check total products
12TOTAL=$(psql "$DATABASE_URL" -t -c "SELECT COUNT(*) FROM products WHERE embedding IS NULL")
13echo "Products to embed: $TOTAL"
14
15# Run the embedding job via API
16curl -X POST http://localhost:8080/admin/jobs/embed-products \
17  -H "Authorization: Bearer $ADMIN_TOKEN"
18
19# Monitor progress
20watch -n 5 'psql "$DATABASE_URL" -t -c "SELECT COUNT(*) FROM products WHERE embedding IS NOT NULL"'
21EOF
22
23# Expected duration:
24# 1000 products x 1 API call/product = ~1000 embedding requests
25# With batching (100 per call) = 10 API calls
26# OpenAI API latency: ~1-2 seconds per batch
27# Total: ~10-20 seconds
28
29# After embedding:
30# CREATE INDEX CONCURRENTLY idx_products_embedding
31# ON products USING ivfflat(embedding vector_cosine_ops)
32# WITH (lists = 100);
33# Duration: ~30 seconds for 1000 products

With batching of 100 products per call, migrating 1000 products finishes in tens of seconds — and CREATE INDEX CONCURRENTLY ensures index creation doesn’t lock the production table.


20.17 Compatibility: Topic 5 Code Doesn’t Need to Change

The core promise of the additive approach is zero changes to the old code. The summary below separates what stays intact from Topic 5 and what’s purely added in Topic 6.

text
 1AI integration strategy: ADDITIVE, not disruptive
 2
 3What does NOT need to change in Topic 5:
 4  [x] Domain entities (User, Product, Order, Payment, Notification)
 5  [x] Repository interfaces (can already accommodate AI queries)
 6  [x] Existing HTTP handlers (behavior unchanged)
 7  [x] Database schema (only add index + fill embedding column)
 8  [x] Kafka topics (AI can subscribe to the same events)
 9  [x] Tests (all unit + integration tests still pass)
10
11What is ADDED in Topic 6:
12  [+] New domain package: internal/domain/ai/
13  [+] New usecase: semantic search, chat, recommendations
14  [+] New handler: AI endpoints (/api/v1/chat, /api/v1/recommendations)
15  [+] New infrastructure: LLM clients, embedding service
16  [+] New migration: IVFFlat index on the embedding column
17
18Zero breaking changes. Feature flags enable gradual rollout.

Because there are no breaking changes, the team can release AI with confidence — all old tests stay green and a rollback is just turning off the feature flag.


20.18 Topic 5: Final Score Card

As a closing evaluation, the scorecard below compares the target and actual result in each quality category. Every row indicates a passing status.

text
 1+-------------------------------------------------------------------+
 2| SANTEKNO SHOP - TOPIC 5 COMPLETION SCORECARD                      |
 3+-------------------------+-----------+-----------------------------+
 4| Category                | Target    | Actual                      |
 5+-------------------------+-----------+-----------------------------+
 6| Spec Coverage           | >= 80/100 | 95/100 PASS                 |
 7| Unit Test Coverage      | >= 80%    | 87% PASS                    |
 8| Integration Tests       | >= 50     | 68 cases PASS               |
 9| E2E Tests               | >= 10     | 22 cases PASS               |
10| CI Pipeline Stages      | 5 stages  | 5 stages PASS               |
11| Docker Image Size       | < 30MB    | ~21MB PASS                  |
12| P95 Latency (50 VU)     | < 500ms   | 180ms max PASS              |
13| Error Rate              | < 0.1%    | 0.02% PASS                  |
14| Observability           | 3 pillars | Metrics+Trace+Logs PASS     |
15| AI-Ready                | pgvector  | Column + interface PASS     |
16+-------------------------+-----------+-----------------------------+
17| OVERALL                 |           | PRODUCTION READY            |
18+-------------------------+-----------+-----------------------------+

This scorecard makes clear that Santekno Shop isn’t a toy project: every quality target is exceeded, and the “PRODUCTION READY” status is backed by real numbers, not claims.


20.19 What You Can Do Right Now

After finishing Topic 5, there are plenty of concrete things you can try immediately. The command list below shows how to run, test, and explore Santekno Shop locally.

bash
 1# 1. Run Santekno Shop locally:
 2docker-compose up -d
 3go run ./cmd/server/
 4
 5# 2. See all tests pass:
 6make test  # unit + integration
 7
 8# 3. See the CI pipeline green on GitHub
 9
10# 4. Browse the API in Swagger UI:
11#    http://localhost:8080/swagger
12
13# 5. View metrics in Grafana:
14#    http://localhost:3000
15
16# 6. View traces in Jaeger:
17#    http://localhost:16686
18
19# 7. Clone and extend it yourself:
20git clone github.com/santekno/santekno-shop
21# Start Topic 6: add AI features

With an app that runs fully locally, you have a real sandbox to experiment before diving into the AI integration in Topic 6.


20.20 Conclusion and Bridge to Topic 6

Santekno Shop isn’t a hello-world tutorial. It’s a production-grade e-commerce platform built with the Spec-Driven Development methodology, a Clean + Modular Monolith architecture, a modern Go stack, and measurable quality: 95/100 spec compliance, 87% test coverage, a 5-stage CI, and SLO-based alerting.

The most important part for golang LLM integration: every architectural decision was made with AI in mind. The embedding VECTOR(1536) column has existed since day one, the provider-agnostic LLMClient interface is ready to implement, and the additive architecture allows adding AI features without changing a single line of the Topic 5 code.

In Topic 6, we’ll fill that empty embedding column, build RAG-based chat support, and add product recommendations with semantic similarity. The foundation is solid, the code is clean, the tests are green, and the pipeline is automated. Now it’s time to add intelligence.

Related Articles

💬 Comments