IMVEEDev Portal

Enterprise & Tenant Konfiguration

Diese Seite dokumentiert wie SOCSuite Konfiguration auf zwei Ebenen verwaltet:

  1. Infrastruktur-Konfiguration — immutable pro Deployment (env, k8s ConfigMap, Infisical)
  2. Enterprise/Tenant-Konfiguration — runtime-änderbar, pro Tenant (DB JSONB + Redis-Cache)

Zielgruppe: Backend-Entwickler und DevOps.


Überblick: Zwei Konfigurations-Ebenen

EbeneSpeicherLebenszyklusÄnderungZielgruppe
Infrastrukturenv, Infisical, k8s ConfigMapImmutable pro DeploymentDeployment nötigDevOps
Enterprise/TenantDB (JSONB) + Redis-CacheRuntime-änderbar, pro TenantKeine DeploymentsAdmins, Multi-Tenant
CI/PipelineGitLab CI/CD Variables, InfisicalNur Build/Deploy-ZeitPipeline-ChangeDevOps

:::info [Prinzip] Infrastruktur wird über Environment-Variablen und Kubernetes ConfigMaps gesteuert. Enterprise/Tenant wird über DB-Tabellen mit JSONB-Spalten gesteuert — mit Redis als Cache-Layer. :::


Infrastruktur-Konfiguration

Infrastruktur-Konfiguration gilt global für alle Instanzen/Deployments und wird über:

  • Environment-Variablen (k8s Secrets, k8s Env-from)
  • Infisical ( Secrets Management)
  • k8s ConfigMaps (nicht-sensitive Config)
  • GitLab CI/CD Variables (nur Build/Deploy)

gesteuert.

Beispiele

VariableBeschreibungQuelle
DATABASE_URLPostgreSQL-VerbindungInfisical / k8s Secret
REDIS_URLRedis-VerbindungInfisical / k8s Secret
METRICS_INTERVALPrometheus-Export-Intervallk8s ConfigMap
API_URLExterne API-URLk8s ConfigMap
TLS_CERT_PATHPfad zum TLS-Zertifikatk8s Secret

:::warn [Sensitive Values] Credentials, API-Keys, TLS-Certs gehören NIEMALS in ConfigMaps — immer Secrets/Infisical. :::


Enterprise & Tenant Konfiguration

Enterprise/Tenant-Konfiguration ist runtime-änderbar und kann pro Tenant unterschiedliche Werte haben.

Architektur

┌─────────────────────────────────────────────────────────┐
│                    SOCSuite API                          │
│                                                          │
│  ┌──────────────┐    ┌──────────────┐    ┌───────────┐  │
│  │   Handler    │───→│   Service    │───→│   Cache   │  │
│  │              │    │              │    │  (Redis)  │  │
│  └──────────────┘    └──────────────┘    └───────────┘  │
│                            │                │           │
│                            ▼                │           │
│                    ┌──────────────┐         │           │
│                    │   DB (PG)    │◄────────┘           │
│                    │  JSONB Columns│                    │
│                    └──────────────┘                    │
└─────────────────────────────────────────────────────────┘

Datenbank-Struktur

Enterprise-Konfiguration wird in JSONB-Spalten gespeichert:

-- Beispiel: tenant_settings Tabelle
CREATE TABLE tenant_settings (
    id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id   UUID NOT NULL REFERENCES tenants(id),
    key         TEXT NOT NULL,
    value       JSONB NOT NULL,
    updated_at  TIMESTAMPTZ DEFAULT NOW(),
    UNIQUE(tenant_id, key)
);

-- Index für schnellen Lookups
CREATE INDEX idx_tenant_settings_tenant_key ON tenant_settings(tenant_id, key);

Redis-Cache-Layer

// Pseudocode: Cache-Pattern für Tenant-Config
func GetTenantConfig(ctx context.Context, tenantID string) (TenantConfig, error) {
    // 1. Redis prüfen
    cacheKey := fmt.Sprintf("tenant:config:%s", tenantID)
    cached, err := redis.Get(ctx, cacheKey).Result()
    if err == nil {
        var cfg TenantConfig
        json.Unmarshal([]byte(cached), &cfg)
        return cfg, nil // Cache-Hit
    }

    // 2. Cache-Miss → DB laden
    var cfg TenantConfig
    err = db.QueryRowContext(ctx, `
        SELECT key, value FROM tenant_settings 
        WHERE tenant_id = $1
    `, tenantID).Scan(...)

    // 3. In Cache schreiben (TTL: 5 Minuten)
    if err == nil {
        redis.Set(ctx, cacheKey, cfg, 5*time.Minute)
    }

    return cfg, err
}

