Multi-Tenant User Preferences Service Plan
1. Requirements Summary
- Multi-Tenant: Isolate preferences by tenant (e.g., organizations). Users belong to tenants; preferences scoped to
{tenant_id, user_id}.
- Polymorphic Value Objects: Preferences store typed values (e.g., string, int, bool, JSON object/array) as immutable value objects with type safety and polymorphism.
- Event-Driven Propagation: Changes (create/update/delete) emit events for real-time sync to downstream services (e.g., UI personalization, analytics).
- Conflict Resolution: Handle concurrent updates, hierarchical overrides (global/tenant/user), and propagation conflicts via versioning and merge rules.
- Non-Functional: High availability (99.99%), low latency (<100ms P99 reads), scalable to 1M+ tenants/users, auditability.
Assumptions: Microservice architecture; event bus (Kafka/Pulsar); relational DB (Postgres with JSONB); gRPC/REST APIs; languages like Go/Java for service impl.
2. High-Level Architecture
[Client Apps] --> [API Gateway (Authz + Tenant Routing)] --> [Preferences Service]
|
v
[Postgres (Primary Store)] <--> [Event Bus (Kafka Topics: prefs-updated, prefs-deleted)]
|
v
[Downstream Subscribers: Caches (Redis), Analytics, Personalization Services, Search Index]
- Core Service: Handles CRUD, validation, storage, event emission.
- CQRS Pattern: Commands mutate state + emit events; Queries read from cache/replica for scale.
- Saga/Choreography: Event-driven for propagation; no distributed transactions.
3. Domain Model (DDD-Inspired)
Aggregates
- Preference Aggregate: Root entity
{tenant_id, user_id, key} (composite ID).
- Fields:
value (PolymorphicValueObject), version (int64, for optimistic locking), created_at, updated_at, metadata (JSON for source/ttl).
- Invariants: Unique per
{tenant_id, user_id, key}; value immutable.
Polymorphic Value Objects
Use discriminated unions (Go: interfaces; JSON Schema: $discriminator; DB: JSONB with type field).
// Go Example
type PreferenceValue interface {
Type() string
MarshalJSON() ([]byte, error)
UnmarshalJSON(data []byte) error
Equal(other PreferenceValue) bool
}
type StringValue string
func (v StringValue) Type() string { return "string" }
func (v StringValue) Value() interface{} { return string(v) }
// Similarly: NumberValue(float64), BoolValue(bool), ObjectValue(map[string]PreferenceValue), ArrayValue([]PreferenceValue)
type Preference struct {
TenantID string
UserID string
Key string
Value PreferenceValue
Version int64
UpdatedAt time.Time
}
- Storage in Postgres:
CREATE TABLE preferences (
tenant_id UUID NOT NULL,
user_id UUID NOT NULL,
key TEXT NOT NULL,
value JSONB NOT NULL, -- e.g., {"type": "string", "value": "dark-mode"}
version BIGINT NOT NULL DEFAULT 1,
updated_at TIMESTAMPTZ NOT NULL,
PRIMARY KEY (tenant_id, user_id, key)
);
CREATE INDEX ON preferences (tenant_id, user_id);
- Validation: Enforce types via service layer (e.g., key prefixes like
ui.theme, privacy.gdpr).
Hierarchical Preferences (Optional Extension)
Support layers: global > tenant > user. Resolve via merge (user overrides tenant).
4. Multi-Tenancy
5. API Design (gRPC + REST)
service PreferencesService {
rpc UpsertPreference(UpsertRequest) returns (UpsertResponse); // Returns ETag/version
rpc GetPreference(GetRequest) returns (Preference); // With tenant/user/key
rpc GetUserPreferences(GetUserPrefsRequest) returns (stream Preference);
rpc DeletePreference(DeleteRequest) returns (google.protobuf.Empty);
rpc BulkUpsert(BulkUpsertRequest) returns (BulkResponse); // For migrations
}
message UpsertRequest {
string tenant_id = 1;
string user_id = 2;
string key = 3;
oneof value {
StringValue string_value = 4;
NumberValue number_value = 5;
// etc. (polymorphic)
}
// If-Match ETag for conditional upsert
}
- Auth: JWT with tenant/user claims.
- Rate Limiting: Per-tenant quotas.
6. Event-Driven Propagation
- Event Schema (Avro/Protobuf):
message PreferenceEvent {
string event_type = 1; // "UPDATED", "DELETED", "CREATED"
string tenant_id = 2;
string user_id = 3;
string key = 4;
PreferenceValue old_value = 5;
PreferenceValue new_value = 6;
int64 version = 7;
google.protobuf.Timestamp timestamp = 8;
}
- Topics:
prefs.events.{env}.{tenant_id?} (fan-out by tenant for scale).
- Emission: On successful mutate (post-version bump):
- Validate + version++ (CAS:
UPDATE ... SET version = version + 1 WHERE version = ?).
- Publish to Kafka (idempotent producer with transaction ID).
- Subscribers (in other services):
- Redis cache invalidation/update.
- Elasticsearch indexing for search.
- WebSocket push for real-time UI.
- Idempotency: Subscribers track
version; skip if newer local.
7. Conflict Resolution
Multi-level strategies:
| Conflict Type | Strategy | Mechanism |
|---|
| Concurrent Writes | Optimistic Locking | Client provides If-Match: version; service rejects if mismatch (409 Conflict). Retry with new version. |
| Hierarchical Overrides | Merge Rules | Query stack: user → tenant → global. Deep-merge objects (user wins). Event includes effective_value. |
| Propagation Conflicts | Last-Write-Wins (LWW) + Tombstones | Events carry version; subscriber applies if event.version > local.version. Deletes emit tombstones. |
| Stale Reads | Read-Your-Writes + Cache | Eventual consistency; strong via cache-aside + events. |
| Bulk/Idempotency | Transaction ID | Bulk ops use unique TXN ID; dedupe in DB/event log. |
- Custom Rules: Metadata field for priority (e.g.,
source: "admin" > "user").
- Audit Log: Separate table/topic for all changes.
8. Persistence & Caching
- Primary: Postgres (JSONB indexes on
value->>'type', GIN for nested queries).
- Cache: Redis Cluster (TTL 1h; key:
prefs:{tenant}:{user}:{key}).
- Backup: WAL + S3 snapshots; CDC (Debezium) for events.
- Query Patterns:
- Point Get: Cache → DB.
- List (paginated): DB replica + cache warming via events.
9. Scalability & Reliability
- Horizontal Scale: Stateless service (multiple replicas); Kafka partitioning by
{tenant_id}-{user_id}.
- Monitoring: Prometheus metrics (latency, event lag); traces (Jaeger); alerts on version conflicts >1%.
- Fault Tolerance:
- DB: Read replicas, failover.
- Events: At-least-once + idempotency; dead-letter queues.
- Deployment: Kubernetes; Circuit breakers (Istio).
- Migration: Versioned schema; feature flags for poly values.
10. Implementation Roadmap
- Week 1: Domain model, Postgres schema, core CRUD (no events).
- Week 2: Polymorphic VO, gRPC API, unit/integration tests.
- Week 3: Event emission (Kafka), basic subscribers.
- Week 4: Conflict resolution, caching, multi-tenancy RLS.
- Week 5+: Load testing, hierarchical prefs, production rollout.
Risks: Event ordering (mitigate with total order per {tenant,user}); JSONB perf (use typed columns if types stabilize); Tenant blast radius (quotas).
This plan delivers a robust, evolvable service. Questions on specifics (e.g., tech stack tweaks)?