# Gorse Learning Note

> This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to [original Chinese version](<https://blog.wendain.ing/posts/gorse-learning/>). I am continuously working to improve the translation.

> Reference materials:
>
> [Getting Started with the Gorse Recommender System: Building a Recommendation Engine from Zero to One - Tech Roaming - cnblogs](https://www.cnblogs.com/wanber/p/19451225)
>
> [gorse-io/gorse | DeepWiki](https://deepwiki.com/gorse-io/gorse/1-overview)
>
> [Homepage | Gorse](https://gorse.io/zh/)

## Getting Started

### What is a Recommender System

Three elements:

- Record behavior
- Understand interests
- Predict possible likes

### Startup and Usage

You can start it directly with `docker` (see the official documentation).

It is web-based; visit `localhost:8088` directly to browse.

Use `curl` to insert data, create items, insert feedback, get recommendations, and so on.

### Overview of the Core Working Principles

Four core concepts:

- User
    - Basic info: ID, labels, etc. (e.g., age, gender)
    - Behavioral history: browsing, clicks, purchases...
- Item
    - Basic info: ID, labels
    - Statistics: popularity, ratings
- Feedback
    - User + Item + Type + Time
- Recommendation
    - Predict items the user may like based on historical behavior

Flow diagram:

1. The user performs an action
2. The system records feedback
3. Models periodically perform analysis and training
4. Recommendations are generated
5. The user sees the recommendations
6. The loop iterates, back to 1

Gorse's recommendation strategy: **multi-source fusion**.

1. **Collaborative filtering**: find similar users and recommend the items they like
2. **Item similarity**: recommend other items similar to the user's historical items
3. **Popular recommendations**: recommend the most popular items
4. **Latest recommendations**: literally what it says

The so-called fusion strategy: recommendation results = 30% collaborative filtering + 30% item similarity + 20% popular recommendations + 20% latest recommendations

### Gorse's Architecture Design

A three-tier architecture:

```mermaid
flowchart TD
    A["用户 / 应用<br/>Web · App · 小程序"]
    B["Server 节点<br/>RESTful API + 实时推荐"]
    C["Master 节点<br/>模型训练 + 任务调度 + Dashboard"]
    D["Worker 节点（多个）<br/>离线计算 + 批量推荐"]
    E["存储层<br/>MySQL + Redis<br/>用户数据 + 物品数据 + 推荐缓存"]

    A -->|HTTP / HTTPS| B
    B -->|gRPC| C
    C -->|gRPC| D
    D --> E
```

> [!note]
>
> About **gRPC**
>
> **RPC** = Remote Procedure Call. The core idea is "calling a function on another machine as if it were a local function call".
>
> **gRPC** = an open-source RPC framework from Google.
>
> **Protobuf** = the data description and serialization format commonly used by gRPC. You write a `.proto` file defining "what functions exist, what the parameters are, and what the return values are".
>
> For example, in the Gorse architecture:
>
> ```TEXT
> Server  ──gRPC──>  Master
> Master  ──gRPC──>  Worker
> ```
>
> Suppose the Master provides a function:
>
> ```go
> GetModel(name string) Model
> ```
>
> The Server wants to call it. But the problem is: **the Master and Server are two separate processes, possibly even running on different machines**, so the Server obviously cannot directly do:
>
> ```go
> model := master.GetModel("ranking")
> ```
>
> What gRPC does is make this kind of **remote call look just like a normal function call**:
>
> ```go
> model, err := client.GetModel(ctx, request)
> ```
>
> What actually happens behind the scenes is:
>
> ```text
> Server
>   │
>   │ calls GetModel(...)
>   ↓
> gRPC Client
>   │
>   │ serializes into Protobuf
>   │ sends over HTTP/2
>   ↓
> Network
>   ↓
> gRPC Server on the Master
>   │
>   │ deserializes
>   ↓
> Actually executes GetModel(...)
> ```

#### Master Node

Can be understood as the brain of the Gorse architecture.

- Model training
- AutoML: Automated Machine Learning
- Task scheduling, triggering Workers
- Dashboard: monitoring, data management

#### Worker Node

Think of it as the hands and feet of the Gorse architecture.

- Batch recommendation: generate recommendation lists for each user
- Similarity computation: compute similarity between items, and similarity between users
- Horizontal scaling: start multiple Workers, load balancing
- Parallel computation; each Worker handles a subset of users

#### Server Node

Think of it as the "mouth".

- Provides RESTful API
- Real-time recommendation
- Online updates
- Stateless

#### Putting It Together

```mermaid
flowchart LR
    A["用户行为"] --> B["Server"]
    B --> C["DataStore<br/>MySQL"]

    C --> D["Master<br/>定期加载数据"]
    D --> E["训练模型"]

    E --> F["Worker<br/>计算推荐"]
    F --> G["CacheStore<br/>Redis"]

    G --> H["Server"]
    H --> I["返回用户"]

    %% 局部调整布局
    subgraph Train[" "]
        direction TB
        D --> E
    end

    subgraph Recommend[" "]
        direction TB
        F --> G
    end
```

## Understanding Gorse's Pipeline

[Pipeline | Gorse](https://gorse.io/zh/docs/concepts/pipeline.html)

```go
type Pipeline struct {
    Config       *config.Config            // 配置
    CacheClient  cache.Database            // Cache Store 客户端
    DataClient   data.Database             // Data Store 客户端
    Tracer       *monitor.Monitor          // 进度监控
    Jobs         int                       // 并行任务数
    
    // 推荐模型
    MatrixFactorizationItems *logics.MatrixFactorizationItems  // 物品向量索引
    MatrixFactorizationUsers *logics.MatrixFactorizationUsers  // 用户向量
    ClickThroughRateModel    ctr.FactorizationMachines        // CTR 预测模型
    
    dontskipColdStartUsers bool  // 是否跳过冷启动用户
}
```

<img src="https://image.wendaining.top/2543ba0dadfa669975c7cf48b4c197e7.png" style="zoom: 80%;" />

- After the data source enters the input layer, it is passed to the retrieval layer
- The retrieval layer consists of multiple recommenders that generate candidate items for the user
- The ranking layer merges all outputs from the different recommenders, removes items the user has already seen (read items), and scores the remaining items by the likelihood of the user interacting with them

The default pipeline only recommends the latest items.

### Caching in the Pipeline

The following intermediate results are cached and periodically updated:

- User neighbors from the user-to-user recommender.
    - Simply put, if user A's similar users are B, C, D, then this result is cached
- Item neighbors from the item-to-item recommender.
    - Same as above; similar items are cached
- Results from non-personalized recommenders.
    - Content not tied to a specific user, such as the latest list or the popular list
- Each user's ranker output
    - i.e., the final output of the ranker

### How Gorse Works

The pipeline executes in a **distributed** manner. Gorse has three types of nodes: master nodes, worker nodes, and server nodes — that is, the Master, Worker, and Server mentioned above; no need to repeat.

## A Deep Dive into the Gorse Recommender System: Data Structures and Storage Layer Design

[A Deep Dive into the Gorse Recommender System: Data Structures and Storage Layer Design - Tech Roaming - cnblogs](https://www.cnblogs.com/wanber/p/19451343)

I feel this is also the author's AI article rewritten... anyway, just skim it.

### String -> Index Mapping

Obviously we will have lots of JSON (or `map[string][]` in Go), with strings as keys.

Using strings as keys is inefficient (mainly because hash comparison costs $O(len(string))$

So we adopt a bidirectional `ID <-> 索引` mapping.

Specifically, use `FreqDict`:

```go
type FreqDict struct {
    idToIndex   map[string]int32   // ID → 索引
    indexToId   []string            // 索引 → ID
    frequencies []int               // 频率统计
}
```

The frequency statistics below can also be used, incidentally, to find the most active users.

### Dataset Sparse Matrix

To represent user-item interactions, using a 2D array like `matrix := make([][]bool, 1000000)` would be very wasteful.

Therefore, sparse storage is used:

```go
type Dataset struct {
    UserIndex    *FreqDict      // 用户字典
    ItemIndex    *FreqDict      // 物品字典
    UserFeedback [][]int32      // 用户 → 物品列表
    ItemFeedback [][]int32      // 物品 → 用户列表
}
```

Both directions are stored, trading space for time.

### Storage Layer

Gorse supports many databases, such as MySQL, PostgreSQL, MongoDB, Redis

The implementation creates a `Database` interface, and each database implements these interfaces.

According to [Configuration | Gorse](https://gorse.io/zh/docs/config.html),

[database]

| Key                  | Type   | Default        | Description                                    |
| -------------------- | ------ | -------------- | ---------------------------------------------- |
| `data_store`         | string |                | Database used for data storage.                |
| `cache_store`        | string |                | Database used for cache storage.               |
| `table_prefix`       | string |                | Naming convention for tables in the database.  |
| `cache_table_prefix` | string | `table_prefix` | Naming convention for tables in the cache store database. |
| `data_table_prefix`  | string | `table_prefix` | Naming convention for tables in the data store database. |

### DataStore and CacheStore

**DataStore**: stores "raw business data"

- User, Item, Feedback

**CacheStore**: stores "intermediate results computed by Gorse and recommendation results"

- The user's recommendation list
- Similar item lists

This way, the former uses a relational database, and the latter uses a NoSQL database like Redis.

### Other Performance Optimizations

#### Batch Loading

Instead of `get`-ting database objects one by one, batch query APIs are used; internally it reads from memory, reducing database I/O.

(This is basically the most core use case of Redis.)

#### Cursor Pagination

To understand cursor pagination, you first need to know what offset pagination is.

For example, suppose the table has 10,000 rows and we fetch 100 at a time.

```sql
SELECT * FROM feedbacks LIMIT 10000, 100;
-- 先找到前 10000 条，把它们全部跳过，再取后面的 100 条 --
```

Problem: although the first 10,000 rows are ultimately not needed, the database still has to process them.

Therefore, the further you paginate, the worse performance gets.

Using cursor pagination: after each query, record `last_id`; on the next query, use `WHERE id > last_id` to locate directly via the index.

#### Concurrency Control

Use read-write locks instead of one big lock.

I think this is common sense...

## Deep Dive into Collaborative Filtering Algorithms

This section is empty for now, because I don't have a solid machine learning foundation.

## Gorse's Distributed Architecture

First, some basic concepts and basic requirements:

**Why distribution is needed**:

1. Insufficient QPS (100 vs 10000)
2. Insufficient memory (32GB vs 100GB needed)
3. Single point of failure (if it goes down, everything goes down)

Scale Out (horizontal scaling):

```text
┌─────────┐      ┌─────────┐      ┌─────────┐
│ Server1 │  +   │ Server2 │  +   │ Server3 │
│ 100 QPS │      │ 100 QPS │      │ 100 QPS │
└─────────┘      └─────────┘      └─────────┘
```

Scale Up (vertical scaling)

```text
┌─────────┐      ┌───────────┐
│  32GB   │  →   │   128GB   │
│ 8 cores │      │ 32 cores  │
└─────────┘      └───────────┘
```

Distributed systems adopt Scale Out horizontal scaling.
### Overall Architecture

```mermaid
flowchart TD
    U["用户请求"]
    LB["Load Balancer<br/>Nginx / HAProxy"]

    U --> LB

    subgraph Servers["Server 集群 · 提供 API"]
        direction LR
        S1["Server1<br/>:8087"]
        S2["Server2<br/>:8087"]
        S3["Server3<br/>:8087"]
    end

    LB --> S1
    LB --> S2
    LB --> S3

    M["Master<br/>:8086<br/>训练模型 · 调度任务"]

    S1 -->|gRPC| M
    S2 -->|gRPC| M
    S3 -->|gRPC| M

    subgraph Workers["Worker 集群 · 计算推荐"]
        direction LR
        W1["Worker1<br/>:8089"]
        W2["Worker2<br/>:8090"]
        W3["Worker3<br/>:8091"]
    end

    M -->|gRPC| W1
    M -->|gRPC| W2
    M -->|gRPC| W3

    subgraph Storage["存储层"]
        direction LR
        DB["MySQL<br/>:3306"]
        R["Redis<br/>:6379"]
    end

    W1 --> DB
    W1 --> R
    W2 --> DB
    W2 --> R
    W3 --> DB
    W3 --> R
```

### Consistent Hashing

It's essentially a load balancing strategy.

For example, suppose the strategy for assigning a User to a Worker is:

```go
func getWorker(userId string) int {
    hash := crc32.ChecksumIEEE([]byte(userId))
    return int(hash) % numWorkers
}
```

But if we add a Worker, then obviously the Workers assigned to most existing Users change.

Therefore, we need to adopt **consistent hashing**.

The rough principle is a **hash ring**:

Imagine a huge numeric ring; here let's assume it's `0~99`.

We hash both Users and Workers; the hash function only yields numbers on the ring.

Suppose:

- hash(worker-A) = 20
- hash(worker-B) = 50
- hash(worker-C) = 80

And

- hash(Alice) = 30

The rule: **walk clockwise from the user's position; the first Worker encountered is the one responsible for this user**.

For example, Alice walks clockwise from 30, and the first one is Worker-B at 50.

When adding a Worker, only the segment where it is inserted into the hash is affected; the rest is unaffected — this is **consistent hashing**.

### Worker Coordination Mechanism

When a Worker starts, it actively connects to the Master, registers itself, syncs configuration, pulls models, and starts working.

The Master's task assignment:

- The Master periodically scans the database to get all users
- If there are new users, notify all workers about the new users
- Workers filter using hash values to get the users they need to handle
- Then compute in parallel to get recommendation lists

### Failure Handling

The Master periodically performs heartbeat checks `healthCheck()`

- If a Worker is down, remove it
- Then, consistent hashing reassigns (not handled in the check function), so this Worker's users are assigned to other Workers

### Server Horizontal Scaling

#### Stateless Design

Each Server connects to the cache Database, usually Redis.

Then, **the Server is stateless, as reflected in this request-handling function**:

```go
// 处理推荐请求
func (s *Server) GetRecommendations(userId string, n int) []string {
    // 1. 从缓存读取（无状态）
    recommendations := s.cacheClient.GetRecommendations(userId, n)
    
    if len(recommendations) >= n {
        return recommendations[:n]
    }
    
    // 2. 缓存未命中，实时计算
    return s.computeRecommendations(userId, n)
}
```

Why should the Server be stateless? Because a Server can go down at any time. If it were stateful and a user's Session was routed to a Server that then crashed, that user's Session would be lost.

But currently any modification is written directly to Redis, so a crash has no impact, and adding or removing Servers doesn't affect the service.

#### Load Balancing

Nginx is used.

### Data Consistency Guarantees

#### Eventual Consistency / Cache-Aside Strategy / Cache Update Problem

*It's basically that MySQL is slow while Redis is fast*. (Not accurate; see the LLM explanation below.) Sometimes a recommendation may be read from the database, but by then the database has already started writing new data, so the user first gets recommendations based on old data, and the new data is updated in later.

Solution: **fast path + slow path**

```go
// Server 端
func (s *Server) InsertFeedback(feedback Feedback) {
    // 1. 写入 MySQL（慢路径）
    s.dataClient.InsertFeedback(feedback)
    
    // 2. 快速更新：从推荐中移除已交互的
    s.cacheClient.RemoveFromRecommendation(
        feedback.UserId,
        feedback.ItemId,
    )
    
    // 3. 触发增量更新（可选）
    s.masterClient.TriggerIncrementalUpdate(feedback.UserId)
}
```

> It's normal that you didn't understand, because this article explains "data consistency" in a somewhat convoluted way, and the "fast update" doesn't first explain **why recommendation results need to be deleted**.
>
> First, grab a very concrete scenario.
>
> Suppose Redis already has recommendations computed for user A:
>
> ```text
> User A's recommendation list:
>
> [phone, earphones, keyboard, mouse]
> ```
>
> This recommendation result was computed **earlier** by the Worker and put into Redis.
>
> Now user A clicks "earphones".
>
> So the system receives a Feedback:
>
> ```text
> User=A
> Item=earphones
> Type=click
> ```
>
> Here comes the problem:
>
> Although MySQL will now record:
>
> ```text
> A has already clicked earphones
> ```
>
> The recommendation list in Redis is still the old one:
>
> ```text
> [phone, earphones, keyboard, mouse]
>         ↑
>       still here
> ```
>
> If the user immediately refreshes the recommendation page, they might see "earphones" again.
>
> That's odd:
>
> > I just clicked on it, why is it still being recommended to me?
>
> So the code in the article:
>
> ```go
> s.cacheClient.RemoveFromRecommendation(
>     feedback.UserId,
>     feedback.ItemId,
> )
> ```
>
> The meaning is very simple:
>
> > **If the user just interacted with an Item, immediately remove that Item from their currently cached recommendation list.**
>
> That is:
>
> ```text
> Original Redis:
>
> A → [phone, earphones, keyboard, mouse]
>              ↑
>            clicked
>
>
> Immediately becomes:
>
> A → [phone, keyboard, mouse]
> ```
>
> This is what's called:
>
> > **Fast update: remove already-interacted items from recommendations**
>
> It does not "recompute recommendations".
>
> It just makes a particularly cheap little patch:
>
> ```text
> The user has already seen/clicked this
> ↓
> Don't recommend it for now
> ```
>
> ------
>
> Why is it called the "fast path"?
>
> Because actually recomputing recommendations can be slow.
>
> Suppose after the user clicks earphones, we want **completely up-to-date** recommendations:
>
> ```text
> User clicks earphones
>     ↓
> Write Feedback
>     ↓
> Re-read user behavior
>     ↓
> Re-run the recommendation algorithm
>     ↓
> Re-rank
>     ↓
> Generate a new Top N
>     ↓
> Write to Redis
> ```
>
> This process can be heavy.
>
> You can't ask the user:
>
> > "Please wait, let me re-run the recommendation algorithm first, then refresh the page for you."
>
> So a compromise is adopted:
>
> ```text
>               User clicks earphones
>                    ↓
>           Write Feedback to the database
>                    ↓
>           ┌────────┴────────┐
>           ↓                 ↓
>        Fast path          Slow path
>
> Immediately remove earphones    Recompute recommendations
> from Redis                      in the background
>      ↓                    ↓
> Almost immediate            May complete a bit later
> ```
>
> This is what the article calls:
>
> > **Fast path + slow path**
>
> More concretely.
>
> Fast path:
>
> ```go
> RemoveFromRecommendation(user, item)
> ```
>
> It only does:
>
> ```text
> [phone, earphones, keyboard]
>        ↓ delete
> [phone, keyboard]
> ```
>
> Very fast.
>
> Slow path:
>
> ```text
> Based on the latest Feedback,
> recompute:
>
> What does A like now?
> ↓
> Regenerate the recommendation list
> ↓
> [phone case, Bluetooth speaker, keyboard, ...]
> ```
>
> Eventually the new recommendation results overwrite Redis.
>
> ------
>
> So you can understand the whole mechanism as:
>
> > **First "stop the bleeding", then "thorough treatment".**
>
> The user just clicked earphones:
>
> Do immediately
>
> ```text
> Stop showing him earphones.
> ```
>
> Slowly do in the background
>
> ```text
> Since he just clicked earphones,
> shouldn't I recommend more
> Bluetooth earphones, speakers, phone accessories?
>
> Recompute.
> ```
>
> ------
>
> Also, I think this sentence in the article you pasted:
>
> > "It's basically that MySQL is slow while Redis is fast."
>
> **is not particularly accurate.**
>
> The real problem is not mainly:
>
> ```text
> MySQL slow
> Redis fast
> ```
>
> but rather:
>
> > **The raw data has changed, but the recommendation results in the cache were still computed from the old data.**
>
> This is a typical case of:
>
> ```text
> Fact in the database          Computed result in Redis
>
> A clicked earphones     ←→     Still recommending earphones
>    new                          old
> ```
>
> The two sides are temporarily inconsistent.
>
> Even if MySQL were extremely fast, this problem would still exist.
>
> Because the recommendation results themselves are usually:
>
> ```text
> Old Feedback
>     ↓
> Worker computation
>     ↓
> Redis recommendation list
> ```
>
> After new Feedback appears, the Worker doesn't necessarily recompute instantly.
>
> So the real problem is:
>
> > **The recommendation cache is lagging.**
>
> ------
>
> Now looking at the three-step code you pasted becomes very easy:
>
> ```go
> func (s *Server) InsertFeedback(feedback Feedback) {
> ```
>
> The user performs an action, for example:
>
> ```text
> A clicks earphones
> ```
>
> Step one:
>
> ```go
> s.dataClient.InsertFeedback(feedback)
> ```
>
> Permanently save:
>
> ```text
> MySQL:
>
> A has clicked earphones
> ```
>
> This is factual data.
>
> Step two:
>
> ```go
> s.cacheClient.RemoveFromRecommendation(
>     feedback.UserId,
>     feedback.ItemId,
> )
> ```
>
> Immediately patch the old cache:
>
> ```text
> Redis:
>
> A → [phone, earphones, keyboard]
>              ↓
>            delete
>
> A → [phone, keyboard]
> ```
>
> Step three:
>
> ```go
> s.masterClient.TriggerIncrementalUpdate(feedback.UserId)
> ```
>
> The meaning can be roughly understood as:
>
> > "A's behavior has changed; when you have time, recompute A's recommendations."
>
> Afterwards it might generate:
>
> ```text
> A →
> [Bluetooth speaker, phone case, keyboard, charger]
> ```
>
> So:
>
> ```text
> Immediately:
> remove already-interacted Items
>
> Later:
> generate the truly updated recommendation list
> ```
>
> That's the whole idea.
>
> For interview purposes, remembering the following sentence is enough:
>
> > **Gorse's recommendation results are precomputed and cached, so after a user generates new Feedback, the cached recommendations may be temporarily stale. You can first quickly remove Items the user has already interacted with from the cache to avoid duplicate recommendations; afterwards, a background task recomputes the recommendation results based on the latest behavior.**
>
> This explanation is far more accurate than "because MySQL is slow and Redis is fast".

#### Cache Penetration Protection

Cache penetration refers to data requested by the client existing in neither the cache nor the database, so the cache never takes effect (only when the database finds data will it be cached in Redis, but the problem is nothing is found), causing frequent database access.

Gorse's solution: a Bloom filter.

> [!note]
>
> A Bloom filter actually uses hashing to solve this problem: through a large binary array, it uses hashing to determine whether the data being queried exists. If the Bloom filter judges it exists, the request is allowed through and will access Redis; even if the data in Redis has expired at that moment, the data definitely exists in the database, and after querying it from the database, it is put back into Redis. If the Bloom filter judges the data doesn't exist, it returns directly. The advantage of this approach is saving memory space, but there can be false positives, because the Bloom filter uses hashing, and any hashing approach can have hash collisions

```go
// 问题：恶意请求大量不存在的用户
func (s *Server) GetRecommendations(userId string) []string {
    // 缓存未命中
    recs := s.cache.Get(userId)
    if recs == nil {
        // ❌ 每次都计算，压垮系统
        recs = s.compute(userId)
    }
    return recs
}

// 解决：布隆过滤器
type Server struct {
    bloomFilter *BloomFilter
}

func (s *Server) GetRecommendations(userId string) []string {
    // 1. 快速检查用户是否存在
    if !s.bloomFilter.Contains(userId) {
        return []string{}  // 用户不存在，直接返回
    }
    
    // 2. 查询缓存
    recs := s.cache.Get(userId)
    if recs == nil {
        recs = s.compute(userId)
    }
    return recs
}
```

#### Cache Avalanche

Cache avalanche refers to a large number of cache keys expiring at the same time, or the Redis service going down, causing a large number of requests to hit the database and bringing enormous pressure.

Gorse's solution: set random expiration times:

```go
// 问题：大量缓存同时过期
func (s *Server) SetRecommendations(userId string, recs []string) {
    // ❌ 所有缓存都是 1 小时过期
    s.cache.Set(userId, recs, 1*time.Hour)
}

// 解决：随机过期时间
func (s *Server) SetRecommendations(userId string, recs []string) {
    // 1 小时 ± 5 分钟
    ttl := time.Hour + time.Duration(rand.Intn(600))*time.Second
    s.cache.Set(userId, recs, ttl)
}
```

> Solutions to cache avalanche, excerpted from [Redis in Practice | Kyle's Blog](https://cyborg2077.github.io/2022/10/22/RedisPractice/#缓存更新策略)
>
> - Add random values to the TTLs of different Keys so they expire in batches at different times
> - Use a Redis cluster to improve service availability (a system composed of one or more `Sentinel` instances monitors Redis nodes; when the master node fails, one of the slave nodes can be promoted to master for failover, ensuring system availability.)
> - Add degradation and rate-limiting strategies to cached services
> - Add multi-level caching to the service (when the browser accesses static resources, it reads the browser's local cache first; when accessing non-static resources (ajax data queries), it accesses the server; after the request reaches Nginx, it reads the Nginx local cache first; if the Nginx local cache misses, it queries Redis directly (bypassing Tomcat); if the Redis query misses, it queries Tomcat; after the request enters Tomcat, it queries the JVM process cache first; if the JVM process cache misses, it queries the database)

### Fault Tolerance and High Availability

- **Fault tolerance**: when part of the system fails, the whole can keep working, rather than everything crashing because of one problem.
- **High availability**: the system tries to keep serving externally as much as possible, even if some internal components are temporarily faulty.
- **Service degradation**: when normal functionality can't be delivered, fall back to a "not as good but still usable" result. For example, if personalized recommendation fails, return popular items.
- **Fallback**: the backup result actually returned during degradation. For example, popular recommendations, default recommendations.
- **Circuit breaker**: after a downstream service fails consecutively many times, the system temporarily stops requesting it, avoiding a large number of continuously failing requests dragging down the whole system.
- **Closed**: the circuit breaker's normal state; requests pass through normally.
- **Open**: the downstream is found to be failing frequently, so requests to it are temporarily blocked.
- **Half-Open**: after a while, let a few requests through to test; if they succeed, recover; if they fail, keep the breaker open.

#### Service Degradation

For example, the rough code logic of the Server fetching recommendations is:

1. Try to get from cache
2. If it fails, compute in real time
3. If real-time computation fails, fall back to fetching pre-cached popular recommendations

```go
type Server struct {
    circuitBreaker *CircuitBreaker
}

func (s *Server) GetRecommendations(userId string) []string {
    // 1. 尝试从缓存获取
    recs, err := s.cache.Get(userId)
    if err == nil {
        return recs
    }
    
    // 2. 缓存失败，尝试实时计算
    if s.circuitBreaker.Allow() {
        recs, err = s.computeRealtime(userId)
        if err == nil {
            return recs
        }
        s.circuitBreaker.RecordFailure()
    }
    
    // 3. 实时计算失败，降级到热门推荐
    return s.getFallbackRecommendations()
}

// 降级策略
func (s *Server) getFallbackRecommendations() []string {
    // 返回热门物品（预先缓存）
    return s.cache.Get("popular_items")
}
```

#### Circuit Breaker

It feels like just opening and closing a gate; after closing, there's still a check, and if the check fails it stays closed — there's a half-open intermediate state.

```go
type CircuitBreaker struct {
    state          State  // Open/Closed/HalfOpen
    failureCount   int
    successCount   int
    failureThreshold int
    timeout        time.Duration
    lastFailTime   time.Time
}

func (cb *CircuitBreaker) Allow() bool {
    switch cb.state {
    case StateClosed:
        return true  // 正常状态，允许请求
        
    case StateOpen:
        // 熔断状态，检查是否到恢复时间
        if time.Since(cb.lastFailTime) > cb.timeout {
            cb.state = StateHalfOpen
            return true  // 尝试恢复
        }
        return false  // 拒绝请求
        
    case StateHalfOpen:
        return true  // 半开状态，允许部分请求
    }
}

func (cb *CircuitBreaker) RecordFailure() {
    cb.failureCount++
    cb.lastFailTime = time.Now()
    
    if cb.failureCount >= cb.failureThreshold {
        cb.state = StateOpen  // 打开熔断器
    }
}

func (cb *CircuitBreaker) RecordSuccess() {
    if cb.state == StateHalfOpen {
        cb.successCount++
        if cb.successCount >= 3 {
            cb.state = StateClosed  // 关闭熔断器，恢复正常
            cb.failureCount = 0
        }
    }
}
```

### Setting Up a Distributed Cluster

Mainly configured in `docker-compose.yml`.

Of course, if you need flexible scaling, you'll need k8s.

This part will be discussed separately later.

### Summary

✅ **Distributed design**

- Master/Worker/Server three-tier architecture
- Each tier scales independently
- Stateless design

✅ **Load balancing**

- Consistent hashing
- Virtual nodes
- Minimized data migration

✅ **High availability**

- Service degradation
- Circuit breaker
- Automatic failure recovery

✅ **Data consistency**

- Eventual consistency
- Fast path + slow path
- Cache protection

## Gorse Server Working Principles in Detail

### The Server's Position in the Architecture

- User requests come into the Server (**a stateless service**)
- The Server's results are cached to Redis; synced to the Master via gRPC

### The Server's Responsibilities

- Provides RESTful API externally
- Reads precomputed cached results from Redis
- Periodically syncs configuration and database connection info from the Master
### code

- Create the Server instance in `main.go`
- Perform initialization in `server.go`
    - Stateless
    - Does not connect to the database initially; waits to get configuration from the Master
    - Only needs to know the Master's address (actually address + port)
- Start the service in `server.go`, connect to the master via gRPC, use `go s.Sync()` to start a goroutine for syncing, and finally start the HTTP server
    - `Sync()` runs an infinite loop, requesting metadata from the Master and parsing it
        - If the configuration has changed, connect to the new Data Store / Cache Store
    - Sleeps for a while, then continues the loop after waking up
- Handle the RESTful API in `rest.go`; after registration, the concrete logic is just a bunch of CRUD operations.

Walking through the complete flow:

1. The user sends a request, e.g. `GET /api/recommend/user123?n=10`
2. The Server's HTTP Handler receives the request and processes it:
    1. Parse the request to get the parameters
    2. Read the recommendation cache from Redis
    3. If the cache hits, **filter out already-consumed items**
    4. If the quantity is insufficient, apply the fallback strategy (random recommendations, etc.)
    5. Return the JSON response

Three key characteristics can be seen:

- Stateless: mainly for convenient load balancing
- Hot configuration updates
- Fallback strategy

### Key Points of Server Performance Optimization

#### Connection Pool

```go
// Redis 连接池
redisClient := redis.NewClient(&redis.Options{
    PoolSize:     100,      // 连接池大小
    MinIdleConns: 20,       // 最小空闲连接
    PoolTimeout:  4 * time.Second,
})

// MySQL 连接池
db.SetMaxOpenConns(100)     // 最大连接数
db.SetMaxIdleConns(20)      // 最大空闲连接
db.SetConnMaxLifetime(time.Hour)
```

Here we can see the two elements of a connection pool: **pool size** and **minimum idle connections**.

#### Caching Strategy

Expiration time: 72h

Update frequency: updated after the Worker recomputes

For hot data:

- Popular items: cached permanently
- New items: cached for 24h

#### Using Batch Operations

As mentioned before, it's just batch queries and batch loading.

## Gorse Worker Architecture in Detail

Gorse's recommendation computation engine.

Responsibilities:

- Sync configuration and models from the Master
- Generate offline recommendations
- Write to cache

### The Worker Struct

```go
type Worker struct {
	Pipeline
	testMode bool

	clickThroughRateModelId int64

	// worker config
	workerName string
	httpHost   string
	httpPort   int
	masterHost string
	masterPort int
	tlsConfig  *util.TLSConfig
	cacheFile  string

	// database connection path
	cachePath    string
	cachePrefix  string
	dataPath     string
	dataPrefix   string
	vectorPath   string
	vectorPrefix string

	blobConfig  string
	blobStore   blob.Store
	vectorStore vectors.Database

	// master connection
	conn         *grpc.ClientConn
	masterClient protocol.MasterClient

	latestCollaborativeFilteringModelId int64
	latestClickThroughRateModelId       int64
	randGenerator                       *rand.Rand

	// peers
	peers []string
	me    string

	// events
	tickDuration time.Duration
	ticker       *time.Ticker
	syncedChan   chan struct{} // meta synced events
	pulledChan   chan struct{} // model pulled events
	done         chan struct{}
	shutdown     sync.Once
	syncWait     sync.WaitGroup
	httpServer   *http.Server
}
```

There's quite a lot here, so let me pick a few fields I consider important:

- `Pipeline`, the same Pipeline described earlier; its core role is to **encapsulate the core logic of recommendation computation**

- Its own HTTP service address + port

- Master address and connection

- The list of Worker nodes and the current Worker's identifier in the cluster, **used for consistent hashing**

- Tickers and channels, used for communication between goroutines (Sync → Pull → Recommend)

    > A Ticker holds a channel that delivers "ticks" of a clock at intervals.

### Worker Startup

First the main function does the basic configuration, then starts `w.Serve()`.

And `w.Serve()`:

- First generates a unique name
- Creates a progress tracker
- Connects to the master via gRPC
- Starts the three major goroutines: Sync → Pull → Recommend
    - Sync is for syncing configuration
    - Pull is for pulling models
    - ServeHTTP is for, literally, that
- Defines the main loop `func loop()`: pull users, generate recommendations, report to the Master
- Then starts an infinite loop; if the channel contains a scheduled trigger / model-update trigger message, it calls `loop()`

### The Three Core Goroutines

#### Sync

Roughly executes:

An infinite loop:

- Fetch data from the Master and update
    - If there's something new, trigger a new connection update
- Detect model version updates
    - If there's a new one, trigger the `Pull()` goroutine
- Update cluster information for consistent hashing
- Wait (sleep for a while)

#### Pull

When a message from the Sync goroutine is received, the loop continues (`for range w.syncedChan`)

- Pull the model
- If there's a new model, notify the main loop via `w.pulledChan`

#### ServeHTTP

Provides Prometheus metrics and a health check API

> [!note]
>
> Prometheus is an **open-source monitoring and alerting system**.
>
> Prometheus metrics are "runtime status data" that a program deliberately exposes for Prometheus to collect.

Mainly used for checks inside k8s.

### User Recommendation Flow

#### `Pipeline.Recommend()` in Detail

```mermaid
flowchart TD
    A["开始推荐"] --> B["创建物品缓存"]
    B --> C["并行处理每个用户<br/>p.Jobs 个并发"]

    C --> D{"是否需要更新推荐？"}

    D -->|"不活跃"| SKIP["跳过该用户"]
    D -->|"缓存未过期"| SKIP
    D -->|"冷启动用户"| SKIP
    D -->|"需要更新"| E

    E["① 协同过滤推荐<br/>获取用户向量<br/>在物品向量索引中搜索 TopK<br/>写入 CollaborativeFiltering"]

    E --> F

    subgraph Candidate["② 生成候选集"]
        direction LR
        F["调用多个 Recommender"]
        F --> F1["ItemBased"]
        F --> F2["UserBased"]
        F --> F3["Latest"]
        F --> F4["Popular"]
        F --> F5["Custom"]
        F1 & F2 & F3 & F4 & F5 --> F6["合并 · 去重"]
    end

    F6 --> G["③ 过滤候选集<br/>过滤已删除物品<br/>过滤隐藏物品<br/>添加替换候选（用户历史）"]

    G --> H

    subgraph Ranking["④ Ranking"]
        direction LR
        H{"排序方式"}
        H --> H1["FM 模型<br/>CTR 预测"]
        H --> H2["LLM 排序<br/>ChatGPT"]
        H --> H3["不排序<br/>使用召回分数"]
    end

    H1 & H2 & H3 --> I["⑤ 应用替换衰减<br/>降低历史物品分数<br/>重新排序"]

    I --> J["⑥ 写入缓存<br/>cache.Recommend<br/>cache.RecommendUpdateTime<br/>cache.RecommendDigest"]

    J --> K["汇总所有用户"]
    SKIP --> K

    K --> L["上报 Metrics"]
    L --> M["结束"]
```

> [!note]
>
> This is essentially the Pipeline section from earlier, expanded.

#### Cache Expiration Strategy

1. Cache is empty
2. Configuration changed (digest mismatch)
3. Cache timed out (CacheExpire)
4. User has new behavior (activeTime > recommendTime)

### Load Balancing

Consistent hashing for assigning users is implemented in the Worker architecture.

Specifically, when assigning users, the consistent hashing assignment method described above is used.

### Interactions Among the Three Architectures

```mermaid
flowchart TD
    M["Master<br/>训练模型<br/>保存模型到 Blob Store<br/>提供配置、模型版本、Worker 列表<br/>接收 Worker 进度上报"]

    W["Worker<br/>同步配置和模型版本<br/>下载模型<br/>生成用户推荐<br/>写入 Cache Store"]

    C["Cache Store<br/>cache.Recommend<br/>cache.CollaborativeFiltering<br/>cache.RecommendUpdateTime"]

    S["Server<br/>提供推荐 API<br/>读取预计算推荐<br/>应用实时过滤和补充"]

    U["Client / User"]

    M -->|"gRPC · GetMeta()"| W
    W -->|"gRPC · PushProgress()"| M

    W -->|"写入推荐结果"| C
    C -->|"读取推荐结果"| S
    S -->|"HTTP API"| U
```

All interactions between the different architectures go through gRPC.

Workers and Servers **do not communicate directly**; they interact indirectly through the Cache Store.

## Interview-Oriented Part

Based on the resume wording provided by the LLM, conduct adversarial deep-dive questioning, aiming to be fully prepared and not get stumped.

### Redis / Cache Part

Actually, Gorse does not specifically handle the so-called cache breakdown, cache penetration, and cache avalanche problems the way Heima Dianping does.

> [!important]
>
> Which means, those cnblogs articles, and the parts of my notes based on them, are all nonsense,,,

But there's no way around it, so I gave the AI this prompt:

> However, I still need some Redis highlights, so here's what you should do next:
>
> 1. Search the internet for relevant excellent blogs / materials that specifically analyze and summarize Gorse's excellent design highlights in Redis / cache handling; if any exist, use them as the highlights written in our blog
> 2. If nothing is found, summarize it yourself based on the source code.

Then with detailed explanation + summarization, this result was obtained:

> **Cache architecture:** To address the high cost of computing recommendation results and the problem where traditional cache invalidation could transmit rebuild pressure to online requests, recommendation results are precomputed offline by the Worker and written to Redis, with logical invalidation and background refresh driven by user data update time, configuration digest, and cache expiration; combined with RediSearch to support filtering and sorting queries over recommendation results, balancing result freshness, computation cost, and online request latency.

But honestly I didn't quite understand it either, so I had the LLM explain this wording to me in detail.

#### First, Understand the Difference Between Recommendation Data and Ordinary Business Data

For ordinary business data, such as a User ID:

- API query
- If Redis misses, just query the database again

But recommendation data requires complex ML computation. For this, Gorse's approach is to have a background Worker continuously compute recommendations and store them in Redis, and then the Server reads from Redis to serve user requests.

> [!note]
>
> **What is Cache Aside?**
>
> Cache Aside (bypass cache) is the most common way of using "database + Redis".
>
> The core logic is simple:
>
> ```text
> Read request:
> Client
>   ↓
> Check Redis first
>   ↓
> Hit → return directly
> 
> Miss
>   ↓
> Query MySQL
>   ↓
> Write the result into Redis
>   ↓
> Return
> ```
>
> Write requests are usually:
>
> ```text
> Update MySQL first
>   ↓
> Then delete the Redis cache
> ```
>
> Why is it called **Aside**? Because the cache is not inside the database, nor is it automatically maintained by the database; instead, **the business code maintains Redis on the side itself**.
>
> For example, Heima Dianping querying a shop:
>
> ```text
> GET /shop/123
>    ↓
> Redis query shop:123
>    ↓
> Not found
>    ↓
> MySQL query shop(id=123)
>    ↓
> Write into Redis
>    ↓
> Return
> ```
>
> This is classic Cache Aside.
>
> Gorse's recommendation cache is quite different from this. Your notes have actually already summarized this difference: an ordinary cache is closer to "a copy of database data", while Gorse's recommendation list is **derived data** obtained after recommendation computation.
>
> So Gorse cannot simply do:
>
> ```text
> Redis miss
> → SELECT MySQL
> → Backfill Redis
> ```
>
> It's more like:
>
> ```text
> DataStore
>   ↓
> Recommendation computation
>   ↓
> Worker
>   ↓
> CacheStore / Redis
> ```
>
> This is also why Gorse's design approach to cache breakdown and avalanche differs a lot from typical Cache Aside systems like "Heima Dianping".

#### The Cache Breakdown Problem

Generally speaking, in projects using Redis like Heima Dianping, the cache breakdown problem is: after a hot key expires, all requests miss Redis and hit the database, causing a breakdown.

But for Gorse, after recommendation results become invalid, the Worker is not forced to recompute immediately; instead, the Server first returns the Fallback result, and the Worker recomputes in the background.

> [!note]
>
> Gorse does not use the traditional "mutex lock to prevent breakdown", but rather **offline precomputation + background refresh**, reducing the breakdown problem at the architectural level.

But how does the Worker know whether this cache should be recomputed? It is not triggered after the TTL of some Redis key expires.

In the Gorse source code, there is a `checkRecommendCacheOutOfDate()` function, which roughly checks logic like this:

- Whether the recommendation list is empty
- Whether the user's configuration has changed
    - Referring to whether the requested user has recently produced new behavior, e.g. new `click / like / favorite`
- Whether the time since the last recommendation computation has exceeded CacheExpire
- Whether the digest of the recommendation configuration has changed
    - The digest can be understood as the result of applying a hash function to the recommendation system's configuration
    - The recommendation system's configuration means things like `cache_size`

#### RediSearch-Related

So-called RediSearch: builds indexes over Redis Hash / JSON, supporting conditional filtering, sorting, full-text search, vector similarity, etc.

Its application in Gorse: a recommendation result is a document-like structure, containing things like:

```text
collection
subset
id
score
is_hidden
categories
timestamp
```

After establishing the User Key -> its K-V structure, a RediSearch index is created.

This way, when querying, you can filter with conditions like `userid=123 && category = tech` + sort by `score` descending and take the Top 20, which native Redis cannot do.

#### Balancing Result Freshness, Computation Cost, and Online Request Latency

- Requiring results to always be the freshest: enormous computation cost
- Low computation cost: results are not fresh
- Online real-time computation: high request latency

### Vector Recall

Original resume text:

> Vector recall: to address the problem that large-scale items cannot have their relevance computed one by one within online requests, unstructured features such as text are encoded into embeddings, and vector similarity retrieval is used to quickly recall semantically relevant candidate items, which are then passed to the subsequent ranking pipeline to generate the final result, so that vector retrieval is responsible for narrowing the candidate space rather than directly bearing the full recommendation decision.

What an Embedding is, I actually do know: it converts features into a high-dimensional vector.

So-called "recall": quickly find some similar items from a massive number of items based on Embedding similarity, forming a candidate set; subsequent computation is then performed on the relatively small candidate set.

The part about quickly finding similar items is done using a **vector database**.

The plain-language version of that resume part: there are too many items to take them all out and rank them every time; so first convert item content into vectors, use vector similarity to quickly filter out a small batch of possibly relevant content, and then do fine-grained ranking.

## The Grilling Part

I used this prompt:

> You are a technical interviewer responsible for **backend development internship / campus recruitment interviews**.
>
> I will give you:
>
> - My resume project descriptions;
> - Necessary project background;
> - Some project knowledge I may have organized in advance.
>
> Your task is not to give me questions, but to conduct a **project deep-dive / resume grilling** that is as close as possible to a real backend technical interview.
>
> ------
>
> I. The Most Important Principle
>
> 1. You cannot see my code
>
> You must always assume:
>
> **The interviewer only has my resume, and the information I tell you verbally during the interview.**
>
> Therefore, it is forbidden to ask questions targeting code details just because the background material I gave you contains code.
>
> Forbidden:
>
> - Asking how a certain function, class, or variable is written;
> - Asking why a certain line of code is written that way;
> - Asking about the implementation of a certain source file;
> - Pretending the interviewer already knows these implementations based on the code content I provided to the AI.
>
> However, follow-up questions about implementation mechanisms that a candidate should be able to explain in a normal interview are allowed, for example:
>
> - How data flows;
> - Why the Redis keys / data structures are designed this way;
> - How MQ messages are produced and consumed;
> - How idempotency is guaranteed;
> - How cache and database stay consistent;
> - How concurrency issues are handled;
> - Which modules a request passes through;
> - Why a certain solution adopted this implementation.
>
> Judgment criterion:
>
> > Would a real interviewer, based only on the resume and the candidate's verbal account, have reason to ask this question?
>
> If not, don't ask it.
>
> ------
>
> II. Ask Only One Question at a Time
>
> Strictly simulate a real interview.
>
> Each round, ask only **one main question**.
>
> Do not output at once:
>
> > 1. Why use Redis?
> > 2. How is the TTL set?
> > 3. How is consistency guaranteed?
> > 4. What if Redis goes down?
>
> The correct way is:
>
> > Why did you choose to use Redis here?
>
> Then wait for my answer.
>
> If I answer:
>
> > Because database queries are relatively slow, we cached the recommendation results in Redis.
>
> The next question should prioritize the follow-up:
>
> > Then when does this cache expire? How did you think about the TTL?
>
> Then continue following up based on my answers.
>
> ------
>
> III. Prioritize Follow-ups, Not Switching Topics
>
> This is the most important rule of the whole interview.
>
> Every time I answer, you first judge:
>
> > **Is there anything in this statement worth following up on?**
>
> If there is, in principle **prioritize the follow-up**; don't switch topics immediately.
>
> A single technical point can be followed up **3–5 layers deep, more if necessary**.
>
> For example:
>
> Me:
>
> > To reduce database pressure, we use Redis to cache recommendation results.
>
> You:
>
> > Why is this scenario suitable for caching?
>
> After I answer:
>
> > Then how is the cache invalidation strategy designed?
>
> Continue:
>
> > When updating recommendation results, how do you handle the database and the cache?
>
> Continue:
>
> > What if the database update succeeds but the cache update fails?
>
> Continue:
>
> > Then why do you accept eventual consistency in that case, rather than strong consistency?
>
> This is what a normal project deep-dive looks like.
>
> ------
>
> IV. Sources of Follow-ups
>
> Prioritize finding points to dig deeper from my previous sentence.
>
> Focus on:
>
> ### Technical Terms
>
> If I proactively mention:
>
> - Redis
> - MySQL
> - PostgreSQL
> - Kafka / RocketMQ
> - gRPC
> - RPC
> - Distributed locks
> - Consistent hashing
> - Bloom Filter
> - goroutine
> - channel
> - Elasticsearch
> - Docker
>
> These words can all become entry points for new follow-ups.
>
> But don't suddenly turn away from the project into a rote-recitation exam.
>
> For example, if I say:
>
> > Use Redis to cache user recommendation results.
>
> You can ask:
>
> > Why choose Redis here?
>
> You should not suddenly ask:
>
> > What are Redis's five basic data structures?
>
> Unless the question is genuinely relevant to the current discussion.
>
> ------
>
> My Cause-and-Effect Claims
>
> If I say:
>
> > Because of A, we use B.
>
> Prioritize attacking this causal relationship:
>
> - Why does A lead to B?
> - What happens if you don't use B?
> - Is B really the most suitable way to solve this problem?
> - Are there other solutions?
> - Why weren't other solutions chosen?
>
> ------
>
> My Technical Decisions
>
> If I say:
>
> > We use a message queue for asynchronous updates.
>
> You can continue:
>
> > Why is asynchrony needed here?
>
> Then:
>
> > If you don't use MQ, what's wrong with direct synchronous calls?
>
> Then:
>
> > What if the message is sent successfully but consumption fails?
>
> Then:
>
> > Won't retries cause duplicate consumption?
>
> Then:
>
> > Then how does your consumer guarantee idempotency?
>
> ------
>
> My Metrics
>
> If I say:
>
> > Performance improved by 50%.
>
> You must consider following up:
>
> > How was this 50% measured?
>
> If I say:
>
> > It can support high concurrency.
>
> You can follow up:
>
> > What is roughly the QPS you actually tested?
>
> If the numbers sound suspicious, keep asking.
>
> Do not default to accepting the numbers on the resume.
>
> ------
>
> My Vague Expressions
>
> For example:
>
> > Did some optimizations.
>
> Ask immediately:
>
> > What specifically was optimized?
>
> Or:
>
> > Improved system stability.
>
> Follow up:
>
> > What problems specifically occurred before, and what changed after you finished?
>
> ------
>
> V. Allow Natural Extension from the Project to Rote Fundamentals
>
> You may test computer science fundamentals, but there must be a natural path:
>
> **Project → Technology → Principle**
>
> For example:
>
> The project uses Redis
>
> → Why use Redis
>
> → Why is Redis fast
>
> → Memory access / IO multiplexing / data structures
>
> This is reasonable.
>
> Not:
>
> The project uses Redis
>
> → What are TCP's four-way handshake waves?
>
> This kind of jump should not appear.
>
> Likewise:
>
> MQ
>
> → Duplicate consumption
>
> → Idempotency
>
> → Database unique index / Redis / state machine
>
> Reasonable.
>
> MySQL
>
> → Slow queries
>
> → Indexes
>
> → B+ trees
>
> Reasonable.
>
> ------
>
> VI. Answers Must Fit a Real Interview
>
> My target answer time for each question is:
>
> **30–60 seconds.**
>
> Therefore, when evaluating answers, don't just judge "whether the knowledge is correct"; also judge:
>
> - Whether it can be finished within 30–60 seconds;
> - Whether it grabs the key points;
> - Whether it answers the question right away;
> - Whether it covers too much irrelevant background;
> - Whether it piles up technical jargon;
> - Whether it sounds like reciting a blog;
> - Whether the interviewer can naturally understand it.
>
> Do not require me to give textbook-style complete answers.
>
> The fact that a knowledge point could theoretically be explained in five minutes does not mean it should take five minutes in an interview.
>
> Prioritize training:
>
> > **Answer the core question in 30–60 seconds first, and leave the remaining details for the interviewer's follow-ups.**
>
> If my answer is clearly too long, note it down, but during the real interview do not immediately launch into a long lecture.
>
> You can briefly remind:
>
> > This answer is a bit long; in a real interview I'd suggest compressing it to under a minute.
>
> Then continue the interview.
>
> ------
>
> VII. Do Not Proactively Complete My Answers
>
> If my answer has gaps, do not immediately tell me the standard answer.
>
> For example:
>
> Me:
>
> > MQ can serve to smooth out traffic peaks.
>
> Do not immediately reply:
>
> > Right, and besides that there's decoupling, asynchrony...
>
> Instead, keep asking:
>
> > Why can it smooth peaks?
>
> Or:
>
> > But peak traffic still has to be processed by consumers in the end — what problem does MQ actually solve?
>
> What I want to train is being pressed by an interviewer, not having the AI lecture me.
>
> ------
>
> VIII. Proactively Look for "Attackable Points"
>
> Every answer of mine may contain:
>
> - Vague statements;
> - Missing data;
> - Insufficient causality;
> - Unclear technical choices;
> - Knowing conclusions but not reasons;
> - Things not actually done in the project;
> - Only having watched tutorials;
> - Over-packaged resume claims.
>
> Upon discovering these, prioritize continuing to press.
>
> For example:
>
> Me:
>
> > To ensure high availability, we use Redis.
>
> You can immediately follow up:
>
> > What if Redis itself goes down? What does "high availability" specifically mean here?
>
> ------
>
> IX. Scenario-Change Follow-ups
>
> When a technical point has been fully explained, you may appropriately change constraints and keep pressing.
>
> Common approaches in real backend interviews include:
>
> Traffic changes
>
> > What if QPS grows 10x?
>
> Component failure
>
> > What happens to the system after Redis goes down?
>
> Network anomalies
>
> > What if the MQ Broker is briefly unavailable?
>
> Data anomalies
>
> > What if messages are duplicated?
>
> Latency anomalies
>
> > The API used to take 50ms and suddenly takes 2s — how do you troubleshoot?
>
> Capacity changes
>
> > What if the data volume grows 100x?
>
> Counterfactuals
>
> > If you were to redesign it, would you still do it this way?
>
> But do not forcibly add ultra-large-scale scenarios unrelated to the project just to create difficulty.
>
> ------
>
> X. Project Ownership
>
> The key judgment:
>
> > **Is this project something I truly understand and actually participated in?**
>
> Therefore you should often ask:
>
> - Why was this module designed this way?
> - What was the initial symptom of this problem?
> - How did you locate it at the time?
> - Why was this solution ultimately adopted?
> - Did you try other methods along the way?
> - What was the biggest problem?
> - If you did it again, what would you change?
>
> For personal projects, do not force questions like:
>
> > How did your team divide the work?
>
> Instead ask:
>
> > Which part did you focus on modifying or researching in depth?
>
> ------
>
> XI. Do Not Obsess Over "Production Experience"
>
> If I am an internship / campus recruitment candidate, especially if the project is a personal or open-source project:
>
> Do not force me to fabricate:
>
> - Millions of QPS;
> - Real production incidents;
> - Large-scale online users;
> - Company-level SLAs.
>
> If there is no real production data, you can ask:
>
> > Have you done load testing?
>
> > If it hasn't launched, how do you judge that this design can solve the problem?
>
> > Has the benefit of this optimization been verified through benchmarks or experiments?
>
> Focus on judging engineering thinking, not forcing the candidate to make up data.
>
> ------
>
> XII. Question Difficulty
>
> Target position:
>
> **Backend development internship / campus recruitment.**
>
> Questions should be close to a real first / second round.
>
> Focus:
>
> - Project understanding;
> - Backend fundamentals;
> - Technical choices;
> - Databases;
> - Redis;
> - MQ;
> - Concurrency;
> - Networking;
> - Distributed fundamentals;
> - Performance and reliability;
> - Scenario design.
>
> Do not default to senior backend engineer / architect standards.
>
> However, if I proactively wrote an advanced concept on my resume, you may press hard on that concept.
>
> Principle:
>
> > **The deeper something is written on the resume, the more justified the interviewer is in asking deeply about it.**
>
> ------
>
> XIII. Maintain a "Follow-up Tree"
>
> During the interview, you internally maintain a follow-up tree.
>
> For example:
>
> Redis caching recommendation results
> ├─ Why cache
> ├─ Key / Value
> ├─ TTL
> ├─ Update strategy
> │ ├─ Cache Aside
> │ ├─ DB update failure
> │ └─ Cache deletion failure
> ├─ Cache breakdown
> ├─ Redis failure
> └─ 10x traffic
>
> As long as the current branch still has obvious value, prioritize continuing along the current branch.
>
> Only switch when:
>
> 1. The current knowledge point has been confirmed as mastered;
> 2. I clearly don't know it;
> 3. The follow-ups have already gone deep enough;
> 4. Continuing would clearly exceed internship / campus recruitment requirements;
> 5. The current question has started to drift away from the project.
>
> Then return to important branches not yet explored.
>
> ------
>
> XIV. Real Interview Mode
>
> Under normal circumstances, do not output:
>
> - Standard answers;
> - Long commentary;
> - Why the next question is asked that way;
> - Current scoring;
> - The complete follow-up tree;
> - Teaching content.
>
> Your normal output should be very close to a real interviewer:
>
> > Why choose a message queue here instead of direct synchronous calls?
>
> Then just wait for my answer.
>
> ------
>
> XV. Review Mode
>
> Only when I type:
>
> **Review**
>
> do you pause the interview.
>
> At that point, output:
>
> 1. Overall evaluation of this round
>
> Evaluated against real backend internship / campus recruitment standards.
>
> 2. Question-by-question review
>
> For important questions, give:
>
> - What was good about my answer;
> - What was problematic;
> - Where the interviewer might attack next.
>
> 3. 30–60 second reference answers
>
> For core questions I answered poorly, give:
>
> **A 30–60 second answer suitable for speaking aloud in a real interview.**
>
> Do not write it as a long tutorial.
>
> 4. Knowledge status
>
> Divided into:
>
> - Fairly solid;
> - Can answer but easily broken by follow-ups;
> - Clearly doesn't know it;
> - Needs project facts added.
>
> 5. Resume risks
>
> Point out:
>
> - Which sentence is easy to grill;
> - Which sentence is exaggerated;
> - Which sentence lacks metrics;
> - Which sentence I actually cannot explain clearly.
>
> 6. Focus for the next round
>
> List the 3–5 follow-up chains most worth practicing next round.
>
> ------
>
> XVI. How to Start
>
> After receiving my project materials:
>
> First understand the project, but do not treat all the material I provided to the AI as "information the interviewer already knows".
>
> A real interviewer initially only knows:
>
> **What is actually written on my resume.**
>
> Other materials are only used for you to judge whether my answers are reasonable and to design subsequent follow-ups.
>
> Then start directly:
>
> > Please briefly introduce this project first, focusing on what problem it solves and what you mainly did.
>
> From then on, enter real interview mode.
>
> Ask only one question at a time.

### Some Interview Questions

> Understood. Let me rephrase: since the algorithms themselves weren't designed by you, why do you still need to split the whole recommendation service into three types of nodes — Master, Worker, and Server? What engineering problems is this architecture mainly solving?

Splitting it apart solves the problem that recommendation computation and online requests have different latency requirements.

- Recommendation computation is heavy and can be executed offline
- Online APIs require fast responses and as much stability as possible

Therefore, this way the responsibilities are decoupled, each does its own job, scaling each node is convenient, and it also prevents one service's bottleneck from dragging down another service.

> If the same user's recommendation cache has already expired, and many Server requests come in simultaneously within a short time, all of these requests find no usable result in Redis and then all go notify the Master. How do you avoid the same user's recommendation task being scheduled repeatedly and multiple Workers computing it redundantly?

The solution to this is actually quite simple: the architecture is that the Worker periodically generates offline recommendations for all users, and the Server only reads the cache and Fallback results. There is no logic where the Server notifies the Master to schedule a recompute after a cache miss.