Konfigurations-Beispiele

Config-SchlüsselTypBeschreibungBeispiel-Wert
tenant_pricing_tierStringPreisstufe des Tenants"enterprise", "pro", "free"
feature_limitsJSONBFeature-Limits pro Tenant{"max_agents": 100, "retention_days": 365}
whitelabel_paramsJSONBWhite-Label Customization{"logo_url": "...", "primary_color": "#123456"}
api_rate_limitIntegerAPI-Rate-Limit pro Minute1000
enabled_featuresArrayAktivierung von Features["advanced_analytics", "sso"]

Feature-Flags (Optional)

Für dynamische Feature-Aktivierung kann ein Feature-Flag-Service integriert werden:

Optionen

ServiceIntegrationVorteile
UnleashEigenes Deployment oder CloudRich targeting, A/B testing
LaunchDarklySaaSEnterprise-ready, analytics
eigene DB-Lösungtenant_settings JSONBEinfach, keine External Dependencies

Implementierung mit eigener DB-Lösung

func IsFeatureEnabled(tenantID, featureName string) bool {
    // 1. Check global default
    globalEnabled := getGlobalFeatureFlag(featureName)
    if !globalEnabled {
        return false
    }

    // 2. Check tenant-specific override
    var overrides []string
    db.QueryRow(`
        SELECT value->'enabled_features'->>'values'
        FROM tenant_settings 
        WHERE tenant_id = $1 AND key = 'whitelabel_params'
    `, tenantID).Scan(&overrides)

    for _, f := range overrides {
        if f == featureName {
            return true
        }
    }

    return globalEnabled
}

:::info [Empfehlung] Für MVP: tenant_settings JSONB reicht aus. Bei >10 Tenants oder komplexem Targeting → Unleash oder LaunchDarkly evaluieren. :::


Migration: Von Hardcoded zu Tenant-Config

Schritt 1: DB-Migration

-- tenant_settings Tabelle erstellen
CREATE TABLE IF NOT EXISTS tenant_settings (
    id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id   UUID NOT NULL REFERENCES tenants(id),
    key         TEXT NOT NULL,
    value       JSONB NOT NULL,
    updated_at  TIMESTAMPTZ DEFAULT NOW(),
    UNIQUE(tenant_id, key)
);

Schritt 2: Service-Schicht implementieren

// internal/service/tenant_config.go
type TenantConfigService struct {
    db    *sql.DB
    redis *redis.Client
}

func (s *TenantConfigService) GetConfig(ctx context.Context, tenantID string) (TenantConfig, error) {
    // Cache-Then-DB Pattern wie oben
}

func (s *TenantConfigService) UpdateConfig(ctx context.Context, tenantID string, key string, value interface{}) error {
    // DB updaten + Cache invalidieren
    jsonValue, _ := json.Marshal(value)
    _, err := s.db.Exec(`
        INSERT INTO tenant_settings (tenant_id, key, value)
        VALUES ($1, $2, $3)
        ON CONFLICT (tenant_id, key) 
        DO UPDATE SET value = $3, updated_at = NOW()
    `, tenantID, key, jsonValue)
    
    if err == nil {
        cacheKey := fmt.Sprintf("tenant:config:%s", tenantID)
        s.redis.Del(ctx, cacheKey)
    }
    
    return err
}

Schritt 3: Cache-Invalidierung

Bei Config-Änderungen den Redis-Cache invalidieren:

// Bei UPDATE/INSERT auf tenant_settings
cacheKey := fmt.Sprintf("tenant:config:%s", tenantID)
redis.Del(ctx, cacheKey)

Best Practices

✅ DO

  • Cache-Layer verwenden — Redis für Tenant-Config mit TTL (5–15 Min.)
  • DB als Source of Truth — Redis ist nur Cache, bei Ausfall muss DB reichen
  • Schema-Validierung — JSONB mit CHECK constraints oder App-Level Validation (Zod/go-playground)
  • Audit-Logging — Alle Config-Änderungen in tenant_settings_audit table loggen

❌ DON'T

  • Keine hardcoded Tenant-IDs — immer über Context/Token resolve
  • Kein Cache-Stale ohne TTL — immer Expiration setzen
  • Kein direkter DB-Zugriff ohne Cache — Redis zuerst prüfen
  • Keine sensiblen Tenant-Keys in Redis ohne Encryption — API-Keys verschlüsselt speichern

Siehe auch

Auf dieser Seite