The user wants a "Real-time personalization service with contextual bandits, quotas, and audit-friendly logs."
This is a system design and implementation task. I need to break it down into several key components:
-
Contextual Bandits: The core ML logic. It needs to handle exploration vs. exploitation.
- Input: Context (user features, item features).
- Output: Action (item to recommend).
- Feedback: Reward (click, conversion, etc.).
- Algorithms: LinUCB, Thompson Sampling, or a neural network-based approach. For a "service," a LinUCB implementation is often the standard baseline for explainability and simplicity in a production environment.
-
Quotas: Limiting the exposure of certain items or the usage of the service by clients.
- This sounds like rate limiting or inventory management (e.g., "don't show this ad more than 1000 times").
- Mechanism: A fast key-value store (Redis) to track counters.
-
Audit-Friendly Logs: Crucial for compliance (GDPR/CCPA) and debugging.
- We need to log why a decision was made (features, model version, probabilities).
- We need to log the outcome.
- Immutable logs (append-only) sent to a data lake or specialized logging service.
-
Real-time Architecture:
- Low latency is key.
- API endpoints for
GET /recommend and POST /reward.
- Asynchronous processing for model updates (or warm-starting with periodic batch updates).
High-Level Architecture:
- API Gateway: Entry point.
- Personalization Service (Python/Go): Hosts the bandit logic.
- Feature Store (Redis/DynamoDB): User context pre-fetching.
- Model Store: Storing the bandit parameters (A and b matrices for LinUCB).
- Quota Service (Redis): Atomic increment operations.
- Logging Pipeline (Kafka/Kinesis -> S3/Redshift): For the audit trail.
Step-by-Step Implementation Plan:
- Step 1: The Bandit Logic. Implement a simple LinUCB agent. It's efficient and mathematically sound for this demonstration.
- Step 2: The API Layer. Use FastAPI (Python) for speed and ease of documentation.
- Step 3: Quota Management. A middleware or helper function checking Redis before returning an arm.
- Step 4: Structured Logging. Use a standard JSON logger format.
- Step 5: Orchestration. Wire it all together.
Drafting the Code Structure:
config.py: Settings.
models.py: Data structures (Request/Response).
bandit.py: The LinUCB implementation.
quota.py: Redis integration for quotas.
logger.py: Structured logging.
main.py: FastAPI application.
Refining the Bandit Logic (LinUCB):
- Disjoint Linear Model (separate parameters per arm) is easier to manage in a dynamic inventory setting than a Hybrid model, but Hybrid allows context. Let's stick to Disjoint for simplicity in code, but mention that the context vector x interacts with the arm parameters.
- Wait, if items change frequently (dynamic inventory), standard LinUCB is hard because new arms appear constantly.
- Alternative: Use an Embedding-based approach or assume a fixed set of "strategies" (super-arms).
- Better approach for a generic prompt: Assume a fixed set of Arms (e.g., "Layout A", "Layout B", "Promo Banner 1") to make the code runnable and understandable. Or, if it's item recommendation, assume a "Warm Start" where we load arms from a DB. Let's stick to a manageable set of arms for the code example but design the system to handle dynamic loading.
Refining the Quota Logic:
KEY: campaign_id:day
VALUE: count
- Check
count < limit.
Refining Audit Logs:
- Log format:
{"timestamp": ..., "event_type": "decision", "request_id": ..., "context": ..., "chosen_arm": ..., "probabilities": ...}
- Reward log:
{"event_type": "reward", "request_id": ..., "reward": ...}
Writing the Solution:
- Intro: Define the architecture.
- The Code: Provide a complete, runnable Python application using FastAPI.
- Dependencies:
fastapi, redis, numpy.
- Key Classes:
LinUCB: The core logic.
QuotaManager: Redis interaction.
AuditLogger: Structured output.
- Endpoints:
/predict: Get context, check quotas, run bandit, log decision, return action.
/feedback: Update model (online learning) or push to buffer, log reward.
Self-Correction/Edge Cases during drafting:
- Concurrency: Updating the LinUCB matrices (A, b) in memory while reading them is not thread-safe. In a real production system, you wouldn't update the model in-memory directly in the API request handler unless you use locking or an actor model.
- For this demo: I will use a lock (
threading.Lock) or simply note that for scalability, updates should be pushed to a queue (Kafka) and consumed by a dedicated training worker.
- Decision: I will implement an "Async Update" pattern or a thread-safe in-memory update for simplicity, but emphasize that production systems usually decouple inference and training. Let's do thread-safe in-memory for the single-node demo to keep it self-contained, but add a comment about distributed systems.
Let's structure the response:
- System Architecture Diagram (Text-based).
- The Core Components (Code).
- The FastAPI Service (Code).
- Explanation of the Audit and Quota mechanisms.
- Scaling considerations.
Let's write the code.
- Bandit: Standard LinUCB. d dimensions.
- Quota: Mock Redis or actual Redis logic. I'll write the logic assuming a
redis client.
- Logger: Standard
structlog or json logger.
Constraint Checklist & Confidence Score:
- Real-time? Yes (FastAPI).
- Contextual Bandits? Yes (LinUCB).
- Quotas? Yes (Redis logic).
- Audit logs? Yes (Structured JSON).
- Engineer/Design? Yes.
Confidence Score: 5/5
Mental Sandbox Simulation:
- User calls
/recommend with user features.
- Service fetches item quotas.
- Service filters items with exceeded quotas.
- Service runs LinUCB on remaining items.
- Service returns best item.
- Service logs the context and decision.
- User calls
/reward with click info.
- Service updates the specific arm's weights.
- Service logs the reward.
This flow is solid. I will present the solution now.
This is a comprehensive system design and implementation for a Real-Time Personalization Service.
This solution uses Python (FastAPI) for the service layer, Redis for stateful quota management, and a LinUCB algorithm for the contextual bandit logic.
1. High-Level Architecture
The system consists of three distinct layers:
- The Inference Layer (API): A low-latency FastAPI service that accepts user context, checks quotas, calculates the best action (Arm), and returns the recommendation.
- The State Layer (Redis):
- Bandit State: Stores the Disjoint Linear Model coefficients (Aa, ba) for each Arm.
- Quota State: Stores atomic counters for campaign budgets or frequency caps.
- The Audit Layer (Logger): An asynchronous, structured JSON logger that emits an immutable "Decision Trail" for every request and feedback event.
2. Project Structure
personalization_service/
├── app/
│ ├── __init__.py
│ ├── main.py # API Endpoints
│ ├── bandit.py # LinUCB Logic
│ ├── quota.py # Quota Enforcement
│ ├── schema.py # Pydantic Models
│ └── audit.py # Structured Logging
├── requirements.txt
└── Dockerfile
3. Implementation
A. Dependencies (requirements.txt)
fastapi
uvicorn
redis
numpy
pydantic
python-json-logger
B. The Contextual Bandit Engine (app/bandit.py)
We implement Disjoint LinUCB. Unlike standard Multi-Armed Bandits, this learns separate parameters for every action (Arm) but uses shared context to predict rewards.
import numpy as np
import redis
import json
import logging
# Configure Logger
logger = logging.getLogger("bandit")
class LinUCBService:
def __init__(self, redis_client: redis.Redis, context_dim: int = 5, alpha: float = 0.5):
self.redis = redis_client
self.d = context_dim # Dimension of the context vector
self.alpha = alpha # Exploration parameter
def _get_arm_params(self, arm_id: str):
"""Retrieve A (dxd) and b (dx1) matrices from Redis."""
key_a = f"model:arm:{arm_id}:A"
key_b = f"model:arm:{arm_id}:b"
# Initialize if not exists (Identity matrix and Zeros)
if not self.redis.exists(key_a):
self.redis.set(key_a, json.dumps(np.identity(self.d).tolist()))
self.redis.set(key_b, json.dumps(np.zeros(self.d).tolist()))
A = np.array(json.loads(self.redis.get(key_a)), dtype=float)
b = np.array(json.loads(self.redis.get(key_b)), dtype=float)
return A, b
def _save_arm_params(self, arm_id: str, A: np.ndarray, b: np.ndarray):
"""Persist updated matrices to Redis."""
self.redis.set(f"model:arm:{arm_id}:A", json.dumps(A.tolist()))
self.redis.set(f"model:arm:{arm_id}:b", json.dumps(b.tolist()))
def predict(self, context_vec: list, available_arms: list, quota_filter: set) -> str:
"""
Select the best arm based on UCB score.
quota_filter: Set of arm_ids that have exceeded quotas and should be ignored.
"""
x = np.array(context_vec)
if x.shape[0] != self.d:
raise ValueError(f"Context dimension mismatch. Expected {self.d}, got {x.shape[0]}")
best_arm = None
max_ucb = -1
# Filter out arms that hit quotas
valid_arms = [arm for arm in available_arms if arm not in quota_filter]
if not valid_arms:
return None # All items exhausted
for arm_id in valid_arms:
A, b = self._get_arm_params(arm_id)
# Calculate Theta (Coefficients)
A_inv = np.linalg.inv(A)
theta = np.dot(A_inv, b)
# Calculate UCB: theta_T * x + alpha * sqrt(x_T * A_inv * x)
p = np.dot(theta, x) + self.alpha * np.sqrt(np.dot(x.T, np.dot(A_inv, x)))
if p > max_ucb:
max_ucb = p
best_arm = arm_id
return best_arm
def update(self, arm_id: str, context_vec: list, reward: float):
"""Online update based on user feedback (reward=1 click, 0 skip)."""
x = np.array(context_vec)
A, b = self._get_arm_params(arm_id)
# Rank-1 update: A = A + x * x_T, b = b + r * x
A += np.outer(x, x)
b += reward * x
self._save_arm_params(arm_id, A, b)
logger.info(f"Model updated for arm {arm_id}", extra={"arm_id": arm_id, "reward": reward})
C. Quota Enforcement (app/quota.py)
This uses Redis atomic increments to ensure we don't overserve items.
import redis
class QuotaManager:
def __init__(self, redis_client: redis.Redis):
self.redis = redis_client
def check_quotas(self, arm_ids: list) -> set:
"""
Returns a set of arm_ids that have exceeded their daily quota.
"""
exhausted_arms = set()
# Use pipelining for network efficiency
pipeline = self.redis.pipeline()
for arm_id in arm_ids:
pipeline.get(f"quota:{arm_id}:count")
pipeline.get(f"quota:{arm_id}:limit")
results = pipeline.execute()
# Results come in pairs [count, limit, count, limit...]
for i in range(0, len(results), 2):
arm_id = arm_ids[i//2]
current_count = float(results[i] or 0)
limit = float(results[i+1] or 1) # Default limit 1 if not set
if current_count >= limit:
exhausted_arms.add(arm_id)
return exhausted_arms
def increment_quota(self, arm_id: str):
"""Increment usage counter atomically."""
self.redis.incr(f"quota:{arm_id}:count")
D. Audit-Friendly Logs (app/audit.py)
We use python-json-logger to output structured logs that can be shipped directly to ELK, Splunk, or S3 for auditing.
import logging
import json
from pythonjsonlogger import jsonlogger
from datetime import datetime
class AuditLogger:
def __init__(self):
self.logger = logging.getLogger("audit")
logHandler = logging.StreamHandler()
formatter = jsonlogger.JsonFormatter('%(timestamp)s %(level)s %(name)s %(message)s')
logHandler.setFormatter(formatter)
self.logger.addHandler(logHandler)
self.logger.setLevel(logging.INFO)
def log_decision(self, request_id: str, context: list, arm_id: str, reason: str):
self.logger.info("DecisionMade", extra={
"timestamp": datetime.utcnow().isoformat(),
"audit_type": "DECISION",
"request_id": request_id,
"context": context,
"selected_arm": arm_id,
"reason": reason # e.g., "ucb_score" or "fallback"
})
def log_feedback(self, request_id: str, arm_id: str, reward: float):
self.logger.info("FeedbackReceived", extra={
"timestamp": datetime.utcnow().isoformat(),
"audit_type": "FEEDBACK",
"request_id": request_id,
"arm_id": arm_id,
"reward": reward
})
E. The API Service (app/main.py)
from fastapi import FastAPI, HTTPException, BackgroundTasks
import redis
import uuid
from typing import List, Optional
from .bandit import LinUCBService
from .quota import QuotaManager
from .audit import AuditLogger
from .schema import PredictRequest, PredictResponse, FeedbackRequest
# Initialize Resources
rdb = redis.Redis(host='localhost', port=6379, db=0)
bandit = LinUCBService(rdb, context_dim=5)
quotas = QuotaManager(rdb)
audit = AuditLogger()
app = FastAPI(title="Real-Time Personalization Engine")
@app.post("/predict", response_model=PredictResponse)
async def predict(request: PredictRequest):
"""
Input: Context vector and available Arms (items).
Output: Selected Arm ID.
"""
# 1. Check Quotas for all available arms
# In a real system, quotas might be pre-loaded or cached locally for speed
exhausted_arms = quotas.check_quotas(request.available_arms)
# 2. Run Bandit Inference
chosen_arm = bandit.predict(request.context, request.available_arms, exhausted_arms)
request_id = str(uuid.uuid4())
# 3. Handle Fallback (if all quotas exhausted or errors)
if chosen_arm is None:
chosen_arm = "fallback_item" # Default logic
audit.log_decision(request_id, request.context, chosen_arm, "all_quotas_exhausted")
else:
audit.log_decision(request_id, request.context, chosen_arm, "linucb_selection")
# Optimistically increment quota or do it in background
quotas.increment_quota(chosen_arm)
return PredictResponse(request_id=request_id, selected_arm=chosen_arm)
@app.post("/feedback")
async def feedback(request: FeedbackRequest):
"""
Updates the model based on reward (e.g., click).
"""
if not (0.0 <= request.reward <= 1.0):
raise HTTPException(status_code=400, detail="Reward must be between 0 and 1")
# 1. Audit the feedback
audit.log_feedback(request.request_id, request.arm_id, request.reward)
# 2. Update Bandit Weights (Online Learning)
# Note: In high throughput, this might be pushed to a Kafka queue
# and processed by a Flink job to avoid blocking the API.
bandit.update(request.arm_id, request.context, request.reward)
return {"status": "updated"}
4. Key Design Decisions
1. Handling Real-Time Constraints
- Redis Pipelining: In
QuotaManager, we batch the GET requests. This reduces the RTT (Round Trip Time) significantly, allowing us to check quotas for 50 items in a single network hop.
- In-Memory Math: The matrix inversions in LinUCB happen in memory. For dimensions < 100,
numpy.linalg.inv is sub-millisecond.
2. Audit Trail Strategy
The logs are structured JSON. This allows data engineering teams to pipe these logs directly into a Data Lake (S3) or an OLAP database (ClickHouse/BigQuery) to answer questions like:
- "Why was User X shown Item Y?" (Traceable via
request_id and context snapshot).
- "Did the model drift after deployment Z?" (Analyze
reward distribution over time).
3. The "Cold Start" & State Storage
The code initializes matrices to the Identity matrix (I) and zeros (0) inside Redis if they don't exist. This allows the system to dynamically handle new Arms (items) appearing in the inventory without a code redeployment.
5. How to Run and Test
- Start Redis:
docker run -p 6379:6379 -d redis
- Run Service:
uvicorn app.main:app --reload
- Set a Quota:
redis-cli SET "quota:item_A:limit" 100
- Send a Prediction Request:
curl -X 'POST' \
'http://127.0.0.1:8000/predict' \
-H 'Content-Type: application/json' \
-d '{
"context": [0.5, 1.2, 0.1, 0.9, 0.3],
"available_arms": ["item_A", "item_B"]
}'
- Send Feedback:
curl -X 'POST' \
'http://127.0.0.1:8000/feedback' \
-H 'Content-Type: application/json' \
-d '{
"request_id": "UUID_FROM_PREVIOUS_CALL",
"arm_id": "item_A",
"context": [0.5, 1.2, 0.1, 0.9, 0.3],
"reward": 1.0
}'