
Software Architect
Pós-graduado em arquitetura de software e soluções. Conecto profundidade técnica com resultados de negócio para entregar produtos que as pessoas realmente usam. Também mentoro desenvolvedores e criadores em programas ao vivo, podcasts e iniciativas de comunidade focadas em tecnologia inclusiva.
Produtos gratuitos e pagos para transformar ideias em uma base que você consegue executar.
11 produtos disponíveisContinue explorando tópicos similares

A production-grade system design for building distributed rate limiting across APIs and microservices, covering algorithms, token state storage, global consistency trade-offs, per-tenant quotas, adapt

A comprehensive system design guide for building a payment processing platform like Stripe, handling millions of transactions with exactly-once semantics, double-entry ledger, idempotency, fraud detec

Um guia prático e senior para desenhar um motor de busca em escala de internet, cobrindo crawler frontier, robots.txt, sitemaps, canonicalização, deduplicação, índice invertido, ranking, snippets.
Checklist de 47 pontos para encontrar bugs, riscos de segurança e problemas de performance antes do lançamento.
Templates testados em produção, usados por desenvolvedores. Economize semanas de setup no seu próximo projeto.

A user opens an app for 15 seconds while waiting for coffee. In those seconds, the system must decide which content to show first, which products to rank, which creators to highlight, and which exploration opportunities are worth spending impressions on.
One wrong recommendation costs almost nothing.
One million wrong recommendations per minute reshape retention, revenue, creator distribution, and trust.
Recommendation systems are not a single model problem. They are end-to-end systems problems:
In interviews, many candidates over-focus on model types and under-focus on architecture. Senior candidates treat recommendation as a distributed system with machine learning components, strict SLOs, and operational guardrails.
This guide follows that senior path.
A recommendation system can be built for feed ranking, ecommerce discovery, ad ranking, video suggestions, or social graph suggestions. This guide uses a generalized architecture that applies to all of them.
| Requirement | Target | Why it matters |
|---|---|---|
| Recommendation API latency | < 120ms p99 | Product responsiveness and engagement |
| Availability | 99.99% serving path | Feeds/search rely on recs continuously |
| Freshness | interaction impact within seconds to minutes | stale personalization hurts quality |
| Throughput | millions of requests/sec in peak systems | internet-scale requirement |
| Consistency | eventual for most features, strong for config and policy | model systems favor throughput with explicit controls |
| Reliability | graceful degradation on model/index outages | avoid blank pages and hard failures |
System should optimize a portfolio of metrics, not one scalar:
For this design we assume:
These estimates drive architecture decisions.
DAU: 400 million
Recommendation requests/day: 120 billion
Avg recommendations returned per request: 20
Candidate pool per request before ranking: 2,000
Item catalog size: 1.5 billion active items
User events/day: 2.8 trillion interactions
Peak multiplier: 5x
Req/sec avg = 120,000,000,000 / 86,400 ~= 1,388,889
Req/sec peak (5x) ~= 6,944,445
If ranking 2,000 candidates/request naively:
6.94M req/sec * 2,000 candidates ~= 13.9 billion item scores/sec
This is expensive. Hence multi-stage architecture:
2.8T events/day ~= 32.4M events/sec average
Peak (3x) ~= 97M events/sec
This demands partitioned streaming architecture and careful schema governance.
Assume 200 bytes/event compressed average for logged interactions.
2.8T * 200B ~= 560TB/day raw logical
with compression and tiering still massive
Hence strong sampling policies, retention tiers, and feature materialization are required.
Recommendation systems are dominated by:
Design API around ranking intent and context quality.
POST /v1/recommendations
Request:
{
"request_id": "req_2381",
"user_id": "u_991",
"surface": "HOME_FEED",
"context": {
"device": "ios",
"locale": "pt-BR",
"timezone": "America/Sao_Paulo",
"network_type": "wifi"
},
"session": {
"session_id": "s_882",
"entry_point": "app_open"
},
"constraints": {
"max_items": 20,
"allow_sensitive": false,
"diversity_level": "medium"
},
"debug": false
}
Response:
{
"request_id": "req_2381",
"model_version": "ranker_v278",
"items": [
{
"item_id": "i_101",
"score": 0.9281,
"reason_codes": ["similar_interest", "fresh_content"],
"rank": 1
}
],
"served_at": "2026-02-22T23:40:10Z",
"fallback_used": false,
"trace_id": "tr_5502"
}
POST /v1/recommendations/events
{
"event_id": "evt_901",
"request_id": "req_2381",
"user_id": "u_991",
"item_id": "i_101",
"event_type": "CLICK",
"position": 1,
"surface": "HOME_FEED",
"event_ts": "2026-02-22T23:40:21Z"
}
Use dedupe key:
dedupe_key = (event_id) or (request_id, user_id, item_id, event_type, event_ts_bucket)
Recommendation architecture relies on multiple data shapes.
{
"user_id": "u_991",
"embedding": [0.12, -0.44, 0.89],
"recent_topics": ["ml", "system-design", "cloud"],
"activity_1d": {
"views": 52,
"clicks": 13,
"likes": 2
},
"quality_signals": {
"session_depth_avg_7d": 8.2,
"negative_feedback_ratio": 0.07
},
"updated_at": "2026-02-22T23:31:01Z"
}
{
"item_id": "i_101",
"creator_id": "c_55",
"embedding": [0.02, 0.88, -0.31],
"tags": ["distributed-systems", "architecture"],
"freshness_hours": 3,
"quality_score": 0.82,
"policy": {
"eligible_surfaces": ["HOME_FEED", "DISCOVER"],
"sensitivity_level": "LOW"
},
"updated_at": "2026-02-22T23:29:44Z"
}
CREATE TABLE experiment_assignments (
experiment_id VARCHAR(64) NOT NULL,
user_id BIGINT NOT NULL,
variant VARCHAR(32) NOT NULL,
assigned_at TIMESTAMP NOT NULL,
PRIMARY KEY (experiment_id, user_id)
);
Ranking every item is impossible. Candidate generation narrows search space.
Combine multiple candidate sets and deduplicate.
final_candidates = unique(
topK(collab, 500)
U topK(embedding, 600)
U topK(trending, 200)
U topK(business, 100)
)
For new users:
For new items:
Embedding retrieval is usually the largest latency-sensitive component.
| Mode | Pros | Cons | Use |
|---|---|---|---|
| Full rebuild daily | simple consistency | stale during day | low freshness surfaces |
| Incremental updates hourly | better freshness | complexity | default |
| near-real-time updates | freshest | expensive and complex | hot surfaces |
Total budget: 120ms
- API + orchestration: 15ms
- retrieval calls: 30ms
- feature fetch: 25ms
- rank + rerank: 35ms
- serialization/network: 15ms
Ranking predicts user-item utility under constraints.
{
"user_id": "u_991",
"surface": "HOME_FEED",
"candidate_ids": ["i_101", "i_102"],
"feature_refs": {
"online_snapshot_id": "ofs_788"
},
"model_version": "ranker_v278"
}
Common constraints:
Optimizing a single short-term metric can hurt long-term retention and ecosystem health. Always include guardrail metrics.
Feature consistency is one of the hardest practical problems.
During training, never join future features accidentally.
Bad:
Good:
feature_name: user_click_rate_7d
entity: user_id
logic: clicks_7d / impressions_7d
source: interaction_events
update_mode: streaming
online_ttl: 10m
offline_backfill: daily
Fresh events are essential for personalization quality.
High-impact signals should reach online features in seconds, not hours.
Pure exploitation creates filter bubbles and long-term stagnation.
maximize expected_utility(items)
subject to:
- policy_eligible(item) == true
- creator_repeat_cap <= threshold
- min_diversity_score >= threshold
- sponsored_slots <= configured_limit
Start with deterministic ranker + lightweight controlled exploration. Increase sophistication only after observability and safeguards mature.
| Approach | Pros | Cons |
|---|---|---|
| no exploration | stable short-term metrics | long-term stagnation |
| aggressive exploration | learning speed | immediate metric volatility |
| controlled exploration | balanced | requires experimentation discipline |
Recommendation systems influence the data they train on.
{
"model_name": "ranker_v278",
"training_data_window": "2026-01-20..2026-02-18",
"feature_set_version": "fs_v91",
"offline_metrics": {
"auc": 0.812,
"ndcg_20": 0.442,
"coverage_1k": 0.71
},
"guardrails": {
"creator_gini_max": 0.82,
"latency_p99_ms_max": 40
}
}
Model promotion should require both metric gains and guardrail compliance.
Recommendation failures should degrade quality, not availability.
Maintain short-lived per-user cached results and longer-lived context fallback caches.
Never return empty list unless policy requires it. Empty surfaces usually destroy UX.
Model quality depends on data and deployment discipline.
Every model artifact should link to:
Recommendation changes require controlled measurement.
Primary metric depends on surface:
Guardrails:
{
"experiment_id": "exp_ranker_278",
"user_id": "u_991",
"variant": "B",
"assigned_at": "2026-02-22T23:35:00Z"
}
Serving performance depends on smart partitioning and caching.
rec:user:{user_id}:surface:{surface}
rec:context:{locale}:{surface}:{hour_bucket}
features:user:{user_id}
features:item:{item_id}
model:config:{surface}
| Store | Suggested Shard Key |
|---|---|
| user profiles/features | hash(user_id) |
| item features | hash(item_id) |
| ANN index shards | partition by item vector space + hash |
| event stream topics | user_id or session_id depending consumption pattern |
Recommendation serving is global and latency-sensitive.
Recommendation systems process sensitive behavioral data.
Mitigation requires anomaly detection and trust-weighted signals.
SLOs must include both system and model health.
| Domain | SLI | SLO |
|---|---|---|
| Recommendation API | p99 latency | < 120ms |
| Serving availability | success rate | > 99.99% |
| Event ingestion | accepted event rate | > 99.95% |
| Feature freshness | lag p95 | < 60s (critical features) |
| Model inference | timeout/error rate | within error budget |
| Recommendation quality | online KPI delta vs baseline | non-negative in guardrail windows |
System signals:
Model signals:
x-request-id
x-user-id
x-surface
x-model-version
x-experiment-variant
| Decision | Option A | Option B | Recommended |
|---|---|---|---|
| ranking depth | heavy model on all candidates | multi-stage ranking | multi-stage ranking |
| feature updates | batch only | hybrid batch+streaming | hybrid |
| exploration | none | controlled exploration | controlled exploration |
| serving strategy | personalized only | personalized + robust fallback | dual path |
| regional strategy | single global cluster | regional serving clusters | regional clusters |
If asked "design a recommendation system":
Problem: impossible compute and latency profile.
Fix: use candidate generation + retrieval to shrink search space first.
Problem: offline gains do not reproduce online.
Fix: versioned feature definitions and point-in-time training joins.
Problem: model/index incident causes blank recommendation surfaces.
Fix: layered fallback hierarchy with tested degradation modes.
Problem: short-term click gains but long-term retention and ecosystem damage.
Fix: multi-objective optimization with guardrail metrics.
Problem: recommendation entropy collapses; discovery quality declines.
Fix: controlled exploration budget and diversity constraints.
Problem: silent model quality decay in production.
Fix: monitor feature, score, and outcome drift continuously.
Problem: false wins and unstable rollouts.
Fix: robust experimentation framework with causal safeguards.
Recommendation systems at scale are distributed systems with ML intelligence, not ML scripts wrapped in APIs.
The stable architecture pattern is:
If you can explain this architecture with clear trade-offs, you can deliver strong system design interviews and build recommendation platforms that are fast, resilient, and responsible.
| Layer | Responsibility |
|---|---|
| Candidate Generation | broad personalized candidate sets |
| Retrieval (ANN) | nearest-neighbor candidate narrowing |
| Ranking | utility prediction and ordering |
| Re-ranking | diversity, policy, and business constraints |
| Feature Stores | online/offline feature consistency |
| Event Pipeline | real-time feedback ingestion |
| Experimentation | causal measurement and rollout control |
| Fallback | graceful degradation and availability protection |
request -> retrieval -> ranking -> reranking -> response
\-> fallback when degraded
1) Scope and objective: define surface + success metrics.
2) Scale: estimate QPS and score compute constraints.
3) Architecture: candidate gen -> retrieval -> ranking -> reranking.
4) Data plane: online/offline feature stores + realtime events.
5) Reliability: fallback hierarchy, circuit breakers, multi-region serving.
6) Governance: experimentation, drift monitoring, fairness/privacy controls.
You now have a production-grade blueprint for recommendation system design with practical architecture decisions and interview-ready trade-off framing.